Welcome to mirror list, hosted at ThFree Co, Russian Federation.

stubhelpers.cpp « vm « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 31692eee21db7c8e6ef30da8c13ef2a5a013d2eb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: stubhelpers.cpp
//

//


#include "common.h"

#include "mlinfo.h"
#include "stubhelpers.h"
#include "jitinterface.h"
#include "dllimport.h"
#include "fieldmarshaler.h"
#include "comdelegate.h"
#include "eventtrace.h"
#include "comdatetime.h"
#include "gcheaputilities.h"
#include "interoputil.h"

#ifdef FEATURE_COMINTEROP
#include <oletls.h>
#include "olecontexthelpers.h"
#include "runtimecallablewrapper.h"
#include "comcallablewrapper.h"
#include "clrtocomcall.h"
#include "cominterfacemarshaler.h"
#endif

#ifdef VERIFY_HEAP

CQuickArray<StubHelpers::ByrefValidationEntry> StubHelpers::s_ByrefValidationEntries;
SIZE_T StubHelpers::s_ByrefValidationIndex = 0;
CrstStatic StubHelpers::s_ByrefValidationLock;

// static
void StubHelpers::Init()
{
    WRAPPER_NO_CONTRACT;
    s_ByrefValidationLock.Init(CrstPinnedByrefValidation);
}

// static
void StubHelpers::ValidateObjectInternal(Object *pObjUNSAFE, BOOL fValidateNextObj)
{
	CONTRACTL
	{
	NOTHROW;
	GC_NOTRIGGER;
	MODE_ANY;
}
	CONTRACTL_END;

	_ASSERTE(GCHeapUtilities::GetGCHeap()->RuntimeStructuresValid());

	// validate the object - there's no need to validate next object's
	// header since we validate the next object explicitly below
	if (pObjUNSAFE)
	{
		pObjUNSAFE->Validate(/*bDeep=*/ TRUE, /*bVerifyNextHeader=*/ FALSE, /*bVerifySyncBlock=*/ TRUE);
	}

	// and the next object as required
	if (fValidateNextObj)
	{
		Object *nextObj = GCHeapUtilities::GetGCHeap()->NextObj(pObjUNSAFE);
		if (nextObj != NULL)
		{
			// Note that the MethodTable of the object (i.e. the pointer at offset 0) can change from
			// g_pFreeObjectMethodTable to NULL, from NULL to <legal-value>, or possibly also from
			// g_pFreeObjectMethodTable to <legal-value> concurrently while executing this function.
			// Once <legal-value> is seen, we believe that the object should pass the Validate check.
			// We have to be careful and read the pointer only once to avoid "phantom reads".
			MethodTable *pMT = VolatileLoad(nextObj->GetMethodTablePtr());
			if (pMT != NULL && pMT != g_pFreeObjectMethodTable)
			{
				// do *not* verify the next object's syncblock - the next object is not guaranteed to
				// be "alive" so the finalizer thread may have already released its syncblock
				nextObj->Validate(/*bDeep=*/ TRUE, /*bVerifyNextHeader=*/ FALSE, /*bVerifySyncBlock=*/ FALSE);
			}
		}
	}
}

// static
MethodDesc *StubHelpers::ResolveInteropMethod(Object *pThisUNSAFE, MethodDesc *pMD)
{
    WRAPPER_NO_CONTRACT;

    if (pMD == NULL && pThisUNSAFE != NULL)
    {
        // if this is a call via delegate, get its Invoke method
        MethodTable *pMT = pThisUNSAFE->GetMethodTable();

        _ASSERTE(pMT->IsDelegate());
        return ((DelegateEEClass *)pMT->GetClass())->GetInvokeMethod();
    }
    return pMD;
}

// static
void StubHelpers::FormatValidationMessage(MethodDesc *pMD, SString &ssErrorString)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    ssErrorString.Append(W("Detected managed heap corruption, likely culprit is interop call through "));

    if (pMD == NULL)
    {
        // the only case where we don't have interop MD is CALLI
        ssErrorString.Append(W("CALLI."));
    }
    else
    {
        ssErrorString.Append(W("method '"));

        StackSString ssClassName;
        pMD->GetMethodTable()->_GetFullyQualifiedNameForClass(ssClassName);

        ssErrorString.Append(ssClassName);
        ssErrorString.Append(NAMESPACE_SEPARATOR_CHAR);
        ssErrorString.AppendUTF8(pMD->GetName());

        ssErrorString.Append(W("'."));
    }
}

