This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
comtoclrcall.cpp
2046 lines (1722 loc) · 68.9 KB
/
comtoclrcall.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: COMtoCLRCall.cpp
//
//
// COM to CLR call support.
//
#include "common.h"
#include "vars.hpp"
#include "clrtypes.h"
#include "stublink.h"
#include "excep.h"
#include "comtoclrcall.h"
#include "cgensys.h"
#include "method.hpp"
#include "siginfo.hpp"
#include "comcallablewrapper.h"
#include "field.h"
#include "security.h"
#include "virtualcallstub.h"
#include "dllimport.h"
#include "mlinfo.h"
#include "dbginterface.h"
#include "mdaassistants.h"
#include "sigbuilder.h"
#include "notifyexternals.h"
#include "comdelegate.h"
#include "finalizerthread.h"
#ifdef _DEBUG
#define FORCEINLINE_NONDEBUG
#else
#define FORCEINLINE_NONDEBUG FORCEINLINE
#endif
#if !defined(DACCESS_COMPILE)
#ifdef _TARGET_X86_
static PCODE g_pGenericComCallStubFields = NULL;
static PCODE g_pGenericComCallStub = NULL;
#endif
UINT64 FieldCallWorker(Thread *pThread, ComMethodFrame* pFrame);
void FieldCallWorkerDebuggerWrapper(Thread *pThread, ComMethodFrame* pFrame);
void FieldCallWorkerBody(Thread *pThread, ComMethodFrame* pFrame);
extern "C" HRESULT STDCALL StubRareDisableHRWorker(Thread *pThread);
#ifndef CROSSGEN_COMPILE
//---------------------------------------------------------
// void SetupGenericStubs()
//
// Throws on failure
//---------------------------------------------------------
static void SetupGenericStubs()
{
STANDARD_VM_CONTRACT;
#ifdef _TARGET_X86_
if ( (g_pGenericComCallStubFields != NULL) && (g_pGenericComCallStub != NULL))
return;
StubHolder<Stub> candidateCall, candidateFields;
// Build each one. If we get a collision on replacement, favor the one that's
// already there. (We have lifetime issues with these, because they are used
// in every VTable without refcounting, so we don't want them to change
// underneath us).
// Allocate all three before setting - if an error occurs, we'll free the
// memory via holder objects and throw.
candidateCall = ComCall::CreateGenericComCallStub(FALSE/*notField*/);
candidateFields = ComCall::CreateGenericComCallStub(TRUE/*Field*/);
if (InterlockedCompareExchangeT<PCODE>(&g_pGenericComCallStub, candidateCall->GetEntryPoint(), 0) == 0)
candidateCall.SuppressRelease();
if (InterlockedCompareExchangeT<PCODE>(&g_pGenericComCallStubFields, candidateFields->GetEntryPoint(), 0) == 0)
candidateFields.SuppressRelease();
#endif // _TARGET_X86_
}
#ifdef PROFILING_SUPPORTED
// The sole purpose of this helper is to transition into preemptive mode
// and then call the profiler transition callbacks. We can't use the GCX_PREEMP
// in a function with SEH (such as COMToCLRWorkerBody()).
NOINLINE
void ProfilerTransitionCallbackHelper(MethodDesc* pMD, Thread* pThread, COR_PRF_TRANSITION_REASON reason)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
SO_TOLERANT;
PRECONDITION(CheckPointer(pMD));
PRECONDITION(CheckPointer(pThread));
PRECONDITION(CORProfilerTrackTransitions());
}
CONTRACTL_END;
GCX_PREEMP_THREAD_EXISTS(pThread);
if (reason == COR_PRF_TRANSITION_CALL)
{
ProfilerUnmanagedToManagedTransitionMD(pMD, COR_PRF_TRANSITION_CALL);
}
else
{
ProfilerManagedToUnmanagedTransitionMD(pMD, COR_PRF_TRANSITION_RETURN);
}
}
#endif // PROFILING_SUPPORTED
// Disable when calling into managed code from a place that fails via HRESULT
extern "C" HRESULT STDCALL StubRareDisableHRWorker(Thread *pThread)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
HRESULT hr = S_OK;
// Do not add a CONTRACT here. We haven't set up SEH. We rely
// on HandleThreadAbort dealing with this situation properly.
// @todo - We need to probe here, but can't introduce destructors etc.
BEGIN_CONTRACT_VIOLATION(SOToleranceViolation);
// 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!
// Check for ShutDown scenario. This happens only when we have initiated shutdown
// and someone is trying to call in after the CLR is suspended. In that case, we
// must either raise an unmanaged exception or return an HRESULT, depending on the
// expectations of our caller.
if (!CanRunManagedCode())
{
hr = E_PROCESS_SHUTDOWN_REENTRY;
}
else
{
// We must do the following in this order, because otherwise we would be constructing
// the exception for the abort without synchronizing with the GC. Also, we have no
// CLR SEH set up, despite the fact that we may throw a ThreadAbortException.
pThread->RareDisablePreemptiveGC();
EX_TRY
{
pThread->HandleThreadAbort();
}
EX_CATCH
{
hr = GET_EXCEPTION()->GetHR();
}
EX_END_CATCH(SwallowAllExceptions);
}
// should always be in coop mode here
_ASSERTE(pThread->PreemptiveGCDisabled());
END_CONTRACT_VIOLATION;
// Note that this code does not handle rare signatures that do not return HRESULT properly
return hr;
}
#ifdef _TARGET_X86_
// defined in i386\asmhelpers.asm
extern "C" ARG_SLOT __fastcall COMToCLRDispatchHelper(
INT_PTR dwArgECX,
INT_PTR dwArgEDX,
PCODE pTarget,
PCODE pSecretArg,
INT_PTR *pInputStack,
WORD wOutputStackSlots,
UINT16 *pOutputStackOffsets,
Frame *pCurFrame);
inline static void InvokeStub(ComCallMethodDesc *pCMD, PCODE pManagedTarget, OBJECTREF orThis, ComMethodFrame *pFrame, Thread *pThread,
UINT64* pRetValOut)
{
LIMITED_METHOD_CONTRACT;
INT_PTR *pInputStack = (INT_PTR *)pFrame->GetPointerToArguments();
PCODE pStubEntryPoint = pCMD->GetILStub();
INT_PTR EDX = (pCMD->m_wSourceSlotEDX == (UINT16)-1 ? NULL : pInputStack[pCMD->m_wSourceSlotEDX]);
ARG_SLOT retVal = 0;
// Managed code is generally "THROWS" and we have no exception handler here that the contract system can
// see. We ensure that we don't get exceptions here by generating a try/catch in the IL stub that covers
// any possible throw points, including all calls within the stub to helpers.
PERMANENT_CONTRACT_VIOLATION(ThrowsViolation, ReasonILStubWillNotThrow);
//
// NOTE! We do not use BEGIN_CALL_TO_MANAGEDEX around this call because we stayed in the SO_TOLERANT
// mode and COMToCLRDispatchHelper is responsible for pushing/popping the CPFH into the FS:0 chain.
//
*pRetValOut = COMToCLRDispatchHelper(
*((INT_PTR *) &orThis), // pArgECX
EDX, // pArgEDX
pStubEntryPoint, // pTarget
pManagedTarget, // pSecretArg
pInputStack, // pInputStack
pCMD->m_wStubStackSlotCount, // wOutputStackSlots
pCMD->m_pwStubStackSlotOffsets, // pOutputStackOffsets
pThread->GetFrame()); // pCurFrame
}
#else // _TARGET_X86_
// defined in amd64\GenericComCallStubs.asm
extern "C" ARG_SLOT COMToCLRDispatchHelper(
DWORD dwStackSlots,
ComMethodFrame *pFrame,
PCODE pTarget,
PCODE pR10,
INT_PTR pDangerousThis);
inline static void InvokeStub(ComCallMethodDesc *pCMD, PCODE pManagedTarget, OBJECTREF orThis, ComMethodFrame *pFrame, Thread *pThread,
UINT64* pRetValOut)
{
WRAPPER_NO_CONTRACT;
ARG_SLOT retVal = 0;
PCODE pStubEntryPoint = pCMD->GetILStub();
INT_PTR dangerousThis;
*(OBJECTREF *)&dangerousThis = orThis;
DWORD dwStackSlots = pCMD->GetNumStackBytes() / STACK_ELEM_SIZE;
// Managed code is generally "THROWS" and we have no exception handler here that the contract system can
// see. We ensure that we don't get exceptions here by generating a try/catch in the IL stub that covers
// any possible throw points, including all calls within the stub to helpers.
PERMANENT_CONTRACT_VIOLATION(ThrowsViolation, ReasonILStubWillNotThrow);
//
// NOTE! We do not use BEGIN_CALL_TO_MANAGEDEX around this call because we stayed in the SO_TOLERANT
// mode and we have no need to push/pop FS:0 on non-x86 Windows platforms.
//
*pRetValOut = COMToCLRDispatchHelper(
dwStackSlots, // dwStackSlots
pFrame, // pFrame
pStubEntryPoint, // pTarget
pManagedTarget, // pSecretArg
dangerousThis); // pDangerousThis
}
#endif // _TARGET_X86_
#if defined(_MSC_VER) && !defined(_DEBUG)
#pragma optimize("t", on) // optimize for speed
#endif
OBJECTREF COMToCLRGetObjectAndTarget_Delegate(ComCallWrapper * pWrap, PCODE * ppManagedTargetOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
DELEGATEREF pDelObj = (DELEGATEREF)pWrap->GetObjectRef();
_ASSERTE(pDelObj->GetMethodTable()->IsDelegate());
// We don't have to go through the Invoke slot because we know what the delegate
// target is. This is the same optimization that reverse P/Invoke stubs do.
*ppManagedTargetOut = (PCODE)pDelObj->GetMethodPtr();
return pDelObj->GetTarget();
}
// returns true on success, false otherwise
NOINLINE // keep the EH tax out of our caller
bool COMToCLRGetObjectAndTarget_WinRTCtor(Thread * pThread, MethodDesc * pRealMD, ComCallMethodDesc * pCMD, PCODE * ppManagedTargetOut,
OBJECTREF* pObjectOut, UINT64* pRetValOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
// Ctor is not virtual and operates on a newly created object.
_ASSERTE(!pCMD->IsVirtual());
*pObjectOut = NULL;
*ppManagedTargetOut = pRealMD->GetSingleCallableAddrOfCode();
MethodTable *pMT = pRealMD->GetMethodTable();
// We should not see a unsealed class here
_ASSERTE(pMT->IsSealed());
// we know for sure that we are allocating a new object
// @TODO: move this object allocation into the IL stub to avoid the try/catch and SO-intolerant region.
bool fSuccess = true;
BEGIN_SO_INTOLERANT_CODE_NOTHROW(pThread, { *pRetValOut = COR_E_STACKOVERFLOW; return false; } );
EX_TRY
{
*pObjectOut = AllocateObject(pMT);
}
EX_CATCH
{
fSuccess = false;
*pRetValOut = SetupErrorInfo(GET_THROWABLE());
}
EX_END_CATCH(SwallowAllExceptions);
END_SO_INTOLERANT_CODE;
return fSuccess;
}
FORCEINLINE_NONDEBUG
OBJECTREF COMToCLRGetObjectAndTarget_Virtual(ComCallWrapper * pWrap, MethodDesc * pRealMD, ComCallMethodDesc * pCMD, PCODE * ppManagedTargetOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
OBJECTREF pObject = pWrap->GetObjectRef();
MethodTable *pMT = pObject->GetMethodTable();
if (pMT->IsTransparentProxy() || pRealMD->IsInterface())
{
// For transparent proxies, we need to call on the interface method desc if
// this method represents an interface method and not an IClassX method.
*ppManagedTargetOut = pCMD->GetCallMethodDesc()->GetSingleCallableAddrOfCode();
}
else if (pWrap->IsAggregated() && pWrap->GetComCallWrapperTemplate()->GetClassType().IsExportedToWinRT())
{
// we know the slot number for this method desc, grab the actual
// address from the vtable for this slot. The slot number should
// remain the same through out the heirarchy.
//
// This is the WinRT inheritance case where we want to always call the method as
// most recently implemented in the managed world.
*ppManagedTargetOut = pWrap->GetComCallWrapperTemplate()->GetClassType().GetMethodTable()->GetSlot(pCMD->GetSlot());
}
else
{
// we know the slot number for this method desc, grab the actual
// address from the vtable for this slot. The slot number should
// remain the same through out the heirarchy.
*ppManagedTargetOut = pMT->GetSlotForVirtual(pCMD->GetSlot());
}
return pObject;
}
FORCEINLINE_NONDEBUG
OBJECTREF COMToCLRGetObjectAndTarget_NonVirtual(ComCallWrapper * pWrap, MethodDesc * pRealMD, ComCallMethodDesc * pCMD, PCODE * ppManagedTargetOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
//NOTE: No need to optimize for stub dispatch since non-virtuals are retrieved quickly.
*ppManagedTargetOut = pRealMD->GetSingleCallableAddrOfCode();
return pWrap->GetObjectRef();
}
FORCEINLINE_NONDEBUG
void COMToCLRInvokeTarget(PCODE pManagedTarget, OBJECTREF pObject, ComCallMethodDesc * pCMD,
ComMethodFrame * pFrame, Thread * pThread, UINT64* pRetValOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
#ifdef DEBUGGING_SUPPORTED
if (CORDebuggerTraceCall())
{
g_pDebugInterface->TraceCall((const BYTE *)pManagedTarget);
}
#endif // DEBUGGING_SUPPORTED
InvokeStub(pCMD, pManagedTarget, pObject, pFrame, pThread, pRetValOut);
}
bool COMToCLRWorkerBody_SecurityCheck(ComCallMethodDesc * pCMD, MethodDesc * pMD, Thread * pThread, UINT64 * pRetValOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
bool result = true;
BEGIN_SO_INTOLERANT_CODE_NOTHROW(pThread, { *pRetValOut = COR_E_STACKOVERFLOW; return false; } );
EX_TRY
{
// Need to check for the presence of a security link demand on the target
// method. If we're hosted inside of an app domain with security, we perform
// the link demand against that app domain's grant set.
Security::CheckLinkDemandAgainstAppDomain(pMD);
if (pCMD->IsEarlyBoundUnsafe())
COMPlusThrow(kSecurityException);
}
EX_CATCH
{
*pRetValOut = SetupErrorInfo(GET_THROWABLE());
result = false;
}
EX_END_CATCH(SwallowAllExceptions);
END_SO_INTOLERANT_CODE;
return result;
}
NOINLINE
void COMToCLRWorkerBody_Rare(Thread * pThread, ComMethodFrame * pFrame, ComCallWrapper * pWrap,
MethodDesc * pRealMD, ComCallMethodDesc * pCMD, DWORD maskedFlags,
UINT64 * pRetValOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
PCODE pManagedTarget;
OBJECTREF pObject;
int fpReturnSize = 0;
if (maskedFlags & enum_NeedsSecurityCheck)
{
if (!COMToCLRWorkerBody_SecurityCheck(pCMD, pRealMD, pThread, pRetValOut))
return;
}
if (maskedFlags & enum_NativeR8Retval)
fpReturnSize = 8;
if (maskedFlags & enum_NativeR4Retval)
fpReturnSize = 4;
maskedFlags &= ~(enum_NeedsSecurityCheck|enum_NativeR4Retval|enum_NativeR8Retval);
CONSISTENCY_CHECK(maskedFlags != ( enum_IsWinRTCtor|enum_IsVirtual));
CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor|enum_IsVirtual));
CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor ));
switch (maskedFlags)
{
case enum_IsDelegateInvoke|enum_IsVirtual:
case enum_IsDelegateInvoke: pObject = COMToCLRGetObjectAndTarget_Delegate(pWrap, &pManagedTarget); break;
case enum_IsVirtual: pObject = COMToCLRGetObjectAndTarget_Virtual(pWrap, pRealMD, pCMD, &pManagedTarget); break;
case 0: pObject = COMToCLRGetObjectAndTarget_NonVirtual(pWrap, pRealMD, pCMD, &pManagedTarget); break;
case enum_IsWinRTCtor:
if (!COMToCLRGetObjectAndTarget_WinRTCtor(pThread, pRealMD, pCMD, &pManagedTarget, &pObject, pRetValOut))
return;
break;
default: UNREACHABLE();
}
COMToCLRInvokeTarget(pManagedTarget, pObject, pCMD, pFrame, pThread, pRetValOut);
if (fpReturnSize != 0)
getFPReturn(fpReturnSize, (INT64*)pRetValOut);
#if defined(PROFILING_SUPPORTED)
// Notify the profiler of the return out of the runtime.
if (CORProfilerTrackTransitions())
{
ProfilerTransitionCallbackHelper(pRealMD, pThread, COR_PRF_TRANSITION_RETURN);
}
#endif // PROFILING_SUPPORTED
return;
}
// This is the factored out body of COMToCLRWorker.
FORCEINLINE_NONDEBUG
void COMToCLRWorkerBody(
Thread * pThread,
ComMethodFrame * pFrame,
ComCallWrapper * pWrap,
UINT64 * pRetValOut)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
ComCallMethodDesc* pCMD = pFrame->GetComCallMethodDesc();
MethodDesc *pRealMD = pCMD->GetMethodDesc();
#if defined(PROFILING_SUPPORTED)
// @TODO: PERF: x86: we are making profiler callbacks in the StubLinker stub as well as here.
// The checks for these callbacks add about 5% to the path length, so we should remove these
// callbacks in the next SxS release because they are redundant.
//
// Notify the profiler of the call into the runtime.
// 32-bit does this callback in the stubs before calling into COMToCLRWorker().
BOOL fNotifyProfiler = CORProfilerTrackTransitions();
if (fNotifyProfiler)
{
ProfilerTransitionCallbackHelper(pRealMD, pThread, COR_PRF_TRANSITION_CALL);
}
#endif // PROFILING_SUPPORTED
LOG((LF_STUBS, LL_INFO1000000, "Calling COMToCLRWorker %s::%s \n", pRealMD->m_pszDebugClassName, pRealMD->m_pszDebugMethodName));
//
// In order to find the managed target code address and target object, we need to know
// what scenario we're in. We do this by switching on the flags of interest. We include
// the NeedsSecurityCheck flag in the calculation even though it's really orthogonal so
// that the faster case--where no security check is needed--can be matched immediately.
//
PCODE pManagedTarget;
OBJECTREF pObject;
DWORD mask = (
enum_NeedsSecurityCheck |
enum_IsDelegateInvoke |
enum_IsWinRTCtor |
enum_IsVirtual |
enum_NativeR4Retval |
enum_NativeR8Retval);
DWORD maskedFlags = pCMD->GetFlags() & mask;
CONSISTENCY_CHECK(maskedFlags != ( enum_IsWinRTCtor|enum_IsVirtual));
CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor|enum_IsVirtual));
CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor ));
switch (maskedFlags)
{
case enum_IsDelegateInvoke|enum_IsVirtual:
case enum_IsDelegateInvoke: pObject = COMToCLRGetObjectAndTarget_Delegate(pWrap, &pManagedTarget); break;
case enum_IsVirtual: pObject = COMToCLRGetObjectAndTarget_Virtual(pWrap, pRealMD, pCMD, &pManagedTarget); break;
case 0: pObject = COMToCLRGetObjectAndTarget_NonVirtual(pWrap, pRealMD, pCMD, &pManagedTarget); break;
case enum_IsWinRTCtor:
if (!COMToCLRGetObjectAndTarget_WinRTCtor(pThread, pRealMD, pCMD, &pManagedTarget, &pObject, pRetValOut))
return;
break;
default:
COMToCLRWorkerBody_Rare(pThread, pFrame, pWrap, pRealMD, pCMD, maskedFlags, pRetValOut);
return;
}
COMToCLRInvokeTarget(pManagedTarget, pObject, pCMD, pFrame, pThread, pRetValOut);
#if defined(PROFILING_SUPPORTED)
// Notify the profiler of the return out of the runtime.
if (fNotifyProfiler)
{
ProfilerTransitionCallbackHelper(pRealMD, pThread, COR_PRF_TRANSITION_RETURN);
}
#endif // PROFILING_SUPPORTED
return;
}
void COMToCLRWorkerBody_SOIntolerant(Thread * pThread, ComMethodFrame * pFrame, ComCallWrapper * pWrap, UINT64 * pRetValOut)
{
STATIC_CONTRACT_THROWS; // THROWS due to END_SO_TOLERANT_CODE
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_SO_INTOLERANT;
BEGIN_SO_TOLERANT_CODE(pThread);
COMToCLRWorkerBody(pThread, pFrame, pWrap, pRetValOut);
END_SO_TOLERANT_CODE;
}
#ifdef _TARGET_X86_
// On x86, we do not want the non-AD-transition path to push an extra FS:0 handler just to
// pop off the ComMethodFrame. On non-x86, we have a personality routine that does this
// (ReverseComUnwindFrameChainHandler), but on x86 we will latch onto the typical CPFH by
// pushing COMPlusFrameHandlerRevCom as the FS:0 handler instead of COMPlusFrameHandler.
// COMPlusFrameHandlerRevCom will look at the Frame chain from the current Frame up to
// the ComMethodFrame and, if it finds a ContextTransitionFrame, it will do nothing.
// Otherwise, it will unwind the Frame chain up to the ComMethodFrame. So here we latch
// onto the AD transition rethrow as the point at which to unwind the Frame chain up to
// the ComMethodFrame.
#define REVERSE_COM_RETHROW_HOOK(pFrame) { ComMethodFrame::DoSecondPassHandlerCleanup(pFrame); }
#else
#define REVERSE_COM_RETHROW_HOOK(pFrame) NULL
#endif // _TARGET_X86_
NOINLINE
void COMToCLRWorkerBodyWithADTransition(
Thread * pThread,
ComMethodFrame * pFrame,
ComCallWrapper * pWrap,
UINT64 * pRetValOut)
{
CONTRACTL
{
NOTHROW; // Although CSE can be thrown
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
BOOL fEnteredDomain = FALSE;
BEGIN_SO_INTOLERANT_CODE_NOTHROW(pThread, { *pRetValOut = COR_E_STACKOVERFLOW; return; } );
EX_TRY
{
bool fNeedToTranslateTAEtoADUE = false;
ADID pTgtDomain = pWrap->GetDomainID();
ENTER_DOMAIN_ID(pTgtDomain)
{
fEnteredDomain = TRUE;
COMToCLRWorkerBody_SOIntolerant(pThread, pFrame, pWrap, pRetValOut);
//
// Below is some logic adapted from Thread::RaiseCrossContextExceptionHelper, which we now
// bypass because the IL stub is catching the ThreadAbortException instead of a proper domain
// transition, where the logic typically resides. This code applies some policy to transform
// the ThreadAbortException into an AppDomainUnloadedException and sets up the HRESULT and
// IErrorInfo accordingly.
//
// If the IL stub caught a TAE...
if (COR_E_THREADABORTED == ((HRESULT)*pRetValOut))
{
// ...first, make sure it was actually an HRESULT return value...
ComCallMethodDesc* pCMD = pFrame->GetComCallMethodDesc();
if (pCMD->IsNativeHResultRetVal())
{
// There may be multiple AD transitions on the stack so the current unload boundary may
// not be the transition frame that was set up to make our AD switch. Detect that by
// comparing the unload boundary's Next with our ComMethodFrame and proceed to translate
// the exception to ADUE only if they match. Otherwise the exception should stay as TAE.
Frame* pUnloadBoundary = pThread->GetUnloadBoundaryFrame();
// ...and we are at an unload boundary with a pending unload...
if ( ( pUnloadBoundary != NULL
&& (pUnloadBoundary->Next() == pFrame
&& pThread->ShouldChangeAbortToUnload(pUnloadBoundary, pUnloadBoundary))
)
// ... or we don't have an unload boundary, but we're otherwise unloading
// this domain from another thread (and we aren't the finalizer)...
|| ( (NULL == pUnloadBoundary)
&& (pThread->GetDomain() == SystemDomain::AppDomainBeingUnloaded())
&& (pThread != SystemDomain::System()->GetUnloadingThread())
&& (pThread != FinalizerThread::GetFinalizerThread())
)
)
{
// ... we take note and then create an ADUE in the domain we're returning to.
fNeedToTranslateTAEtoADUE = true;
}
}
}
}
END_DOMAIN_TRANSITION;
if (fNeedToTranslateTAEtoADUE)
{
EEResourceException ex(kAppDomainUnloadedException, W("Remoting_AppDomainUnloaded_ThreadUnwound"));
OBJECTREF oEx = CLRException::GetThrowableFromException(&ex);
*pRetValOut = SetupErrorInfo(oEx, pFrame->GetComCallMethodDesc());
}
}
EX_CATCH
{
*pRetValOut = SetupErrorInfo(GET_THROWABLE(), pFrame->GetComCallMethodDesc());
}
EX_END_CATCH(
RethrowCorruptingExceptionsExAndHookRethrow(
// If it was thrown at us from the IL stub (which will evaluate the CE policy), then we must
// rethrow it here. But we should swallow exceptions generated by our domain transition.
fEnteredDomain,
REVERSE_COM_RETHROW_HOOK(pThread->GetFrame())
));
END_SO_INTOLERANT_CODE;
}
//------------------------------------------------------------------
// UINT64 __stdcall COMToCLRWorker(Thread *pThread,
// ComMethodFrame* pFrame)
//------------------------------------------------------------------
extern "C" UINT64 __stdcall COMToCLRWorker(Thread *pThread, ComMethodFrame* pFrame)
{
CONTRACTL
{
NOTHROW; // Although CSE can be thrown
GC_TRIGGERS;
#if defined(_TARGET_X86_)
MODE_COOPERATIVE; // X86 sets up COOP in stublinker-generated stub
#else
// This contract is disabled because user code can illegally reenter here through no fault of the
// CLR (i.e. it's a user code bug), so we shouldn't be popping ASSERT dialogs in those cases. Note
// that this reentrancy check is already done by the stublinker-generated stub on x86, so it's OK
// to leave the MODE_ contract enabled on x86.
DISABLED(MODE_PREEMPTIVE);
#endif
SO_TOLERANT;
PRECONDITION(CheckPointer(pFrame));
PRECONDITION(CheckPointer(pThread, NULL_OK));
}
CONTRACTL_END;
UINT64 retVal = 0;
ComCallMethodDesc* pCMD = pFrame->GetComCallMethodDesc();
#if !defined(_TARGET_X86_)
//
// The following code is a transcription of the code that is generated by CreateGenericComCallStub. The
// idea is that we needn't really do this work either in static assembly code nor in dynamically
// generated code since the benefit/cost ratio is low. There are some minor differences in the below
// code, compared to x86. First, the reentrancy and loader lock checks are optionally compiled into the
// stub on x86, depending on whether or not the corresponding MDAs are active at stub-generation time.
// We must check each time at runtime here because we're using static code.
//
HRESULT hr = S_OK;
pThread = GetThread();
if (NULL == pThread)
{
pThread = SetupThreadNoThrow();
if (pThread == NULL)
{
hr = E_OUTOFMEMORY;
goto ErrorExit;
}
}
// Check for an illegal coop->coop transition. We may fire the Reentrancy MDA as a result.
if (pThread->PreemptiveGCDisabled())
HasIllegalReentrancy();
// Attempt to switch GC modes. Note that this is performed manually just like in the x86 stub because
// we have additional checks for shutdown races, MDAs, and thread abort that are performed only when
// g_TrapReturningThreads is set.
pThread->m_fPreemptiveGCDisabled.StoreWithoutBarrier(1);
if (g_TrapReturningThreads.LoadWithoutBarrier())
{
hr = StubRareDisableHRWorker(pThread);
if (S_OK != hr)
goto ErrorExit;
}
#ifdef MDA_SUPPORTED
// Check for and trigger the LoaderLock MDA
if (ShouldCheckLoaderLock())
{
BOOL IsHeld;
if (AuxUlibIsDLLSynchronizationHeld(&IsHeld) && IsHeld)
{
MDA_TRIGGER_ASSISTANT(LoaderLock, ReportViolation(0));
}
}
#endif // MDA_SUPPORTED
// Initialize the frame's VPTR and GS cookie.
*((TADDR*)pFrame) = ComMethodFrame::GetMethodFrameVPtr();
*pFrame->GetGSCookiePtr() = GetProcessGSCookie();
// Link frame into the chain.
pFrame->Push(pThread);
#endif // !_TARGET_X86_
_ASSERTE(pThread);
// At this point we should be in preemptive GC mode (regardless of if it happened
// in the stub or in the worker).
_ASSERTE(pThread->PreemptiveGCDisabled());
{
#ifndef _TARGET_X86_
if (pCMD->IsFieldCall())
{
retVal = FieldCallWorker(pThread, pFrame);
}
else
#endif // !_TARGET_X86_
{
IUnknown **pip = (IUnknown **)pFrame->GetPointerToArguments();
IUnknown *pUnk = (IUnknown *)*pip;
_ASSERTE(pUnk != NULL);
// Obtain the managed 'this' for the call
ComCallWrapper *pWrap = ComCallWrapper::GetWrapperFromIP(pUnk);
_ASSERTE(pWrap != NULL);
if (pWrap->NeedToSwitchDomains(pThread))
{
COMToCLRWorkerBodyWithADTransition(pThread, pFrame, pWrap, &retVal);
}
else
{
// This is the common case that needs to be fast: we are in the right domain and
// all we have to do is marshal the parameters and deliver the call.
COMToCLRWorkerBody(pThread, pFrame, pWrap, &retVal);
}
}
}
#ifndef _TARGET_X86_
// Note: the EH subsystem will handle reseting the frame chain and setting
// the correct GC mode on exception.
pFrame->Pop(pThread);
pThread->EnablePreemptiveGC();
#endif
LOG((LF_STUBS, LL_INFO1000000, "COMToCLRWorker leave\n"));
// The call was successfull. If the native return type is a floating point
// value, then we need to set the floating point registers appropriately.
if (pCMD->IsNativeFloatingPointRetVal()) // single check skips both cases
{
if (pCMD->IsNativeR4RetVal())
setFPReturn(4, retVal);
else
setFPReturn(8, retVal);
}
return retVal;
#ifndef _TARGET_X86_
ErrorExit:
if (pThread->PreemptiveGCDisabled())
pThread->EnablePreemptiveGC();
// The call failed so we need to report an error to the caller.
if (pCMD->IsNativeHResultRetVal())
{
_ASSERTE(FAILED(hr));
retVal = hr;
}
else if (pCMD->IsNativeBoolRetVal())
retVal = 0;
else if (pCMD->IsNativeR4RetVal())
setFPReturn(4, CLR_NAN_32);
else if (pCMD->IsNativeR8RetVal())
setFPReturn(8, CLR_NAN_64);
else
_ASSERTE(pCMD->IsNativeVoidRetVal());
return retVal;
#endif // _TARGET_X86_
}
#if defined(_MSC_VER) && !defined(_DEBUG)
#pragma optimize("", on) // restore settings
#endif
static UINT64 __stdcall FieldCallWorker(Thread *pThread, ComMethodFrame* pFrame)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
ENTRY_POINT;
PRECONDITION(CheckPointer(pThread));
PRECONDITION(CheckPointer(pFrame));
}
CONTRACTL_END;
#ifdef MDA_SUPPORTED
MDA_TRIGGER_ASSISTANT(GcUnmanagedToManaged, TriggerGC());
#endif
LOG((LF_STUBS, LL_INFO1000000, "FieldCallWorker enter\n"));
HRESULT hrRetVal = S_OK;
BEGIN_SO_INTOLERANT_CODE_NOTHROW(pThread, return COR_E_STACKOVERFLOW);
// BEGIN_ENTRYPOINT_NOTHROW_WITH_THREAD(pThread);
IUnknown** pip = (IUnknown **)pFrame->GetPointerToArguments();
IUnknown* pUnk = (IUnknown *)*pip;
_ASSERTE(pUnk != NULL);
ComCallWrapper* pWrap = ComCallWrapper::GetWrapperFromIP(pUnk);
_ASSERTE(pWrap != NULL);
GCX_ASSERT_COOP();
OBJECTREF pThrowable = NULL;
GCPROTECT_BEGIN(pThrowable);
{
if (!pWrap->NeedToSwitchDomains(pThread))
{
// This is the common case that needs to be fast: we are in the right domain and
// all we have to do is marshal the parameters and deliver the call. We still have to
// set up an EX_TRY/EX_CATCH to transform any exceptions that were thrown into
// HRESULTs.
EX_TRY
{
FieldCallWorkerDebuggerWrapper(pThread, pFrame);
}
EX_CATCH
{
pThrowable = GET_THROWABLE();
}
EX_END_CATCH(SwallowAllExceptions);
if (pThrowable != NULL)
{
// Transform the exception into an HRESULT. This also sets up
// an IErrorInfo on the current thread for the exception.
hrRetVal = SetupErrorInfo(pThrowable, pFrame->GetComCallMethodDesc());
pThrowable = NULL;
}
}
else
{
ADID pTgtDomain = pWrap->GetDomainID();
if (!pTgtDomain.m_dwId)
{
hrRetVal = COR_E_APPDOMAINUNLOADED;
}
else
{
// We need a try/catch around the code to enter the domain since entering
// an AppDomain can throw an exception.
EX_TRY
{
ENTER_DOMAIN_ID(pTgtDomain)
{
// Set up a new GC protection frame for any exceptions thrown inside the AppDomain. Do
// this so we can be sure we don't leak an AppDomain-specific object outside the
// lifetime of the AppDomain (which can happen if an AppDomain unload causes us to
// unwind out via a ThreadAbortException).
OBJECTREF pAppDomainThrowable = NULL;
GCPROTECT_BEGIN(pAppDomainThrowable);
{
// We need a try/catch around the call to the worker since we need
// to transform any exceptions into HRESULTs. We want to do this
// inside the AppDomain of the CCW.
EX_TRY
{
FieldCallWorkerDebuggerWrapper(pThread, pFrame);
}
EX_CATCH
{
pAppDomainThrowable = GET_THROWABLE();
}
EX_END_CATCH(RethrowTerminalExceptions);