This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
reflectioninvocation.cpp
3165 lines (2544 loc) · 104 KB
/
reflectioninvocation.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.
//
//
#include "common.h"
#include "reflectioninvocation.h"
#include "invokeutil.h"
#include "object.h"
#include "class.h"
#include "method.hpp"
#include "typehandle.h"
#include "field.h"
#include "eeconfig.h"
#include "vars.hpp"
#include "jitinterface.h"
#include "contractimpl.h"
#include "virtualcallstub.h"
#include "comdelegate.h"
#include "generics.h"
#ifdef FEATURE_COMINTEROP
#include "interoputil.h"
#include "runtimecallablewrapper.h"
#endif
#include "dbginterface.h"
#include "argdestination.h"
/**************************************************************************/
/* if the type handle 'th' is a byref to a nullable type, return the
type handle to the nullable type in the byref. Otherwise return
the null type handle */
static TypeHandle NullableTypeOfByref(TypeHandle th) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (th.GetVerifierCorElementType() != ELEMENT_TYPE_BYREF)
return TypeHandle();
TypeHandle subType = th.AsTypeDesc()->GetTypeParam();
if (!Nullable::IsNullableType(subType))
return TypeHandle();
return subType;
}
static void TryCallMethodWorker(MethodDescCallSite* pMethodCallSite, ARG_SLOT* args, Frame* pDebuggerCatchFrame)
{
// Use static contracts b/c we have SEH.
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_ANY;
struct Param: public NotifyOfCHFFilterWrapperParam
{
MethodDescCallSite * pMethodCallSite;
ARG_SLOT* args;
} param;
param.pFrame = pDebuggerCatchFrame;
param.pMethodCallSite = pMethodCallSite;
param.args = args;
PAL_TRY(Param *, pParam, ¶m)
{
pParam->pMethodCallSite->CallWithValueTypes(pParam->args);
}
PAL_EXCEPT_FILTER(NotifyOfCHFFilterWrapper)
{
// Should never reach here b/c handler should always continue search.
_ASSERTE(false);
}
PAL_ENDTRY
}
// Warning: This method has subtle differences from CallDescrWorkerReflectionWrapper
// In particular that one captures watson bucket data and corrupting exception severity,
// then transfers that data to the newly produced TargetInvocationException. This one
// doesn't take those same steps.
//
static void TryCallMethod(MethodDescCallSite* pMethodCallSite, ARG_SLOT* args, bool wrapExceptions) {
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (wrapExceptions)
{
OBJECTREF ppException = NULL;
GCPROTECT_BEGIN(ppException);
// The sole purpose of having this frame is to tell the debugger that we have a catch handler here
// which may swallow managed exceptions. The debugger needs this in order to send a
// CatchHandlerFound (CHF) notification.
FrameWithCookie<DebuggerU2MCatchHandlerFrame> catchFrame;
EX_TRY{
TryCallMethodWorker(pMethodCallSite, args, &catchFrame);
}
EX_CATCH{
ppException = GET_THROWABLE();
_ASSERTE(ppException);
}
EX_END_CATCH(RethrowTransientExceptions)
catchFrame.Pop();
// It is important to re-throw outside the catch block because re-throwing will invoke
// the jitter and managed code and will cause us to use more than the backout stack limit.
if (ppException != NULL)
{
// If we get here we need to throw an TargetInvocationException
OBJECTREF except = InvokeUtil::CreateTargetExcept(&ppException);
COMPlusThrow(except);
}
GCPROTECT_END();
}
else
{
pMethodCallSite->CallWithValueTypes(args);
}
}
FCIMPL5(Object*, RuntimeFieldHandle::GetValue, ReflectFieldObject *pFieldUNSAFE, Object *instanceUNSAFE, ReflectClassBaseObject *pFieldTypeUNSAFE, ReflectClassBaseObject *pDeclaringTypeUNSAFE, CLR_BOOL *pDomainInitialized) {
CONTRACTL {
FCALL_CHECK;
}
CONTRACTL_END;
struct _gc
{
OBJECTREF target;
REFLECTCLASSBASEREF pFieldType;
REFLECTCLASSBASEREF pDeclaringType;
REFLECTFIELDREF refField;
}gc;
gc.target = ObjectToOBJECTREF(instanceUNSAFE);
gc.pFieldType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pFieldTypeUNSAFE);
gc.pDeclaringType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pDeclaringTypeUNSAFE);
gc.refField = (REFLECTFIELDREF)ObjectToOBJECTREF(pFieldUNSAFE);
if ((gc.pFieldType == NULL) || (gc.refField == NULL))
FCThrowRes(kArgumentNullException, W("Arg_InvalidHandle"));
TypeHandle fieldType = gc.pFieldType->GetType();
TypeHandle declaringType = (gc.pDeclaringType != NULL) ? gc.pDeclaringType->GetType() : TypeHandle();
Assembly *pAssem;
if (declaringType.IsNull())
{
// global field
pAssem = gc.refField->GetField()->GetModule()->GetAssembly();
}
else
{
pAssem = declaringType.GetAssembly();
}
OBJECTREF rv = NULL; // not protected
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
// There can be no GC after this until the Object is returned.
rv = InvokeUtil::GetFieldValue(gc.refField->GetField(), fieldType, &gc.target, declaringType, pDomainInitialized);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(rv);
}
FCIMPLEND
FCIMPL2(FC_BOOL_RET, ReflectionInvocation::CanValueSpecialCast, ReflectClassBaseObject *pValueTypeUNSAFE, ReflectClassBaseObject *pTargetTypeUNSAFE) {
CONTRACTL {
FCALL_CHECK;
PRECONDITION(CheckPointer(pValueTypeUNSAFE));
PRECONDITION(CheckPointer(pTargetTypeUNSAFE));
}
CONTRACTL_END;
REFLECTCLASSBASEREF refValueType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pValueTypeUNSAFE);
REFLECTCLASSBASEREF refTargetType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pTargetTypeUNSAFE);
TypeHandle valueType = refValueType->GetType();
TypeHandle targetType = refTargetType->GetType();
// we are here only if the target type is a primitive, an enum or a pointer
CorElementType targetCorElement = targetType.GetVerifierCorElementType();
BOOL ret = TRUE;
HELPER_METHOD_FRAME_BEGIN_RET_2(refValueType, refTargetType);
// the field type is a pointer
if (targetCorElement == ELEMENT_TYPE_PTR || targetCorElement == ELEMENT_TYPE_FNPTR) {
// the object must be an IntPtr or a System.Reflection.Pointer
if (valueType == TypeHandle(MscorlibBinder::GetClass(CLASS__INTPTR))) {
//
// it's an IntPtr, it's good.
}
//
// it's a System.Reflection.Pointer object
// void* assigns to any pointer. Otherwise the type of the pointer must match
else if (!InvokeUtil::IsVoidPtr(targetType)) {
if (!valueType.CanCastTo(targetType))
ret = FALSE;
}
} else {
// the field type is an enum or a primitive. To have any chance of assignement the object type must
// be an enum or primitive as well.
// So get the internal cor element and that must be the same or widen
CorElementType valueCorElement = valueType.GetVerifierCorElementType();
if (InvokeUtil::IsPrimitiveType(valueCorElement))
ret = (InvokeUtil::CanPrimitiveWiden(targetCorElement, valueCorElement)) ? TRUE : FALSE;
else
ret = FALSE;
}
HELPER_METHOD_FRAME_END();
FC_RETURN_BOOL(ret);
}
FCIMPLEND
FCIMPL3(Object*, ReflectionInvocation::AllocateValueType, ReflectClassBaseObject *pTargetTypeUNSAFE, Object *valueUNSAFE, CLR_BOOL fForceTypeChange) {
CONTRACTL {
FCALL_CHECK;
PRECONDITION(CheckPointer(pTargetTypeUNSAFE));
PRECONDITION(CheckPointer(valueUNSAFE, NULL_OK));
}
CONTRACTL_END;
struct _gc
{
REFLECTCLASSBASEREF refTargetType;
OBJECTREF value;
OBJECTREF obj;
}gc;
gc.value = ObjectToOBJECTREF(valueUNSAFE);
gc.obj = gc.value;
gc.refTargetType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pTargetTypeUNSAFE);
TypeHandle targetType = gc.refTargetType->GetType();
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
CorElementType targetElementType = targetType.GetSignatureCorElementType();
if (InvokeUtil::IsPrimitiveType(targetElementType) || targetElementType == ELEMENT_TYPE_VALUETYPE)
{
MethodTable* allocMT = targetType.AsMethodTable();
if (gc.value != NULL)
{
// ignore the type of the incoming box if fForceTypeChange is set
// and the target type is not nullable
if (!fForceTypeChange || Nullable::IsNullableType(targetType))
allocMT = gc.value->GetMethodTable();
}
// for null Nullable<T> we don't want a default value being created.
// just allow the null value to be passed, as it will be converted to
// a true nullable
if (!(gc.value == NULL && Nullable::IsNullableType(targetType)))
{
// boxed value type are 'read-only' in the sence that you can't
// only the implementor of the value type can expose mutators.
// To insure byrefs don't mutate value classes in place, we make
// a copy (and if we were not given one, we create a null value type
// instance.
gc.obj = allocMT->Allocate();
if (gc.value != NULL)
CopyValueClass(gc.obj->UnBox(), gc.value->UnBox(), allocMT);
}
}
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(gc.obj);
}
FCIMPLEND
FCIMPL7(void, RuntimeFieldHandle::SetValue, ReflectFieldObject *pFieldUNSAFE, Object *targetUNSAFE, Object *valueUNSAFE, ReflectClassBaseObject *pFieldTypeUNSAFE, DWORD attr, ReflectClassBaseObject *pDeclaringTypeUNSAFE, CLR_BOOL *pDomainInitialized) {
CONTRACTL {
FCALL_CHECK;
}
CONTRACTL_END;
struct _gc {
OBJECTREF target;
OBJECTREF value;
REFLECTCLASSBASEREF fieldType;
REFLECTCLASSBASEREF declaringType;
REFLECTFIELDREF refField;
} gc;
gc.target = ObjectToOBJECTREF(targetUNSAFE);
gc.value = ObjectToOBJECTREF(valueUNSAFE);
gc.fieldType= (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pFieldTypeUNSAFE);
gc.declaringType= (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pDeclaringTypeUNSAFE);
gc.refField = (REFLECTFIELDREF)ObjectToOBJECTREF(pFieldUNSAFE);
if ((gc.fieldType == NULL) || (gc.refField == NULL))
FCThrowResVoid(kArgumentNullException, W("Arg_InvalidHandle"));
TypeHandle fieldType = gc.fieldType->GetType();
TypeHandle declaringType = gc.declaringType != NULL ? gc.declaringType->GetType() : TypeHandle();
Assembly *pAssem;
if (declaringType.IsNull())
{
// global field
pAssem = gc.refField->GetField()->GetModule()->GetAssembly();
}
else
{
pAssem = declaringType.GetAssembly();
}
FC_GC_POLL_NOT_NEEDED();
FieldDesc* pFieldDesc = gc.refField->GetField();
HELPER_METHOD_FRAME_BEGIN_PROTECT(gc);
// Verify we're not trying to set the value of a static initonly field
// once the class has been initialized.
if (pFieldDesc->IsStatic())
{
MethodTable* pEnclosingMT = pFieldDesc->GetEnclosingMethodTable();
if (pEnclosingMT->IsClassInited() && IsFdInitOnly(pFieldDesc->GetAttributes()))
{
DefineFullyQualifiedNameForClassW();
SString ssFieldName(SString::Utf8, pFieldDesc->GetName());
COMPlusThrow(kFieldAccessException,
IDS_EE_CANNOT_SET_INITONLY_STATIC_FIELD,
ssFieldName.GetUnicode(),
GetFullyQualifiedNameForClassW(pEnclosingMT));
}
}
//TODO: cleanup this function
InvokeUtil::SetValidField(fieldType.GetSignatureCorElementType(), fieldType, pFieldDesc, &gc.target, &gc.value, declaringType, pDomainInitialized);
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
//A.CI work
FCIMPL1(Object*, RuntimeTypeHandle::Allocate, ReflectClassBaseObject* pTypeUNSAFE)
{
CONTRACTL {
FCALL_CHECK;
PRECONDITION(CheckPointer(pTypeUNSAFE));
}
CONTRACTL_END
REFLECTCLASSBASEREF refType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pTypeUNSAFE);
TypeHandle type = refType->GetType();
// Handle the nullable<T> special case
if (Nullable::IsNullableType(type)) {
return OBJECTREFToObject(Nullable::BoxedNullableNull(type));
}
OBJECTREF rv = NULL;
HELPER_METHOD_FRAME_BEGIN_RET_1(refType);
rv = AllocateObject(type.GetMethodTable());
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(rv);
}//Allocate
FCIMPLEND
FCIMPL6(Object*, RuntimeTypeHandle::CreateInstance, ReflectClassBaseObject* refThisUNSAFE,
CLR_BOOL publicOnly,
CLR_BOOL wrapExceptions,
CLR_BOOL* pbCanBeCached,
MethodDesc** pConstructor,
CLR_BOOL* pbHasNoDefaultCtor) {
CONTRACTL {
FCALL_CHECK;
PRECONDITION(CheckPointer(refThisUNSAFE));
PRECONDITION(CheckPointer(pbCanBeCached));
PRECONDITION(CheckPointer(pConstructor));
PRECONDITION(CheckPointer(pbHasNoDefaultCtor));
PRECONDITION(*pbCanBeCached == false);
PRECONDITION(*pConstructor == NULL);
PRECONDITION(*pbHasNoDefaultCtor == false);
}
CONTRACTL_END;
if (refThisUNSAFE == NULL)
FCThrow(kNullReferenceException);
MethodDesc* pMeth;
OBJECTREF rv = NULL;
REFLECTCLASSBASEREF refThis = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(refThisUNSAFE);
TypeHandle thisTH = refThis->GetType();
Assembly *pAssem = thisTH.GetAssembly();
HELPER_METHOD_FRAME_BEGIN_RET_2(rv, refThis);
MethodTable* pVMT;
// Get the type information associated with refThis
if (thisTH.IsNull() || thisTH.IsTypeDesc()) {
*pbHasNoDefaultCtor = true;
goto DoneCreateInstance;
}
pVMT = thisTH.AsMethodTable();
pVMT->EnsureInstanceActive();
#ifdef FEATURE_COMINTEROP
// If this is __ComObject then create the underlying COM object.
if (IsComObjectClass(refThis->GetType())) {
#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
SyncBlock* pSyncBlock = refThis->GetSyncBlock();
void* pClassFactory = (void*)pSyncBlock->GetInteropInfo()->GetComClassFactory();
if (!pClassFactory)
COMPlusThrow(kInvalidComObjectException, IDS_EE_NO_BACKING_CLASS_FACTORY);
// create an instance of the Com Object
rv = ((ComClassFactory*)pClassFactory)->CreateInstance(NULL);
#else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
COMPlusThrow(kInvalidComObjectException, IDS_EE_NO_BACKING_CLASS_FACTORY);
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
}
else
#endif // FEATURE_COMINTEROP
{
// if this is an abstract class then we will fail this
if (pVMT->IsAbstract()) {
if (pVMT->IsInterface())
COMPlusThrow(kMissingMethodException,W("Acc_CreateInterface"));
else
COMPlusThrow(kMissingMethodException,W("Acc_CreateAbst"));
}
else if (pVMT->ContainsGenericVariables()) {
COMPlusThrow(kArgumentException,W("Acc_CreateGeneric"));
}
if (pVMT->IsByRefLike())
COMPlusThrow(kNotSupportedException, W("NotSupported_ByRefLike"));
if (pVMT->IsSharedByGenericInstantiations())
COMPlusThrow(kNotSupportedException, W("NotSupported_Type"));
if (!pVMT->HasDefaultConstructor())
{
// We didn't find the parameterless constructor,
// if this is a Value class we can simply allocate one and return it
if (!pVMT->IsValueType()) {
*pbHasNoDefaultCtor = true;
goto DoneCreateInstance;
}
// Handle the nullable<T> special case
if (Nullable::IsNullableType(thisTH)) {
rv = Nullable::BoxedNullableNull(thisTH);
}
else
rv = pVMT->Allocate();
if (!pVMT->Collectible())
{
*pbCanBeCached = true;
}
}
else // !pVMT->HasDefaultConstructor()
{
pMeth = pVMT->GetDefaultConstructor();
// Validate the method can be called by this caller
DWORD attr = pMeth->GetAttrs();
if (!IsMdPublic(attr) && publicOnly) {
*pbHasNoDefaultCtor = true;
goto DoneCreateInstance;
}
// We've got the class, lets allocate it and call the constructor
OBJECTREF o;
bool remoting = false;
o = AllocateObject(pVMT);
GCPROTECT_BEGIN(o);
MethodDescCallSite ctor(pMeth, &o);
// Copy "this" pointer
ARG_SLOT arg;
if (pVMT->IsValueType())
arg = PtrToArgSlot(o->UnBox());
else
arg = ObjToArgSlot(o);
// Call the method
TryCallMethod(&ctor, &arg, wrapExceptions);
rv = o;
GCPROTECT_END();
// No need to set these if they cannot be cached. In particular, if the type is a value type with a custom
// parameterless constructor, don't allow caching and have subsequent calls come back here to allocate an object and
// call the constructor.
if (!remoting && !pVMT->Collectible() && !pVMT->IsValueType())
{
*pbCanBeCached = true;
*pConstructor = pMeth;
}
}
}
DoneCreateInstance:
;
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(rv);
}
FCIMPLEND
FCIMPL2(Object*, RuntimeTypeHandle::CreateInstanceForGenericType, ReflectClassBaseObject* pTypeUNSAFE, ReflectClassBaseObject* pParameterTypeUNSAFE) {
FCALL_CONTRACT;
struct _gc
{
OBJECTREF rv;
REFLECTCLASSBASEREF refType;
REFLECTCLASSBASEREF refParameterType;
} gc;
gc.rv = NULL;
gc.refType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pTypeUNSAFE);
gc.refParameterType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pParameterTypeUNSAFE);
MethodDesc* pMeth;
TypeHandle genericType = gc.refType->GetType();
TypeHandle parameterHandle = gc.refParameterType->GetType();
_ASSERTE (genericType.HasInstantiation());
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
TypeHandle instantiatedType = ((TypeHandle)genericType.GetCanonicalMethodTable()).Instantiate(Instantiation(¶meterHandle, 1));
// Get the type information associated with refThis
MethodTable* pVMT = instantiatedType.GetMethodTable();
_ASSERTE (pVMT != 0 && !instantiatedType.IsTypeDesc());
_ASSERTE( !pVMT->IsAbstract() ||! instantiatedType.ContainsGenericVariables());
_ASSERTE(!pVMT->IsByRefLike() && pVMT->HasDefaultConstructor());
pMeth = pVMT->GetDefaultConstructor();
MethodDescCallSite ctor(pMeth);
// We've got the class, lets allocate it and call the constructor
// Nullables don't take this path, if they do we need special logic to make an instance
_ASSERTE(!Nullable::IsNullableType(instantiatedType));
gc.rv = instantiatedType.GetMethodTable()->Allocate();
ARG_SLOT arg = ObjToArgSlot(gc.rv);
// Call the method
TryCallMethod(&ctor, &arg, true);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(gc.rv);
}
FCIMPLEND
NOINLINE FC_BOOL_RET IsInstanceOfTypeHelper(OBJECTREF obj, REFLECTCLASSBASEREF refType)
{
FCALL_CONTRACT;
BOOL canCast = false;
FC_INNER_PROLOG(RuntimeTypeHandle::IsInstanceOfType);
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_2(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, obj, refType);
canCast = ObjIsInstanceOf(OBJECTREFToObject(obj), refType->GetType());
HELPER_METHOD_FRAME_END();
FC_RETURN_BOOL(canCast);
}
FCIMPL2(FC_BOOL_RET, RuntimeTypeHandle::IsInstanceOfType, ReflectClassBaseObject* pTypeUNSAFE, Object *objectUNSAFE) {
FCALL_CONTRACT;
OBJECTREF obj = ObjectToOBJECTREF(objectUNSAFE);
REFLECTCLASSBASEREF refType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(pTypeUNSAFE);
// Null is not instance of anything in reflection world
if (obj == NULL)
FC_RETURN_BOOL(false);
if (refType == NULL)
FCThrowRes(kArgumentNullException, W("Arg_InvalidHandle"));
switch (ObjIsInstanceOfNoGC(objectUNSAFE, refType->GetType())) {
case TypeHandle::CanCast:
FC_RETURN_BOOL(true);
case TypeHandle::CannotCast:
FC_RETURN_BOOL(false);
default:
// fall through to the slow helper
break;
}
FC_INNER_RETURN(FC_BOOL_RET, IsInstanceOfTypeHelper(obj, refType));
}
FCIMPLEND
/****************************************************************************/
/* boxed Nullable<T> are represented as a boxed T, so there is no unboxed
Nullable<T> inside to point at by reference. Because of this a byref
parameters of type Nullable<T> are copied out of the boxed instance
(to a place on the stack), before the call is made (and this copy is
pointed at). After the call returns, this copy must be copied back to
the original argument array. ByRefToNullable, is a simple linked list
that remembers what copy-backs are needed */
struct ByRefToNullable {
unsigned argNum; // The argument number for this byrefNullable argument
void* data; // The data to copy back to the ByRefNullable. This points to the stack
TypeHandle type; // The type of Nullable for this argument
ByRefToNullable* next; // list of these
ByRefToNullable(unsigned aArgNum, void* aData, TypeHandle aType, ByRefToNullable* aNext) {
argNum = aArgNum;
data = aData;
type = aType;
next = aNext;
}
};
void CallDescrWorkerReflectionWrapper(CallDescrData * pCallDescrData, Frame * pFrame)
{
// Use static contracts b/c we have SEH.
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_ANY;
struct Param: public NotifyOfCHFFilterWrapperParam
{
CallDescrData * pCallDescrData;
} param;
param.pFrame = pFrame;
param.pCallDescrData = pCallDescrData;
PAL_TRY(Param *, pParam, ¶m)
{
CallDescrWorkerWithHandler(pParam->pCallDescrData);
}
PAL_EXCEPT_FILTER(ReflectionInvocationExceptionFilter)
{
// Should never reach here b/c handler should always continue search.
_ASSERTE(false);
}
PAL_ENDTRY
} // CallDescrWorkerReflectionWrapper
OBJECTREF InvokeArrayConstructor(ArrayTypeDesc* arrayDesc, MethodDesc* pMeth, PTRARRAYREF* objs, int argCnt)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
DWORD i;
// If we're trying to create an array of pointers or function pointers,
// check that the caller has skip verification permission.
CorElementType et = arrayDesc->GetArrayElementTypeHandle().GetVerifierCorElementType();
// Validate the argCnt an the Rank. Also allow nested SZARRAY's.
_ASSERTE(argCnt == (int) arrayDesc->GetRank() || argCnt == (int) arrayDesc->GetRank() * 2 ||
arrayDesc->GetInternalCorElementType() == ELEMENT_TYPE_SZARRAY);
// Validate all of the parameters. These all typed as integers
int allocSize = 0;
if (!ClrSafeInt<int>::multiply(sizeof(INT32), argCnt, allocSize))
COMPlusThrow(kArgumentException, IDS_EE_SIGTOOCOMPLEX);
INT32* indexes = (INT32*) _alloca((size_t)allocSize);
ZeroMemory(indexes, allocSize);
for (i=0; i<(DWORD)argCnt; i++)
{
if (!(*objs)->m_Array[i])
COMPlusThrowArgumentException(W("parameters"), W("Arg_NullIndex"));
MethodTable* pMT = ((*objs)->m_Array[i])->GetMethodTable();
CorElementType oType = TypeHandle(pMT).GetVerifierCorElementType();
if (!InvokeUtil::IsPrimitiveType(oType) || !InvokeUtil::CanPrimitiveWiden(ELEMENT_TYPE_I4,oType))
COMPlusThrow(kArgumentException,W("Arg_PrimWiden"));
memcpy(&indexes[i],(*objs)->m_Array[i]->UnBox(),pMT->GetNumInstanceFieldBytes());
}
return AllocateArrayEx(TypeHandle(arrayDesc), indexes, argCnt);
}
static BOOL IsActivationNeededForMethodInvoke(MethodDesc * pMD)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// The activation for non-generic instance methods is covered by non-null "this pointer"
if (!pMD->IsStatic() && !pMD->HasMethodInstantiation() && !pMD->IsInterface())
return FALSE;
// We need to activate the instance at least once
pMD->EnsureActive();
return FALSE;
}
class ArgIteratorBaseForMethodInvoke
{
protected:
SIGNATURENATIVEREF * m_ppNativeSig;
FORCEINLINE CorElementType GetReturnType(TypeHandle * pthValueType)
{
WRAPPER_NO_CONTRACT;
return (*pthValueType = (*m_ppNativeSig)->GetReturnTypeHandle()).GetInternalCorElementType();
}
FORCEINLINE CorElementType GetNextArgumentType(DWORD iArg, TypeHandle * pthValueType)
{
WRAPPER_NO_CONTRACT;
return (*pthValueType = (*m_ppNativeSig)->GetArgumentAt(iArg)).GetInternalCorElementType();
}
FORCEINLINE void Reset()
{
LIMITED_METHOD_CONTRACT;
}
FORCEINLINE BOOL IsRegPassedStruct(MethodTable* pMT)
{
return pMT->IsRegPassedStruct();
}
public:
BOOL HasThis()
{
LIMITED_METHOD_CONTRACT;
return (*m_ppNativeSig)->HasThis();
}
BOOL HasParamType()
{
LIMITED_METHOD_CONTRACT;
// param type methods are not supported for reflection invoke, so HasParamType is always false for them
return FALSE;
}
BOOL IsVarArg()
{
LIMITED_METHOD_CONTRACT;
// vararg methods are not supported for reflection invoke, so IsVarArg is always false for them
return FALSE;
}
DWORD NumFixedArgs()
{
LIMITED_METHOD_CONTRACT;
return (*m_ppNativeSig)->NumFixedArgs();
}
#ifdef FEATURE_INTERPRETER
BYTE CallConv()
{
LIMITED_METHOD_CONTRACT;
return IMAGE_CEE_CS_CALLCONV_DEFAULT;
}
#endif // FEATURE_INTERPRETER
};
class ArgIteratorForMethodInvoke : public ArgIteratorTemplate<ArgIteratorBaseForMethodInvoke>
{
public:
ArgIteratorForMethodInvoke(SIGNATURENATIVEREF * ppNativeSig)
{
m_ppNativeSig = ppNativeSig;
DWORD dwFlags = (*m_ppNativeSig)->GetArgIteratorFlags();
// Use the cached values if they are available
if (dwFlags & SIZE_OF_ARG_STACK_COMPUTED)
{
m_dwFlags = dwFlags;
m_nSizeOfArgStack = (*m_ppNativeSig)->GetSizeOfArgStack();
return;
}
//
// Compute flags and stack argument size, and cache them for next invocation
//
ForceSigWalk();
if (IsActivationNeededForMethodInvoke((*m_ppNativeSig)->GetMethod()))
{
m_dwFlags |= METHOD_INVOKE_NEEDS_ACTIVATION;
}
(*m_ppNativeSig)->SetSizeOfArgStack(m_nSizeOfArgStack);
_ASSERTE((*m_ppNativeSig)->GetSizeOfArgStack() == m_nSizeOfArgStack);
// This has to be last
(*m_ppNativeSig)->SetArgIteratorFlags(m_dwFlags);
_ASSERTE((*m_ppNativeSig)->GetArgIteratorFlags() == m_dwFlags);
}
BOOL IsActivationNeeded()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & METHOD_INVOKE_NEEDS_ACTIVATION) != 0;
}
};
void DECLSPEC_NORETURN ThrowInvokeMethodException(MethodDesc * pMethod, OBJECTREF targetException)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
GCPROTECT_BEGIN(targetException);
#if defined(_DEBUG) && !defined(FEATURE_PAL)
if (IsWatsonEnabled())
{
if (!CLRException::IsPreallocatedExceptionObject(targetException))
{
// If the exception is not preallocated, we should be having the
// watson buckets in the throwable already.
if(!((EXCEPTIONREF)targetException)->AreWatsonBucketsPresent())
{
// If an exception is raised by the VM (e.g. type load exception by the JIT) and it comes
// across the reflection invocation boundary before CLR's personality routine for managed
// code has been invoked, then no buckets would be available for us at this point.
//
// Since we cannot assert this, better log it for diagnosis if required.
LOG((LF_EH, LL_INFO100, "InvokeImpl - No watson buckets available - regular exception likely raised within VM and not seen by managed code.\n"));
}
}
else
{
// Exception is preallocated.
PTR_EHWatsonBucketTracker pUEWatsonBucketTracker = GetThread()->GetExceptionState()->GetUEWatsonBucketTracker();
if ((IsThrowableThreadAbortException(targetException) && pUEWatsonBucketTracker->CapturedForThreadAbort())||
(pUEWatsonBucketTracker->CapturedAtReflectionInvocation()))
{
// ReflectionInvocationExceptionFilter would have captured
// the watson bucket details for preallocated exceptions
// in the UE watson bucket tracker.
if(pUEWatsonBucketTracker->RetrieveWatsonBuckets() == NULL)
{
// See comment above
LOG((LF_EH, LL_INFO100, "InvokeImpl - No watson buckets available - preallocated exception likely raised within VM and not seen by managed code.\n"));
}
}
}
}
#endif // _DEBUG && !FEATURE_PAL
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// Get the corruption severity of the exception that came in through reflection invocation.
CorruptionSeverity severity = GetThread()->GetExceptionState()->GetLastActiveExceptionCorruptionSeverity();
// Since we are dealing with an exception, set the flag indicating if the target of Reflection can handle exception or not.
// This flag is used in CEHelper::CanIDispatchTargetHandleException.
GetThread()->GetExceptionState()->SetCanReflectionTargetHandleException(CEHelper::CanMethodHandleException(severity, pMethod));
#endif // FEATURE_CORRUPTING_EXCEPTIONS
OBJECTREF except = InvokeUtil::CreateTargetExcept(&targetException);
#ifndef FEATURE_PAL
if (IsWatsonEnabled())
{
struct
{
OBJECTREF oExcept;
} gcTIE;
ZeroMemory(&gcTIE, sizeof(gcTIE));
GCPROTECT_BEGIN(gcTIE);
gcTIE.oExcept = except;
_ASSERTE(!CLRException::IsPreallocatedExceptionObject(gcTIE.oExcept));
// If the original exception was preallocated, then copy over the captured
// watson buckets to the TargetInvocationException object, if available.
//
// We dont need to do this if the original exception was not preallocated
// since it already contains the watson buckets inside the object.
if (CLRException::IsPreallocatedExceptionObject(targetException))
{
PTR_EHWatsonBucketTracker pUEWatsonBucketTracker = GetThread()->GetExceptionState()->GetUEWatsonBucketTracker();
BOOL fCopyWatsonBuckets = TRUE;
PTR_VOID pBuckets = pUEWatsonBucketTracker->RetrieveWatsonBuckets();
if (pBuckets != NULL)
{
// Copy the buckets to the exception object
CopyWatsonBucketsToThrowable(pBuckets, gcTIE.oExcept);
// Confirm that they are present.
_ASSERTE(((EXCEPTIONREF)gcTIE.oExcept)->AreWatsonBucketsPresent());
}
// Clear the UE watson bucket tracker since the bucketing
// details are now in the TargetInvocationException object.
pUEWatsonBucketTracker->ClearWatsonBucketDetails();
}
// update "except" incase the reference to the object
// was updated by the GC
except = gcTIE.oExcept;
GCPROTECT_END();
}
#endif // !FEATURE_PAL
// Since the original exception is inner of target invocation exception,
// when TIE is seen to be raised for the first time, we will end up
// using the inner exception buckets automatically.
// Since VM is throwing the exception, we set it to use the same corruption severity
// that the original exception came in with from reflection invocation.
COMPlusThrow(except
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
, severity
#endif // FEATURE_CORRUPTING_EXCEPTIONS
);
GCPROTECT_END();
}
FCIMPL5(Object*, RuntimeMethodHandle::InvokeMethod,
Object *target, PTRArray *objs, SignatureNative* pSigUNSAFE,
CLR_BOOL fConstructor, CLR_BOOL fWrapExceptions)
{
FCALL_CONTRACT;
struct {
OBJECTREF target;
PTRARRAYREF args;
SIGNATURENATIVEREF pSig;
OBJECTREF retVal;
} gc;
gc.target = ObjectToOBJECTREF(target);
gc.args = (PTRARRAYREF)objs;
gc.pSig = (SIGNATURENATIVEREF)pSigUNSAFE;
gc.retVal = NULL;
MethodDesc* pMeth = gc.pSig->GetMethod();
TypeHandle ownerType = gc.pSig->GetDeclaringType();
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
Assembly *pAssem = pMeth->GetAssembly();
if (ownerType.IsSharedByGenericInstantiations())
COMPlusThrow(kNotSupportedException, W("NotSupported_Type"));
#ifdef _DEBUG
if (g_pConfig->ShouldInvokeHalt(pMeth))
{
_ASSERTE(!"InvokeHalt");
}
#endif