// static
void StubHelpers::ProcessByrefValidationList()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    StackSString errorString;
    ByrefValidationEntry entry = { NULL, NULL };

    EX_TRY
    {
        AVInRuntimeImplOkayHolder AVOkay;

        // Process all byref validation entries we have saved since the last GC. Note that EE is suspended at
        // this point so we don't have to take locks and we can safely call code:GCHeap.GetContainingObject.
        for (SIZE_T i = 0; i < s_ByrefValidationIndex; i++)
        {
            entry = s_ByrefValidationEntries[i];

            Object *pObjUNSAFE = GCHeapUtilities::GetGCHeap()->GetContainingObject(entry.pByref, false);
            ValidateObjectInternal(pObjUNSAFE, TRUE);
        }
    }
    EX_CATCH
    {
        EX_TRY
        {
            FormatValidationMessage(entry.pMD, errorString);
            EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, errorString.GetUnicode());
        }
        EX_CATCH
        {
            EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
        }
        EX_END_CATCH_UNREACHABLE;
    }
    EX_END_CATCH_UNREACHABLE;

    s_ByrefValidationIndex = 0;
}

#endif // VERIFY_HEAP

#ifdef FEATURE_COMINTEROP

FORCEINLINE static void GetCOMIPFromRCW_ClearFP()
{
    LIMITED_METHOD_CONTRACT;

#ifdef TARGET_X86
    // As per ASURT 146699 we need to clear FP state before calling to COM
    // the following sequence was previously generated to compiled ML stubs
    // and is faster than _clearfp().
    __asm
    {
        fnstsw ax
        and    eax, 0x3F
        jz     NoNeedToClear
        fnclex
NoNeedToClear:
    }
#endif // TARGET_X86
}

FORCEINLINE static SOleTlsData *GetOrCreateOleTlsData()
{
    LIMITED_METHOD_CONTRACT;

    SOleTlsData *pOleTlsData;
#ifdef TARGET_X86
    // This saves 1 memory instruction over NtCurretTeb()->ReservedForOle because
    // NtCurrentTeb() reads _TEB.NtTib.Self which is the same as what FS:0 already
    // points to.
    pOleTlsData = (SOleTlsData *)(ULONG_PTR)__readfsdword(offsetof(TEB, ReservedForOle));
#else // TARGET_X86
    pOleTlsData = (SOleTlsData *)NtCurrentTeb()->ReservedForOle;
#endif // TARGET_X86
    if (pOleTlsData == NULL)
    {
        pOleTlsData = (SOleTlsData *)SetupOleContext();
    }
    return pOleTlsData;
}

FORCEINLINE static void *GetCOMIPFromRCW_GetTargetNoInterception(IUnknown *pUnk, ComPlusCallInfo *pComInfo)
{
    LIMITED_METHOD_CONTRACT;

    LPVOID *lpVtbl = *(LPVOID **)pUnk;
    return lpVtbl[pComInfo->m_cachedComSlot];
}

FORCEINLINE static IUnknown *GetCOMIPFromRCW_GetIUnknownFromRCWCache(RCW *pRCW, MethodTable * pItfMT)
{
    LIMITED_METHOD_CONTRACT;

    // The code in this helper is the "fast path" that used to be generated directly
    // to compiled ML stubs. The idea is to aim for an efficient RCW cache hit.
    SOleTlsData * pOleTlsData = GetOrCreateOleTlsData();

    // test for free-threaded after testing for context match to optimize for apartment-bound objects
    if (pOleTlsData->pCurrentCtx == pRCW->GetWrapperCtxCookie() || pRCW->IsFreeThreaded())
    {
        for (int i = 0; i < INTERFACE_ENTRY_CACHE_SIZE; i++)
        {
            if (pRCW->m_aInterfaceEntries[i].m_pMT == pItfMT)
            {
                return pRCW->m_aInterfaceEntries[i].m_pUnknown;
            }
        }
    }

    return NULL;
}

