This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
dllimportcallback.cpp
1562 lines (1245 loc) · 50.9 KB
/
dllimportcallback.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: DllImportCallback.cpp
//
//
#include "common.h"
#include "threads.h"
#include "excep.h"
#include "object.h"
#include "dllimportcallback.h"
#include "mlinfo.h"
#include "comdelegate.h"
#include "ceeload.h"
#include "eeconfig.h"
#include "dbginterface.h"
#include "stubgen.h"
#include "mdaassistants.h"
#include "appdomain.inl"
#ifndef CROSSGEN_COMPILE
struct UM2MThunk_Args
{
UMEntryThunk *pEntryThunk;
void *pAddr;
void *pThunkArgs;
int argLen;
};
EXTERN_C void STDCALL UM2MThunk_WrapperHelper(void *pThunkArgs,
int argLen,
void *pAddr,
UMEntryThunk *pEntryThunk,
Thread *pThread);
#ifdef MDA_SUPPORTED
EXTERN_C void __fastcall CallbackOnCollectedDelegateHelper(UMEntryThunk *pEntryThunk)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
PRECONDITION(CheckPointer(pEntryThunk));
}
CONTRACTL_END;
MdaCallbackOnCollectedDelegate* pProbe = MDA_GET_ASSISTANT(CallbackOnCollectedDelegate);
// This MDA must be active if we generated a call to CallbackOnCollectedDelegateHelper
_ASSERTE(pProbe);
if (pEntryThunk->IsCollected())
{
INSTALL_UNWIND_AND_CONTINUE_HANDLER;
pProbe->ReportViolation(pEntryThunk->GetMethod());
COMPlusThrow(kNullReferenceException);
UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;
}
}
#endif // MDA_SUPPORTED
// This is used as target of callback from DoADCallBack. It sets up the environment and effectively
// calls back into the thunk that needed to switch ADs.
void UM2MThunk_Wrapper(LPVOID ptr) // UM2MThunk_Args
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_SO_INTOLERANT;
UM2MThunk_Args *pArgs = (UM2MThunk_Args *) ptr;
Thread* pThread = GetThread();
BEGIN_CALL_TO_MANAGED();
// return value is saved to pArgs->pThunkArgs
UM2MThunk_WrapperHelper(pArgs->pThunkArgs,
pArgs->argLen,
pArgs->pAddr,
pArgs->pEntryThunk,
pThread);
END_CALL_TO_MANAGED();
}
EXTERN_C void STDCALL UM2MDoADCallBack(UMEntryThunk *pEntryThunk,
void *pAddr,
void *pArgs,
int argLen)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
ENTRY_POINT;
PRECONDITION(CheckPointer(pEntryThunk));
PRECONDITION(CheckPointer(pArgs));
}
CONTRACTL_END;
UM2MThunk_Args args = { pEntryThunk, pAddr, pArgs, argLen };
INSTALL_MANAGED_EXCEPTION_DISPATCHER;
INSTALL_UNWIND_AND_CONTINUE_HANDLER;
{
AppDomainFromIDHolder domain(pEntryThunk->GetDomainId(),FALSE);
domain.ThrowIfUnloaded();
if(!domain->CanReversePInvokeEnter())
COMPlusThrow(kNotSupportedException);
}
GetThread()->DoADCallBack(pEntryThunk->GetDomainId(), UM2MThunk_Wrapper, &args);
UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;
UNINSTALL_MANAGED_EXCEPTION_DISPATCHER;
}
#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
EXTERN_C VOID __cdecl UMThunkStubRareDisable();
EXTERN_C Thread* __stdcall CreateThreadBlockThrow();
// argument stack offsets are multiple of sizeof(SLOT) so we can tag them by OR'ing with 1
static_assert_no_msg((sizeof(SLOT) & 1) == 0);
#define MAKE_BYVAL_STACK_OFFSET(x) (x)
#define MAKE_BYREF_STACK_OFFSET(x) ((x) | 1)
#define IS_BYREF_STACK_OFFSET(x) ((x) & 1)
#define GET_STACK_OFFSET(x) ((x) & ~1)
// -1 means not used
#define UNUSED_STACK_OFFSET (UINT)-1
// static
VOID UMEntryThunk::CompileUMThunkWorker(UMThunkStubInfo *pInfo,
CPUSTUBLINKER *pcpusl,
UINT *psrcofsregs, // NUM_ARGUMENT_REGISTERS elements
UINT *psrcofs, // pInfo->m_cbDstStack/STACK_ELEM_SIZE elements
UINT retbufofs) // the large structure return buffer ptr arg offset (if any)
{
STANDARD_VM_CONTRACT;
CodeLabel* pSetupThreadLabel = pcpusl->NewCodeLabel();
CodeLabel* pRejoinThreadLabel = pcpusl->NewCodeLabel();
CodeLabel* pDisableGCLabel = pcpusl->NewCodeLabel();
CodeLabel* pRejoinGCLabel = pcpusl->NewCodeLabel();
CodeLabel* pDoADCallBackLabel = pcpusl->NewCodeLabel();
CodeLabel* pDoneADCallBackLabel = pcpusl->NewCodeLabel();
CodeLabel* pADCallBackEpilog = pcpusl->NewCodeLabel();
CodeLabel* pDoADCallBackStartLabel = pcpusl->NewAbsoluteCodeLabel();
// We come into this code with UMEntryThunk in EAX
const X86Reg kEAXentryThunk = kEAX;
// For ThisCall, we make it look like a normal stdcall so that
// the rest of the code (like repushing the arguments) does not
// have to worry about it.
if (pInfo->m_wFlags & umtmlThisCall)
{
// pop off the return address into EDX
pcpusl->X86EmitPopReg(kEDX);
if (pInfo->m_wFlags & umtmlThisCallHiddenArg)
{
// exchange ecx ( "this") with the hidden structure return buffer
// xchg ecx, [esp]
pcpusl->X86EmitOp(0x87, kECX, (X86Reg)4 /*ESP*/);
}
// jam ecx (the "this" param onto stack. Now it looks like a normal stdcall.)
pcpusl->X86EmitPushReg(kECX);
// push edx - repush the return address
pcpusl->X86EmitPushReg(kEDX);
}
// Setup the EBP frame
pcpusl->X86EmitPushEBPframe();
// Save EBX
pcpusl->X86EmitPushReg(kEBX);
// Make space for return value - instead of repeatedly doing push eax edx <trash regs> pop edx eax
// we will save the return value once and restore it just before returning.
pcpusl->X86EmitSubEsp(sizeof(PCONTEXT(NULL)->Eax) + sizeof(PCONTEXT(NULL)->Edx));
// Load thread descriptor into ECX
const X86Reg kECXthread = kECX;
// save UMEntryThunk
pcpusl->X86EmitPushReg(kEAXentryThunk);
pcpusl->EmitSetup(pSetupThreadLabel);
pcpusl->X86EmitMovRegReg(kECX, kEBX);
pcpusl->EmitLabel(pRejoinThreadLabel);
// restore UMEntryThunk
pcpusl->X86EmitPopReg(kEAXentryThunk);
#ifdef _DEBUG
// Save incoming registers
pcpusl->X86EmitPushReg(kEAXentryThunk); // UMEntryThunk
pcpusl->X86EmitPushReg(kECXthread); // thread descriptor
pcpusl->X86EmitPushReg(kEAXentryThunk);
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID) LogUMTransition), 4);
// Restore registers
pcpusl->X86EmitPopReg(kECXthread);
pcpusl->X86EmitPopReg(kEAXentryThunk);
#endif
#ifdef PROFILING_SUPPORTED
// Notify profiler of transition into runtime, before we disable preemptive GC
if (CORProfilerTrackTransitions())
{
// Load the methoddesc into EBX (UMEntryThunk->m_pMD)
pcpusl->X86EmitIndexRegLoad(kEBX, kEAXentryThunk, UMEntryThunk::GetOffsetOfMethodDesc());
// Save registers
pcpusl->X86EmitPushReg(kEAXentryThunk); // UMEntryThunk
pcpusl->X86EmitPushReg(kECXthread); // pCurThread
// Push arguments and notify profiler
pcpusl->X86EmitPushImm32(COR_PRF_TRANSITION_CALL); // Reason
pcpusl->X86EmitPushReg(kEBX); // MethodDesc*
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID)ProfilerUnmanagedToManagedTransitionMD), 8);
// Restore registers
pcpusl->X86EmitPopReg(kECXthread);
pcpusl->X86EmitPopReg(kEAXentryThunk);
// Push the MethodDesc* (in EBX) for use by the transition on the way out.
pcpusl->X86EmitPushReg(kEBX);
}
#endif // PROFILING_SUPPORTED
pcpusl->EmitDisable(pDisableGCLabel, TRUE, kECXthread);
pcpusl->EmitLabel(pRejoinGCLabel);
// construct a FrameHandlerExRecord
// push [ECX]Thread.m_pFrame - corresponding to FrameHandlerExRecord::m_pEntryFrame
pcpusl->X86EmitIndexPush(kECXthread, offsetof(Thread, m_pFrame));
// push offset FastNExportExceptHandler
pcpusl->X86EmitPushImm32((INT32)(size_t)FastNExportExceptHandler);
// push fs:[0]
const static BYTE codeSEH1[] = { 0x64, 0xFF, 0x35, 0x0, 0x0, 0x0, 0x0};
pcpusl->EmitBytes(codeSEH1, sizeof(codeSEH1));
// link in the exception frame
// mov dword ptr fs:[0], esp
const static BYTE codeSEH2[] = { 0x64, 0x89, 0x25, 0x0, 0x0, 0x0, 0x0};
pcpusl->EmitBytes(codeSEH2, sizeof(codeSEH2));
// EBX will hold address of start of arguments. Calculate here so the AD switch case can access
// the arguments at their original location rather than re-copying them to the inner frame.
// lea ebx, [ebp + 8]
pcpusl->X86EmitIndexLea(kEBX, kEBP, 8);
// Load pThread->m_pDomain into edx
// mov edx,[ecx + offsetof(Thread, m_pAppDomain)]
pcpusl->X86EmitIndexRegLoad(kEDX, kECXthread, Thread::GetOffsetOfAppDomain());
// Load pThread->m_pAppDomain->m_dwId into edx
// mov edx,[edx + offsetof(AppDomain, m_dwId)]
pcpusl->X86EmitIndexRegLoad(kEDX, kEDX, AppDomain::GetOffsetOfId());
// check if the app domain of the thread matches that of delegate
// cmp edx,[eax + offsetof(UMEntryThunk, m_dwDomainId))]
pcpusl->X86EmitOffsetModRM(0x3b, kEDX, kEAXentryThunk, offsetof(UMEntryThunk, m_dwDomainId));
// jne pWrongAppDomain ; mismatch. This will call back into the stub with the
// correct AppDomain through DoADCallBack
pcpusl->X86EmitCondJump(pDoADCallBackLabel, X86CondCode::kJNE);
//
// ----------------------------------------------------------------------------------------------
//
// From this point on (until noted) we might be executing as the result of calling into the
// runtime in order to switch AppDomain. In order for the following code to function in both
// scenarios it must be careful when making assumptions about the current stack layout (in the AD
// switch case a new inner frame has been pushed which is not identical to the original outer
// frame).
//
// Our guaranteed state at this point is as follows:
// EAX: Pointer to UMEntryThunk
// EBX: Pointer to start of caller's arguments
// ECX: Pointer to current Thread
// EBP: Equals EBX - 8 (no AD switch) or unspecified (AD switch)
//
// Stack:
//
// +-------------------------+
// ESP + 0 | |
//
// | Varies |
//
// | |
// +-------------------------+
// EBX - 20 | Saved Result: EDX/ST(0) |
// +- - - - - - - - - - - - -+
// EBX - 16 | Saved Result: EAX/ST(0) |
// +-------------------------+
// EBX - 12 | Caller's EBX |
// +-------------------------+
// EBX - 8 | Caller's EBP |
// +-------------------------+
// EBX - 4 | Return address |
// +-------------------------+
// EBX + 0 | |
//
// | Caller's arguments |
//
// | |
// +-------------------------+
//
// It's important that the "restart" after an AppDomain switch will skip
// the check for g_TrapReturningThreads. That's because, during shutdown,
// we can only go through the UMThunkStubRareDisable pathway if we have
// not yet pushed a frame. (Once pushed, the frame cannot be popped
// without coordinating with the GC. During shutdown, such coordination
// would deadlock).
pcpusl->EmitLabel(pDoADCallBackStartLabel);
#ifdef MDA_SUPPORTED
if ((pInfo->m_wFlags & umtmlSkipStub) && !(pInfo->m_wFlags & umtmlIsStatic) &&
MDA_GET_ASSISTANT(CallbackOnCollectedDelegate))
{
// save registers
pcpusl->X86EmitPushReg(kEAXentryThunk);
pcpusl->X86EmitPushReg(kECXthread);
// CallbackOnCollectedDelegateHelper is a fast call
pcpusl->X86EmitMovRegReg(kECX, kEAXentryThunk);
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID)CallbackOnCollectedDelegateHelper), 0);
// restore registers
pcpusl->X86EmitPopReg(kECXthread);
pcpusl->X86EmitPopReg(kEAXentryThunk);
}
#endif
// save the thread pointer
pcpusl->X86EmitPushReg(kECXthread);
// reserve the space for call slot
pcpusl->X86EmitSubEsp(4);
// remember stack size for offset computations
INT iStackSizeAtCallSlot = pcpusl->GetStackSize();
if (!(pInfo->m_wFlags & umtmlSkipStub))
{
// save EDI (it's used by the IL stub invocation code)
pcpusl->X86EmitPushReg(kEDI);
}
// repush any stack arguments
int arg = pInfo->m_cbDstStack/STACK_ELEM_SIZE;
while (arg--)
{
if (IS_BYREF_STACK_OFFSET(psrcofs[arg]))
{
// lea ecx, [ebx + ofs]
pcpusl->X86EmitIndexLea(kECX, kEBX, GET_STACK_OFFSET(psrcofs[arg]));
// push ecx
pcpusl->X86EmitPushReg(kECX);
}
else
{
// push dword ptr [ebx + ofs]
pcpusl->X86EmitIndexPush(kEBX, GET_STACK_OFFSET(psrcofs[arg]));
}
}
// load register arguments
int regidx = 0;
#define ARGUMENT_REGISTER(regname) \
if (psrcofsregs[regidx] != UNUSED_STACK_OFFSET) \
{ \
if (IS_BYREF_STACK_OFFSET(psrcofsregs[regidx])) \
{ \
/* lea reg, [ebx + ofs] */ \
pcpusl->X86EmitIndexLea(k##regname, kEBX, GET_STACK_OFFSET(psrcofsregs[regidx])); \
} \
else \
{ \
/* mov reg, [ebx + ofs] */ \
pcpusl->X86EmitIndexRegLoad(k##regname, kEBX, GET_STACK_OFFSET(psrcofsregs[regidx])); \
} \
} \
regidx++;
ENUM_ARGUMENT_REGISTERS_BACKWARD();
#undef ARGUMENT_REGISTER
if (!(pInfo->m_wFlags & umtmlSkipStub))
{
//
// Call the IL stub which will:
// 1) marshal
// 2) call the managed method
// 3) unmarshal
//
// the delegate object is extracted by the stub from UMEntryThunk
_ASSERTE(pInfo->m_wFlags & umtmlIsStatic);
// mov EDI, [EAX + UMEntryThunk.m_pUMThunkMarshInfo]
pcpusl->X86EmitIndexRegLoad(kEDI, kEAXentryThunk, offsetof(UMEntryThunk, m_pUMThunkMarshInfo));
// mov EDI, [EDI + UMThunkMarshInfo.m_pILStub]
pcpusl->X86EmitIndexRegLoad(kEDI, kEDI, UMThunkMarshInfo::GetOffsetOfStub());
// EAX still contains the UMEntryThunk pointer, so we cannot really use SCRATCHREG
// we can use EDI, though
INT iCallSlotOffset = pcpusl->GetStackSize() - iStackSizeAtCallSlot;
// mov [ESP+iCallSlotOffset], EDI
pcpusl->X86EmitIndexRegStore((X86Reg)kESP_Unsafe, iCallSlotOffset, kEDI);
// call [ESP+iCallSlotOffset]
pcpusl->X86EmitOp(0xff, (X86Reg)2, (X86Reg)kESP_Unsafe, iCallSlotOffset);
// Emit a NOP so we know that we can call managed code
INDEBUG(pcpusl->Emit8(X86_INSTR_NOP));
// restore EDI
pcpusl->X86EmitPopReg(kEDI);
}
else if (!(pInfo->m_wFlags & umtmlIsStatic))
{
//
// This is call on delegate
//
// mov THIS, [EAX + UMEntryThunk.m_pObjectHandle]
pcpusl->X86EmitOp(0x8b, THIS_kREG, kEAXentryThunk, offsetof(UMEntryThunk, m_pObjectHandle));
// mov THIS, [THIS]
pcpusl->X86EmitOp(0x8b, THIS_kREG, THIS_kREG);
//
// Inline Delegate.Invoke for perf
//
// mov SCRATCHREG, [THISREG + Delegate.FP] ; Save target stub in register
pcpusl->X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfMethodPtr());
// mov THISREG, [THISREG + Delegate.OR] ; replace "this" pointer
pcpusl->X86EmitIndexRegLoad(THIS_kREG, THIS_kREG, DelegateObject::GetOffsetOfTarget());
INT iCallSlotOffset = pcpusl->GetStackSize() - iStackSizeAtCallSlot;
// mov [ESP+iCallSlotOffset], SCRATCHREG
pcpusl->X86EmitIndexRegStore((X86Reg)kESP_Unsafe,iCallSlotOffset,SCRATCH_REGISTER_X86REG);
// call [ESP+iCallSlotOffset]
pcpusl->X86EmitOp(0xff, (X86Reg)2, (X86Reg)kESP_Unsafe, iCallSlotOffset);
INDEBUG(pcpusl->Emit8(X86_INSTR_NOP)); // Emit a NOP so we know that we can call managed code
}
else
{
//
// Call the managed method
//
INT iCallSlotOffset = pcpusl->GetStackSize() - iStackSizeAtCallSlot;
// mov SCRATCH, [SCRATCH + offsetof(UMEntryThunk.m_pManagedTarget)]
pcpusl->X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, SCRATCH_REGISTER_X86REG, offsetof(UMEntryThunk, m_pManagedTarget));
// mov [ESP+iCallSlotOffset], SCRATCHREG
pcpusl->X86EmitIndexRegStore((X86Reg)kESP_Unsafe, iCallSlotOffset, SCRATCH_REGISTER_X86REG);
// call [ESP+iCallSlotOffset]
pcpusl->X86EmitOp(0xff, (X86Reg)2, (X86Reg)kESP_Unsafe, iCallSlotOffset);
INDEBUG(pcpusl->Emit8(X86_INSTR_NOP)); // Emit a NOP so we know that we can call managed code
}
// skip the call slot
pcpusl->X86EmitAddEsp(4);
// Save the return value to the outer frame
if (pInfo->m_wFlags & umtmlFpu)
{
// save FP return value
// fstp qword ptr [ebx - 0x8 - 0xc]
pcpusl->X86EmitOffsetModRM(0xdd, (X86Reg)3, kEBX, -0x8 /* to outer EBP */ -0xc /* skip saved EBP, EBX */);
}
else
{
// save EDX:EAX
if (retbufofs == UNUSED_STACK_OFFSET)
{
pcpusl->X86EmitIndexRegStore(kEBX, -0x8 /* to outer EBP */ -0x8 /* skip saved EBP, EBX */, kEAX);
pcpusl->X86EmitIndexRegStore(kEBX, -0x8 /* to outer EBP */ -0xc /* skip saved EBP, EBX, EAX */, kEDX);
}
else
{
// pretend that the method returned the ret buf hidden argument
// (the structure ptr); C++ compiler seems to rely on this
// mov dword ptr eax, [ebx + retbufofs]
pcpusl->X86EmitIndexRegLoad(kEAX, kEBX, retbufofs);
// save it as the return value
pcpusl->X86EmitIndexRegStore(kEBX, -0x8 /* to outer EBP */ -0x8 /* skip saved EBP, EBX */, kEAX);
}
}
// restore the thread pointer
pcpusl->X86EmitPopReg(kECXthread);
// Check whether we got here via the switch AD case. We can tell this by looking at whether the
// caller's arguments immediately precede our EBP frame (they will for the non-switch case but
// otherwise we will have pushed several frames in the interim). If we did switch now is the time
// to jump to our inner epilog which will clean up the inner stack frame and return to the runtime
// AD switching code.
// Does EBX (argument pointer) == EBP + 8?
// sub ebx, 8
pcpusl->X86EmitSubReg(kEBX, 8);
// cmp ebx, ebp
pcpusl->X86EmitR2ROp(0x3B, kEBX, kEBP);
// jne pADCallBackEpilog
pcpusl->X86EmitCondJump(pADCallBackEpilog, X86CondCode::kJNE);
//
// Once we reach this point in the code we're back to a single scenario: the outer frame of the
// reverse p/invoke. Either we never had to switch AppDomains or the AD switch code has already
// unwound and returned here to pop off the outer frame.
//
// ----------------------------------------------------------------------------------------------
//
pcpusl->EmitLabel(pDoneADCallBackLabel);
// move byte ptr [ecx + Thread.m_fPreemptiveGCDisabled],0
pcpusl->X86EmitOffsetModRM(0xc6, (X86Reg)0, kECXthread, Thread::GetOffsetOfGCFlag());
pcpusl->Emit8(0);
CodeLabel *pRareEnable, *pEnableRejoin;
pRareEnable = pcpusl->NewCodeLabel();
pEnableRejoin = pcpusl->NewCodeLabel();
// test byte ptr [ecx + Thread.m_State], TS_CatchAtSafePoint
pcpusl->X86EmitOffsetModRM(0xf6, (X86Reg)0, kECXthread, Thread::GetOffsetOfState());
pcpusl->Emit8(Thread::TS_CatchAtSafePoint);
pcpusl->X86EmitCondJump(pRareEnable,X86CondCode::kJNZ);
pcpusl->EmitLabel(pEnableRejoin);
// *** unhook SEH frame
// mov edx,[esp] ;;pointer to the next exception record
pcpusl->X86EmitEspOffset(0x8B, kEDX, 0);
// mov dword ptr fs:[0], edx
static const BYTE codeSEH[] = { 0x64, 0x89, 0x15, 0x0, 0x0, 0x0, 0x0 };
pcpusl->EmitBytes(codeSEH, sizeof(codeSEH));
// deallocate SEH frame
pcpusl->X86EmitAddEsp(sizeof(FrameHandlerExRecord));
#ifdef PROFILING_SUPPORTED
if (CORProfilerTrackTransitions())
{
// Load the MethodDesc* we pushed on the entry transition into EBX.
pcpusl->X86EmitPopReg(kEBX);
// Save registers
pcpusl->X86EmitPushReg(kECX);
// Push arguments and notify profiler
pcpusl->X86EmitPushImm32(COR_PRF_TRANSITION_RETURN); // Reason
pcpusl->X86EmitPushReg(kEBX); // MethodDesc*
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID)ProfilerManagedToUnmanagedTransitionMD), 8);
// Restore registers
pcpusl->X86EmitPopReg(kECX);
}
#endif // PROFILING_SUPPORTED
// Load the saved return value
if (pInfo->m_wFlags & umtmlFpu)
{
// fld qword ptr [esp]
pcpusl->Emit8(0xdd);
pcpusl->Emit16(0x2404);
pcpusl->X86EmitAddEsp(8);
}
else
{
pcpusl->X86EmitPopReg(kEDX);
pcpusl->X86EmitPopReg(kEAX);
}
// Restore EBX, which was saved in prolog
pcpusl->X86EmitPopReg(kEBX);
pcpusl->X86EmitPopReg(kEBP);
//retn n
pcpusl->X86EmitReturn(pInfo->m_cbRetPop);
//-------------------------------------------------------------
// coming here if the thread is not set up yet
//
pcpusl->EmitLabel(pSetupThreadLabel);
// call CreateThreadBlock
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID) CreateThreadBlockThrow), 0);
// mov ecx,eax
pcpusl->Emit16(0xc189);
// jump back into the main code path
pcpusl->X86EmitNearJump(pRejoinThreadLabel);
//-------------------------------------------------------------
// coming here if g_TrapReturningThreads was true
//
pcpusl->EmitLabel(pDisableGCLabel);
// call UMThunkStubRareDisable. This may throw if we are not allowed
// to enter. Note that we have not set up our SEH yet (deliberately).
// This is important to handle the case where we cannot enter the CLR
// during shutdown and cannot coordinate with the GC because of
// deadlocks.
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID) UMThunkStubRareDisable), 0);
// jump back into the main code path
pcpusl->X86EmitNearJump(pRejoinGCLabel);
//-------------------------------------------------------------
// coming here if appdomain didn't match
//
pcpusl->EmitLabel(pDoADCallBackLabel);
// we will call DoADCallBack which calls into managed code to switch ADs and then calls us
// back. So when come in the second time the ADs will match and just keep processing.
// So we need to setup the parms to pass to DoADCallBack one of which is an address inside
// the stub that will branch back to the top of the stub to start again. Need to setup
// the parms etc so that when we return from the 2nd call we pop things properly.
// save thread pointer
pcpusl->X86EmitPushReg(kECXthread);
// push values for UM2MThunk_Args
// Move address of args (EBX) into EDX since some paths below use EBX.
pcpusl->X86EmitMovRegReg(kEDX, kEBX);
// size of args
pcpusl->X86EmitPushImm32(pInfo->m_cbSrcStack);
// address of args
pcpusl->X86EmitPushReg(kEDX);
// addr to call
pcpusl->X86EmitPushImm32(*pDoADCallBackStartLabel);
// UMEntryThunk
pcpusl->X86EmitPushReg(kEAXentryThunk);
// call UM2MDoADCallBack
pcpusl->X86EmitCall(pcpusl->NewExternalCodeLabel((LPVOID) UM2MDoADCallBack), 8);
// We need to clear the thread off the top of the stack and place it in ECX. Two birds with one stone.
pcpusl->X86EmitPopReg(kECX);
// Re-join the original stub to perform the last parts of the epilog.
pcpusl->X86EmitNearJump(pDoneADCallBackLabel);
//-------------------------------------------------------------
// Coming here for rare case when enabling GC pre-emptive mode
//
pcpusl->EmitLabel(pRareEnable);
// Thread object is expected to be in EBX. So first save caller's EBX
pcpusl->X86EmitPushReg(kEBX);
// mov ebx, ecx
pcpusl->X86EmitMovRegReg(kEBX, kECXthread);
pcpusl->EmitRareEnable(NULL);
// restore ebx
pcpusl->X86EmitPopReg(kEBX);
// return to mainline of function
pcpusl->X86EmitNearJump(pEnableRejoin);
//-------------------------------------------------------------
// Coming here when we switched AppDomain and have successfully called the target. We must return
// into the runtime code (which will eventually unwind the AD transition and return us to the
// mainline stub in order to run the outer epilog).
//
pcpusl->EmitLabel(pADCallBackEpilog);
pcpusl->X86EmitReturn(0);
}
// Compiles an unmanaged to managed thunk for the given signature.
Stub *UMThunkMarshInfo::CompileNExportThunk(LoaderHeap *pLoaderHeap, PInvokeStaticSigInfo* pSigInfo, MetaSig *pMetaSig, BOOL fNoStub)
{
STANDARD_VM_CONTRACT;
// stub is always static
BOOL fIsStatic = (fNoStub ? pSigInfo->IsStatic() : TRUE);
ArgIterator argit(pMetaSig);
UINT nStackBytes = argit.SizeOfArgStack();
_ASSERTE((nStackBytes % STACK_ELEM_SIZE) == 0);
// size of stack passed to us from unmanaged, may be bigger that nStackBytes if there are
// parameters with copy constructors where we perform value-to-reference transformation
UINT nStackBytesIncoming = nStackBytes;
UINT *psrcofs = (UINT *)_alloca((nStackBytes / STACK_ELEM_SIZE) * sizeof(UINT));
UINT psrcofsregs[NUM_ARGUMENT_REGISTERS];
UINT retbufofs = UNUSED_STACK_OFFSET;
for (int i = 0; i < NUM_ARGUMENT_REGISTERS; i++)
psrcofsregs[i] = UNUSED_STACK_OFFSET;
UINT nNumArgs = pMetaSig->NumFixedArgs();
UINT nOffset = 0;
int numRegistersUsed = 0;
int numStackSlotsIndex = nStackBytes / STACK_ELEM_SIZE;
// process this
if (!fIsStatic)
{
// just reserve ECX, instance target is special-cased in the thunk compiler
numRegistersUsed++;
}
// process the return buffer parameter
if (argit.HasRetBuffArg())
{
numRegistersUsed++;
_ASSERTE(numRegistersUsed - 1 < NUM_ARGUMENT_REGISTERS);
psrcofsregs[NUM_ARGUMENT_REGISTERS - numRegistersUsed] = nOffset;
retbufofs = nOffset;
nOffset += StackElemSize(sizeof(LPVOID));
}
// process ordinary parameters
for (DWORD i = nNumArgs; i > 0; i--)
{
TypeHandle thValueType;
CorElementType type = pMetaSig->NextArgNormalized(&thValueType);
UINT cbSize = MetaSig::GetElemSize(type, thValueType);
BOOL fPassPointer = FALSE;
if (!fNoStub && type == ELEMENT_TYPE_PTR)
{
// this is a copy-constructed argument - get its size
TypeHandle thPtr = pMetaSig->GetLastTypeHandleThrowing();
_ASSERTE(thPtr.IsPointer());
cbSize = thPtr.AsTypeDesc()->GetTypeParam().GetSize();
// the incoming stack may be bigger that the outgoing (IL stub) stack
nStackBytesIncoming += (StackElemSize(cbSize) - StackElemSize(sizeof(LPVOID)));
fPassPointer = TRUE;
}
if (ArgIterator::IsArgumentInRegister(&numRegistersUsed, type))
{
_ASSERTE(numRegistersUsed - 1 < NUM_ARGUMENT_REGISTERS);
psrcofsregs[NUM_ARGUMENT_REGISTERS - numRegistersUsed] =
(fPassPointer ?
MAKE_BYREF_STACK_OFFSET(nOffset) : // the register will get pointer to the incoming stack slot
MAKE_BYVAL_STACK_OFFSET(nOffset)); // the register will get the incoming stack slot
}
else if (fPassPointer)
{
// the stack slot will get pointer to the incoming stack slot
psrcofs[--numStackSlotsIndex] = MAKE_BYREF_STACK_OFFSET(nOffset);
}
else
{
// stack slots will get incoming stack slots (we may need more stack slots for larger parameters)
for (UINT nSlotOfs = StackElemSize(cbSize); nSlotOfs > 0; nSlotOfs -= STACK_ELEM_SIZE)
{
// note the reverse order here which is necessary to maintain
// the original layout of the structure (it'll be reversed once
// more when repushing)
psrcofs[--numStackSlotsIndex] = MAKE_BYVAL_STACK_OFFSET(nOffset + nSlotOfs - STACK_ELEM_SIZE);
}
}
nOffset += StackElemSize(cbSize);
}
_ASSERTE(numStackSlotsIndex == 0);
UINT cbActualArgSize = nStackBytesIncoming + (numRegistersUsed * STACK_ELEM_SIZE);
if (!fIsStatic)
{
// do not count THIS
cbActualArgSize -= StackElemSize(sizeof(LPVOID));
}
m_cbActualArgSize = cbActualArgSize;
m_callConv = static_cast<UINT16>(pSigInfo->GetCallConv());
UMThunkStubInfo stubInfo;
memset(&stubInfo, 0, sizeof(stubInfo));
if (!FitsInU2(m_cbActualArgSize))
COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX);
stubInfo.m_cbSrcStack = static_cast<UINT16>(m_cbActualArgSize);
stubInfo.m_cbDstStack = nStackBytes;
if (pSigInfo->GetCallConv() == pmCallConvCdecl)
{
// caller pop
m_cbRetPop = 0;
}
else
{
// callee pop
m_cbRetPop = static_cast<UINT16>(m_cbActualArgSize);
if (pSigInfo->GetCallConv() == pmCallConvThiscall)
{
stubInfo.m_wFlags |= umtmlThisCall;
if (argit.HasRetBuffArg())
{
stubInfo.m_wFlags |= umtmlThisCallHiddenArg;
}
}
}
stubInfo.m_cbRetPop = m_cbRetPop;
if (fIsStatic) stubInfo.m_wFlags |= umtmlIsStatic;
if (fNoStub) stubInfo.m_wFlags |= umtmlSkipStub;
if (pMetaSig->HasFPReturn()) stubInfo.m_wFlags |= umtmlFpu;
CPUSTUBLINKER cpusl;
CPUSTUBLINKER *pcpusl = &cpusl;
// call the worker to emit the actual thunk
UMEntryThunk::CompileUMThunkWorker(&stubInfo, pcpusl, psrcofsregs, psrcofs, retbufofs);
return pcpusl->Link(pLoaderHeap);
}
#else // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
PCODE UMThunkMarshInfo::GetExecStubEntryPoint()
{
LIMITED_METHOD_CONTRACT;
return GetEEFuncEntryPoint(UMThunkStub);
}
#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
UMEntryThunkCache::UMEntryThunkCache(AppDomain *pDomain) :
m_crst(CrstUMEntryThunkCache),
m_pDomain(pDomain)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(pDomain != NULL);
}
UMEntryThunkCache::~UMEntryThunkCache()
{
WRAPPER_NO_CONTRACT;
for (SHash<ThunkSHashTraits>::Iterator i = m_hash.Begin(); i != m_hash.End(); i++)
{
// UMEntryThunks in this cache own UMThunkMarshInfo in 1-1 fashion
DestroyMarshInfo(i->m_pThunk->GetUMThunkMarshInfo());
UMEntryThunk::FreeUMEntryThunk(i->m_pThunk);
}
}
UMEntryThunk *UMEntryThunkCache::GetUMEntryThunk(MethodDesc *pMD)
{
CONTRACT (UMEntryThunk *)
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
UMEntryThunk *pThunk;
CrstHolder ch(&m_crst);
const CacheElement *pElement = m_hash.LookupPtr(pMD);
if (pElement != NULL)
{
pThunk = pElement->m_pThunk;
}
else
{
// cache miss -> create a new thunk
pThunk = UMEntryThunk::CreateUMEntryThunk();
Holder<UMEntryThunk *, DoNothing, UMEntryThunk::FreeUMEntryThunk> umHolder;
umHolder.Assign(pThunk);
UMThunkMarshInfo *pMarshInfo = (UMThunkMarshInfo *)(void *)(m_pDomain->GetStubHeap()->AllocMem(S_SIZE_T(sizeof(UMThunkMarshInfo))));
Holder<UMThunkMarshInfo *, DoNothing, UMEntryThunkCache::DestroyMarshInfo> miHolder;
miHolder.Assign(pMarshInfo);
pMarshInfo->LoadTimeInit(pMD);
pThunk->LoadTimeInit(NULL, NULL, pMarshInfo, pMD, m_pDomain->GetId());
// add it to the cache
CacheElement element;
element.m_pMD = pMD;
element.m_pThunk = pThunk;
m_hash.Add(element);
miHolder.SuppressRelease();
umHolder.SuppressRelease();
}
RETURN pThunk;
}
// FailFast if a native callable method invoked directly from managed code.
// UMThunkStub.asm check the mode and call this function to failfast.
extern "C" VOID STDCALL ReversePInvokeBadTransition()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
// Fail
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(
COR_E_EXECUTIONENGINE,
W("Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code.")
);
}
// Disable from a place that is calling into managed code via a UMEntryThunk.
extern "C" VOID STDCALL UMThunkStubRareDisableWorker(Thread *pThread, UMEntryThunk *pUMEntryThunk)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
// Do not add a CONTRACT here. We haven't set up SEH. We rely
// on HandleThreadAbort and COMPlusThrowBoot dealing with this situation properly.
// WARNING!!!!
// when we start executing here, we are actually in cooperative mode. But we
// haven't synchronized with the barrier to reentry yet. So we are in a highly
// dangerous mode. If we call managed code, we will potentially be active in
// the GC heap, even as GC's are occuring!