// Like GetCOMIPFromRCW_GetIUnknownFromRCWCache but also computes the target. This is a couple of instructions
// faster than GetCOMIPFromRCW_GetIUnknownFromRCWCache + GetCOMIPFromRCW_GetTargetNoInterception.
FORCEINLINE static IUnknown *GetCOMIPFromRCW_GetIUnknownFromRCWCache_NoInterception(RCW *pRCW, ComPlusCallInfo *pComInfo, void **ppTarget)
{
    LIMITED_METHOD_CONTRACT;

    // The code in this helper is the "fast path" that used to be generated directly
    // to compiled ML stubs. The idea is to aim for an efficient RCW cache hit.
    SOleTlsData *pOleTlsData = GetOrCreateOleTlsData();
    MethodTable *pItfMT = pComInfo->m_pInterfaceMT;

    // test for free-threaded after testing for context match to optimize for apartment-bound objects
    if (pOleTlsData->pCurrentCtx == pRCW->GetWrapperCtxCookie() || pRCW->IsFreeThreaded())
    {
        for (int i = 0; i < INTERFACE_ENTRY_CACHE_SIZE; i++)
        {
            if (pRCW->m_aInterfaceEntries[i].m_pMT == pItfMT)
            {
                IUnknown *pUnk = pRCW->m_aInterfaceEntries[i].m_pUnknown;
                _ASSERTE(pUnk != NULL);
                *ppTarget = GetCOMIPFromRCW_GetTargetNoInterception(pUnk, pComInfo);
                return pUnk;
            }
        }
    }

    return NULL;
}

FORCEINLINE static void *GetCOMIPFromRCW_GetTarget(IUnknown *pUnk, ComPlusCallInfo *pComInfo)
{
    LIMITED_METHOD_CONTRACT;


    LPVOID *lpVtbl = *(LPVOID **)pUnk;
    return lpVtbl[pComInfo->m_cachedComSlot];
}

NOINLINE static IUnknown* GetCOMIPFromRCWHelper(LPVOID pFCall, OBJECTREF pSrc, MethodDesc* pMD, void **ppTarget)
{
    FC_INNER_PROLOG(pFCall);

    IUnknown *pIntf = NULL;

    // This is only called in IL stubs which are in CER, so we don't need to worry about ThreadAbort
    HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_NO_THREAD_ABORT|Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, pSrc);

    SafeComHolder<IUnknown> pRetUnk;

    ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD);
    pRetUnk = ComObject::GetComIPFromRCWThrowing(&pSrc, pComInfo->m_pInterfaceMT);

    *ppTarget = GetCOMIPFromRCW_GetTarget(pRetUnk, pComInfo);
    _ASSERTE(*ppTarget != NULL);

    GetCOMIPFromRCW_ClearFP();

    pIntf = pRetUnk.Extract();

    // No exception will be thrown here (including thread abort as it is delayed in IL stubs)
    HELPER_METHOD_FRAME_END();

    FC_INNER_EPILOG();
    return pIntf;
}

//==================================================================================================================
// The GetCOMIPFromRCW helper exists in four specialized versions to optimize CLR->COM perf. Please be careful when
// changing this code as one of these methods is executed as part of every CLR->COM call so every instruction counts.
//==================================================================================================================


#include <optsmallperfcritical.h>

// This helper can handle any CLR->COM call, it supports hosting,
// and clears FP state on x86 for compatibility with VB6.
FCIMPL4(IUnknown*, StubHelpers::GetCOMIPFromRCW, Object* pSrcUNSAFE, MethodDesc* pMD, void **ppTarget, CLR_BOOL* pfNeedsRelease)
{
    CONTRACTL
    {
        FCALL_CHECK;
        PRECONDITION(pMD->IsComPlusCall() || pMD->IsGenericComPlusCall() || pMD->IsEEImpl());
    }
    CONTRACTL_END;

    OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE);
    *pfNeedsRelease = false;

    ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD);
    RCW *pRCW = pSrc->PassiveGetSyncBlock()->GetInteropInfoNoCreate()->GetRawRCW();
    if (pRCW != NULL)
    {

        IUnknown * pUnk = GetCOMIPFromRCW_GetIUnknownFromRCWCache(pRCW, pComInfo->m_pInterfaceMT);
        if (pUnk != NULL)
        {
            *ppTarget = GetCOMIPFromRCW_GetTarget(pUnk, pComInfo);
            if (*ppTarget != NULL)
            {
                GetCOMIPFromRCW_ClearFP();
                return pUnk;
            }
        }
    }

    /* if we didn't find the COM interface pointer in the cache we will have to erect an HMF */
    *pfNeedsRelease = true;
    FC_INNER_RETURN(IUnknown*, GetCOMIPFromRCWHelper(StubHelpers::GetCOMIPFromRCW, pSrc, pMD, ppTarget));
}
FCIMPLEND

#include <optdefault.h>

FCIMPL2(void, StubHelpers::ObjectMarshaler__ConvertToNative, Object* pSrcUNSAFE, VARIANT* pDest)
{
    FCALL_CONTRACT;

    OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE);

    HELPER_METHOD_FRAME_BEGIN_1(pSrc);
    if (pDest->vt & VT_BYREF)
    {
        OleVariant::MarshalOleRefVariantForObject(&pSrc, pDest);
    }
    else
    {
        OleVariant::MarshalOleVariantForObject(&pSrc, pDest);
    }
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

FCIMPL1(Object*, StubHelpers::ObjectMarshaler__ConvertToManaged, VARIANT* pSrc)
{
    FCALL_CONTRACT;

    OBJECTREF retVal = NULL;
    HELPER_METHOD_FRAME_BEGIN_RET_1(retVal);
    // The IL stub is going to call ObjectMarshaler__ClearNative() afterwards.
    // If it doesn't it's a bug in ILObjectMarshaler.
    OleVariant::MarshalObjectForOleVariant(pSrc, &retVal);
    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(retVal);
}
FCIMPLEND

FCIMPL1(void, StubHelpers::ObjectMarshaler__ClearNative, VARIANT* pSrc)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_0();
    SafeVariantClear(pSrc);
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

#include <optsmallperfcritical.h>
FCIMPL4(IUnknown*, StubHelpers::InterfaceMarshaler__ConvertToNative, Object* pObjUNSAFE, MethodTable* pItfMT, MethodTable* pClsMT, DWORD dwFlags)
{
    FCALL_CONTRACT;

    if (NULL == pObjUNSAFE)
    {
        return NULL;
    }

    IUnknown *pIntf = NULL;
    OBJECTREF pObj = ObjectToOBJECTREF(pObjUNSAFE);

    // This is only called in IL stubs which are in CER, so we don't need to worry about ThreadAbort
    HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_NO_THREAD_ABORT, pObj);

    // We're going to be making some COM calls, better initialize COM.
    EnsureComStarted();

    pIntf = MarshalObjectToInterface(&pObj, pItfMT, pClsMT, dwFlags);

    // No exception will be thrown here (including thread abort as it is delayed in IL stubs)
    HELPER_METHOD_FRAME_END();

    return pIntf;
}
FCIMPLEND

FCIMPL4(Object*, StubHelpers::InterfaceMarshaler__ConvertToManaged, IUnknown **ppUnk, MethodTable *pItfMT, MethodTable *pClsMT, DWORD dwFlags)
{
    FCALL_CONTRACT;

    if (NULL == *ppUnk)
    {
        return NULL;
    }

    OBJECTREF pObj = NULL;
    HELPER_METHOD_FRAME_BEGIN_RET_1(pObj);

    // We're going to be making some COM calls, better initialize COM.
    EnsureComStarted();

    UnmarshalObjectFromInterface(&pObj, ppUnk, pItfMT, pClsMT, dwFlags);

    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(pObj);
}
FCIMPLEND

void QCALLTYPE StubHelpers::InterfaceMarshaler__ClearNative(IUnknown * pUnk)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    ULONG cbRef = SafeReleasePreemp(pUnk);
    LogInteropRelease(pUnk, cbRef, "InterfaceMarshalerBase::ClearNative: In/Out release");

    END_QCALL;
}
#include <optdefault.h>

#endif // FEATURE_COMINTEROP

FCIMPL0(void, StubHelpers::SetLastError)
{
    // Make sure this is the first thing we do after returning from the target, as almost everything can cause the last error to get trashed
    DWORD lastError = ::GetLastError();

    FCALL_CONTRACT;

    GetThread()->m_dwLastError = lastError;
}
FCIMPLEND

FCIMPL0(void, StubHelpers::ClearLastError)
{
    FCALL_CONTRACT;

    ::SetLastError(0);
}
FCIMPLEND

NOINLINE static void InitDeclaringTypeHelper(MethodTable *pMT)
{
    FC_INNER_PROLOG(StubHelpers::InitDeclaringType);

    HELPER_METHOD_FRAME_BEGIN_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2);
    pMT->CheckRunClassInitThrowing();
    HELPER_METHOD_FRAME_END();

    FC_INNER_EPILOG();
}

// Triggers cctor of pNMD's declarer, similar to code:JIT_InitClass.
#include <optsmallperfcritical.h>
FCIMPL1(void, StubHelpers::InitDeclaringType, NDirectMethodDesc* pNMD)
{
    FCALL_CONTRACT;

    MethodTable *pMT = pNMD->GetMethodTable();
    _ASSERTE(!pMT->IsClassPreInited());

    if (pMT->GetDomainLocalModule()->IsClassInitialized(pMT))
        return;

    FC_INNER_RETURN_VOID(InitDeclaringTypeHelper(pMT));
}
FCIMPLEND
#include <optdefault.h>

FCIMPL1(void*, StubHelpers::GetNDirectTarget, NDirectMethodDesc* pNMD)
{
    FCALL_CONTRACT;

    FCUnique(0xa2);
    return pNMD->GetNDirectTarget();
}
FCIMPLEND

FCIMPL2(void*, StubHelpers::GetDelegateTarget, DelegateObject *pThisUNSAFE, UINT_PTR *ppStubArg)
{
    PCODE pEntryPoint = NULL;

#ifdef _DEBUG
    BEGIN_PRESERVE_LAST_ERROR;
#endif

    CONTRACTL
    {
        FCALL_CHECK;
        PRECONDITION(CheckPointer(pThisUNSAFE));
    }
    CONTRACTL_END;

    DELEGATEREF orefThis = (DELEGATEREF)ObjectToOBJECTREF(pThisUNSAFE);

#if defined(HOST_64BIT)
    UINT_PTR target = (UINT_PTR)orefThis->GetMethodPtrAux();

    // See code:GenericPInvokeCalliHelper
    // The lowest bit is used to distinguish between MD and target on 64-bit.
    target = (target << 1) | 1;

    // On 64-bit we pass the real target to the stub-for-host through this out argument,
    // see IL code gen in NDirectStubLinker::DoNDirect for details.
    *ppStubArg = target;

#elif defined(TARGET_ARM)
    // @ARMTODO: Nothing to do for ARM yet since we don't support the hosted path.
#endif // HOST_64BIT, TARGET_ARM

    if (pEntryPoint == NULL)
    {
        pEntryPoint = orefThis->GetMethodPtrAux();
    }

#ifdef _DEBUG
    END_PRESERVE_LAST_ERROR;
#endif

    return (PVOID)pEntryPoint;
}
FCIMPLEND



FCIMPL2(void, StubHelpers::ThrowInteropParamException, UINT resID, UINT paramIdx)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_0();
    ::ThrowInteropParamException(resID, paramIdx);
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

#ifdef PROFILING_SUPPORTED
FCIMPL3(SIZE_T, StubHelpers::ProfilerBeginTransitionCallback, SIZE_T pSecretParam, Thread* pThread, Object* unsafe_pThis)
{
    FCALL_CONTRACT;

    // We can get here with an ngen image generated with "/prof",
    // even if the profiler doesn't want to track transitions.
    if (!CORProfilerTrackTransitions())
    {
        return NULL;
    }

    MethodDesc* pRealMD = NULL;

    BEGIN_PRESERVE_LAST_ERROR;

    // We must transition to preemptive GC mode before calling out to the profiler,
    // and the transition requires us to set up a HMF.
    DELEGATEREF dref = (DELEGATEREF)ObjectToOBJECTREF(unsafe_pThis);
    HELPER_METHOD_FRAME_BEGIN_RET_1(dref);

    bool fReverseInterop = false;

    if (NULL == pThread)
    {
        // This is our signal for the reverse interop cases.
        fReverseInterop = true;
        pThread = GET_THREAD();
        // the secret param in this casee is the UMEntryThunk
        pRealMD = ((UMEntryThunk*)pSecretParam)->GetMethod();
    }
    else
    if (pSecretParam == 0)
    {
        // Secret param is null.  This is the calli pinvoke case or the unmanaged delegate case.
        // We have an unmanaged target address but no MD.  For the unmanaged delegate case, we can
        // still retrieve the MD by looking at the "this" object.

        if (dref == NULL)
        {
            // calli pinvoke case
            pRealMD = NULL;
        }
        else
        {
            // unmanaged delegate case
            MethodTable* pMT = dref->GetMethodTable();
            _ASSERTE(pMT->IsDelegate());

            EEClass * pClass = pMT->GetClass();
            pRealMD = ((DelegateEEClass*)pClass)->GetInvokeMethod();
            _ASSERTE(pRealMD);
        }
    }
    else
    {
        // This is either the COM interop or the pinvoke case.
        pRealMD = (MethodDesc*)pSecretParam;
    }

    {
        GCX_PREEMP_THREAD_EXISTS(pThread);

        if (fReverseInterop)
        {
            ProfilerUnmanagedToManagedTransitionMD(pRealMD, COR_PRF_TRANSITION_CALL);
        }
        else
        {
            ProfilerManagedToUnmanagedTransitionMD(pRealMD, COR_PRF_TRANSITION_CALL);
        }
    }

    HELPER_METHOD_FRAME_END();

    END_PRESERVE_LAST_ERROR;

    return (SIZE_T)pRealMD;
}
FCIMPLEND

FCIMPL2(void, StubHelpers::ProfilerEndTransitionCallback, MethodDesc* pRealMD, Thread* pThread)
{
    FCALL_CONTRACT;

    // We can get here with an ngen image generated with "/prof",
    // even if the profiler doesn't want to track transitions.
    if (!CORProfilerTrackTransitions())
    {
        return;
    }

    BEGIN_PRESERVE_LAST_ERROR;

    // We must transition to preemptive GC mode before calling out to the profiler,
    // and the transition requires us to set up a HMF.
    HELPER_METHOD_FRAME_BEGIN_0();
    {
        bool fReverseInterop = false;

        if (NULL == pThread)
        {
            // if pThread is null, we are doing reverse interop
            pThread = GET_THREAD();
            fReverseInterop = true;
        }

        GCX_PREEMP_THREAD_EXISTS(pThread);

        if (fReverseInterop)
        {
            ProfilerManagedToUnmanagedTransitionMD(pRealMD, COR_PRF_TRANSITION_RETURN);
        }
        else
        {
            ProfilerUnmanagedToManagedTransitionMD(pRealMD, COR_PRF_TRANSITION_RETURN);
        }
    }
    HELPER_METHOD_FRAME_END();

    END_PRESERVE_LAST_ERROR;
}
FCIMPLEND
#endif // PROFILING_SUPPORTED

FCIMPL1(Object*, StubHelpers::GetHRExceptionObject, HRESULT hr)
{
    FCALL_CONTRACT;

    OBJECTREF oThrowable = NULL;

    HELPER_METHOD_FRAME_BEGIN_RET_1(oThrowable);
    {
        // GetExceptionForHR uses equivalant logic as COMPlusThrowHR
        GetExceptionForHR(hr, &oThrowable);
    }
    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(oThrowable);
}
FCIMPLEND

#ifdef FEATURE_COMINTEROP
FCIMPL3(Object*, StubHelpers::GetCOMHRExceptionObject, HRESULT hr, MethodDesc *pMD, Object *unsafe_pThis)
{
    FCALL_CONTRACT;

    OBJECTREF oThrowable = NULL;

    // get 'this'
    OBJECTREF oref = ObjectToOBJECTREF(unsafe_pThis);

    HELPER_METHOD_FRAME_BEGIN_RET_2(oref, oThrowable);
    {
        IErrorInfo *pErrInfo = NULL;

        if (pErrInfo == NULL && pMD != NULL)
        {
            // Retrieve the interface method table.
            MethodTable *pItfMT = ComPlusCallInfo::FromMethodDesc(pMD)->m_pInterfaceMT;

            // Get IUnknown pointer for this interface on this object
            IUnknown* pUnk = ComObject::GetComIPFromRCW(&oref, pItfMT);
            if (pUnk != NULL)
            {
                // Check to see if the component supports error information for this interface.
                IID ItfIID;
                pItfMT->GetGuid(&ItfIID, TRUE);
                pErrInfo = GetSupportedErrorInfo(pUnk, ItfIID);

                DWORD cbRef = SafeRelease(pUnk);
                LogInteropRelease(pUnk, cbRef, "IUnk to QI for ISupportsErrorInfo");
            }
        }

        GetExceptionForHR(hr, pErrInfo, &oThrowable);
    }
    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(oThrowable);
}
FCIMPLEND
#endif // FEATURE_COMINTEROP

FCIMPL3(void, StubHelpers::FmtClassUpdateNativeInternal, Object* pObjUNSAFE, BYTE* pbNative, OBJECTREF *ppCleanupWorkListOnStack)
{
    FCALL_CONTRACT;

    OBJECTREF pObj = ObjectToOBJECTREF(pObjUNSAFE);
    HELPER_METHOD_FRAME_BEGIN_1(pObj);

    MethodTable* pMT = pObj->GetMethodTable();

    if (pMT->IsBlittable())
    {
        memcpyNoGCRefs(pbNative, pObj->GetData(), pMT->GetNativeSize());
    }
    else
    {
        MethodDesc* structMarshalStub;

        {
            GCX_PREEMP();
            structMarshalStub = NDirect::CreateStructMarshalILStub(pMT);
        }

        MarshalStructViaILStub(structMarshalStub, pObj->GetData(), pbNative, StructMarshalStubs::MarshalOperation::Marshal, (void**)ppCleanupWorkListOnStack);
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

FCIMPL2(void, StubHelpers::FmtClassUpdateCLRInternal, Object* pObjUNSAFE, BYTE* pbNative)
{
    FCALL_CONTRACT;

    OBJECTREF pObj = ObjectToOBJECTREF(pObjUNSAFE);
    HELPER_METHOD_FRAME_BEGIN_1(pObj);

    MethodTable* pMT = pObj->GetMethodTable();

    if (pMT->IsBlittable())
    {
        memcpyNoGCRefs(pObj->GetData(), pbNative, pMT->GetNativeSize());
    }
    else
    {
        MethodDesc* structMarshalStub;

        {
            GCX_PREEMP();
            structMarshalStub = NDirect::CreateStructMarshalILStub(pMT);
        }

        MarshalStructViaILStub(structMarshalStub, pObj->GetData(), pbNative, StructMarshalStubs::MarshalOperation::Unmarshal);
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

FCIMPL2(void, StubHelpers::LayoutDestroyNativeInternal, Object* pObjUNSAFE, BYTE* pbNative)
{
    FCALL_CONTRACT;

    OBJECTREF pObj = ObjectToOBJECTREF(pObjUNSAFE);
    HELPER_METHOD_FRAME_BEGIN_1(pObj);
    MethodTable* pMT = pObj->GetMethodTable();

    if (!pMT->IsBlittable())
    {
        MethodDesc* structMarshalStub;

        {
            GCX_PREEMP();
            structMarshalStub = NDirect::CreateStructMarshalILStub(pMT);
        }

        MarshalStructViaILStub(structMarshalStub, pObj->GetData(), pbNative, StructMarshalStubs::MarshalOperation::Cleanup);
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

FCIMPL1(Object*, StubHelpers::AllocateInternal, EnregisteredTypeHandle pRegisteredTypeHnd)
{
    FCALL_CONTRACT;

    TypeHandle typeHnd = TypeHandle::FromPtr(pRegisteredTypeHnd);
    OBJECTREF objRet = NULL;
    HELPER_METHOD_FRAME_BEGIN_RET_1(objRet);

    MethodTable* pMT = typeHnd.GetMethodTable();
    objRet = pMT->Allocate();

    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(objRet);
}
FCIMPLEND

FCIMPL3(void, StubHelpers::MarshalToUnmanagedVaListInternal, va_list va, DWORD cbVaListSize, const VARARGS* pArgIterator)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_0();
    VARARGS::MarshalToUnmanagedVaList(va, cbVaListSize, pArgIterator);
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

FCIMPL2(void, StubHelpers::MarshalToManagedVaListInternal, va_list va, VARARGS* pArgIterator)
{
    FCALL_CONTRACT;

    VARARGS::MarshalToManagedVaList(va, pArgIterator);
}
FCIMPLEND

FCIMPL3(void, StubHelpers::ValidateObject, Object *pObjUNSAFE, MethodDesc *pMD, Object *pThisUNSAFE)
{
    FCALL_CONTRACT;

#ifdef VERIFY_HEAP
    HELPER_METHOD_FRAME_BEGIN_0();

    StackSString errorString;
    EX_TRY
    {
        AVInRuntimeImplOkayHolder AVOkay;
		// don't validate the next object if a BGC is in progress.  we can race with background
	    // sweep which could make the next object a Free object underneath us if it's dead.
        ValidateObjectInternal(pObjUNSAFE, !(GCHeapUtilities::GetGCHeap()->IsConcurrentGCInProgress()));
    }
    EX_CATCH
    {
        FormatValidationMessage(ResolveInteropMethod(pThisUNSAFE, pMD), errorString);
        EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, errorString.GetUnicode());
    }
    EX_END_CATCH_UNREACHABLE;

    HELPER_METHOD_FRAME_END();
#else // VERIFY_HEAP
    FCUnique(0xa3);
    UNREACHABLE_MSG("No validation support without VERIFY_HEAP");
#endif // VERIFY_HEAP
}
FCIMPLEND

FCIMPL3(void, StubHelpers::ValidateByref, void *pByref, MethodDesc *pMD, Object *pThisUNSAFE)
{
    FCALL_CONTRACT;

#ifdef VERIFY_HEAP
    // We cannot validate byrefs at this point as code:GCHeap.GetContainingObject could potentially race
    // with allocations on other threads. We'll just remember this byref along with the interop MD and
    // perform the validation on next GC (see code:StubHelpers.ProcessByrefValidationList).

    // Skip byref if is not pointing inside managed heap
    if (!GCHeapUtilities::GetGCHeap()->IsHeapPointer(pByref))
    {
        return;
    }
    ByrefValidationEntry entry;
    entry.pByref = pByref;
    entry.pMD = ResolveInteropMethod(pThisUNSAFE, pMD);

    HELPER_METHOD_FRAME_BEGIN_0();

    SIZE_T NumOfEntries = 0;
    {
        CrstHolder ch(&s_ByrefValidationLock);

        if (s_ByrefValidationIndex >= s_ByrefValidationEntries.Size())
        {
            // The validation list grows as necessary, for simplicity we never shrink it.
            SIZE_T newSize;
            if (!ClrSafeInt<SIZE_T>::multiply(s_ByrefValidationIndex, 2, newSize) ||
                !ClrSafeInt<SIZE_T>::addition(newSize, 1, newSize))
            {
                ThrowHR(COR_E_OVERFLOW);
            }

            s_ByrefValidationEntries.ReSizeThrows(newSize);
            _ASSERTE(s_ByrefValidationIndex < s_ByrefValidationEntries.Size());
        }

        s_ByrefValidationEntries[s_ByrefValidationIndex] = entry;
        NumOfEntries = ++s_ByrefValidationIndex;
    }

    if (NumOfEntries > BYREF_VALIDATION_LIST_MAX_SIZE)
    {
        // if the list is too big, trigger GC now
        GCHeapUtilities::GetGCHeap()->GarbageCollect(0);
    }

    HELPER_METHOD_FRAME_END();
#else // VERIFY_HEAP
    FCUnique(0xa4);
    UNREACHABLE_MSG("No validation support without VERIFY_HEAP");
#endif // VERIFY_HEAP
}
FCIMPLEND

FCIMPL0(void*, StubHelpers::GetStubContext)
{
    FCALL_CONTRACT;

    FCUnique(0xa0);
    UNREACHABLE_MSG_RET("This is a JIT intrinsic!");
}
FCIMPLEND

FCIMPL2(void, StubHelpers::LogPinnedArgument, MethodDesc *target, Object *pinnedArg)
{
    FCALL_CONTRACT;

    SIZE_T managedSize = 0;

    if (pinnedArg != NULL)
    {
        // Can pass null objects to interop, only check the size if the object is valid.
        managedSize = pinnedArg->GetSize();
    }

    if (target != NULL)
    {
        STRESS_LOG3(LF_STUBS, LL_INFO100, "Managed object %#X with size '%#X' pinned for interop to Method [%pM]\n", pinnedArg, managedSize, target);
    }
    else
    {
        STRESS_LOG2(LF_STUBS, LL_INFO100, "Managed object %#X pinned for interop with size '%#X'", pinnedArg, managedSize);
    }
}
FCIMPLEND

#ifdef TARGET_64BIT
FCIMPL0(void*, StubHelpers::GetStubContextAddr)
{
    FCALL_CONTRACT;

    FCUnique(0xa1);
    UNREACHABLE_MSG("This is a JIT intrinsic!");
}
FCIMPLEND
#endif // TARGET_64BIT

FCIMPL1(DWORD, StubHelpers::CalcVaListSize, VARARGS *varargs)
{
    FCALL_CONTRACT;

    return VARARGS::CalcVaListSize(varargs);
}
FCIMPLEND

#ifdef FEATURE_ARRAYSTUB_AS_IL
NOINLINE static void ArrayTypeCheckSlow(Object* element, PtrArray* arr)
{
    FC_INNER_PROLOG(StubHelpers::ArrayTypeCheck);
    HELPER_METHOD_FRAME_BEGIN_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2);

    if (!ObjIsInstanceOf(element, arr->GetArrayElementTypeHandle()))
        COMPlusThrow(kArrayTypeMismatchException);

    HELPER_METHOD_FRAME_END();

    FC_INNER_EPILOG();
}

FCIMPL2(void, StubHelpers::ArrayTypeCheck, Object* element, PtrArray* arr)
{
    FCALL_CONTRACT;

    if (ObjIsInstanceOfCached(element, arr->GetArrayElementTypeHandle()) == TypeHandle::CanCast)
        return;

    FC_INNER_RETURN_VOID(ArrayTypeCheckSlow(element, arr));
}
FCIMPLEND
#endif // FEATURE_ARRAYSTUB_AS_IL

#ifdef FEATURE_MULTICASTSTUB_AS_IL
FCIMPL2(void, StubHelpers::MulticastDebuggerTraceHelper, Object* element, INT32 count)
{
    FCALL_CONTRACT;
    FCUnique(0xa5);
}
FCIMPLEND
#endif // FEATURE_MULTICASTSTUB_AS_IL

FCIMPL0(void*, StubHelpers::NextCallReturnAddress)
{
    FCALL_CONTRACT;
    UNREACHABLE_MSG("This is a JIT intrinsic!");
}
FCIMPLEND