summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/MethodInfo.cs
blob: 39387b1f8fc10007b83c56407090eed4de2aa5f7 (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
// 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.

// 

namespace System.Reflection
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;
    using System.Globalization;
    using System.Runtime;
    using System.Runtime.InteropServices;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.Serialization;
    using System.Security;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading;
    using MemberListType = System.RuntimeType.MemberListType;
    using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
    using System.Runtime.CompilerServices;

    [Serializable]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_MethodInfo))]
    [System.Runtime.InteropServices.ComVisible(true)]
    public abstract class MethodInfo : MethodBase, _MethodInfo
    {
        #region Constructor
        protected MethodInfo() { }
        #endregion

        public static bool operator ==(MethodInfo left, MethodInfo right)
        {
            if (ReferenceEquals(left, right))
                return true;

            if ((object)left == null || (object)right == null ||
                left is RuntimeMethodInfo || right is RuntimeMethodInfo)
            {
                return false;
            }
            return left.Equals(right);
        }

        public static bool operator !=(MethodInfo left, MethodInfo right)
        {
            return !(left == right);
        }

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        #region MemberInfo Overrides
        public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } }
        #endregion
    
        #region Public Abstract\Virtual Members
        public virtual Type ReturnType { get { throw new NotImplementedException(); } }
    
        public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } }

        public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get;  }

        public abstract MethodInfo GetBaseDefinition();

        [System.Runtime.InteropServices.ComVisible(true)]
        public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }

        [System.Runtime.InteropServices.ComVisible(true)]
        public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }

        public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }

        public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
        public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
        #endregion
    }

    [Serializable]
    internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo
    {
        #region Private Data Members
        private IntPtr m_handle;        
        private RuntimeTypeCache m_reflectedTypeCache;
        private string m_name;
        private string m_toString;
        private ParameterInfo[] m_parameters;
        private ParameterInfo m_returnParameter;
        private BindingFlags m_bindingFlags;
        private MethodAttributes m_methodAttributes;
        private Signature m_signature;
        private RuntimeType m_declaringType;
        private object m_keepalive;
        private INVOCATION_FLAGS m_invocationFlags;

#if FEATURE_APPX
        private bool IsNonW8PFrameworkAPI()
        {
            if (m_declaringType.IsArray && IsPublic && !IsStatic)
                return false;

            RuntimeAssembly rtAssembly = GetRuntimeAssembly();
            if (rtAssembly.IsFrameworkAssembly())
            {
                int ctorToken = rtAssembly.InvocableAttributeCtorToken;
                if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
                    !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
                    return true;
            }

            if (GetRuntimeType().IsNonW8PFrameworkAPI())
                return true;

            if (IsGenericMethod && !IsGenericMethodDefinition)
            {
                foreach (Type t in GetGenericArguments())
                {
                    if (((RuntimeType)t).IsNonW8PFrameworkAPI())
                        return true;
                }
            }

            return false;
        }

        internal override bool IsDynamicallyInvokable
        {
            get
            {
                return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
            }
        }
#endif

        internal INVOCATION_FLAGS InvocationFlags
        {
            get
            {
                if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
                {
                    INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;

                    Type declaringType = DeclaringType;

                    //
                    // first take care of all the NO_INVOKE cases. 
                    if (ContainsGenericParameters ||
                         ReturnType.IsByRef ||
                         (declaringType != null && declaringType.ContainsGenericParameters) ||
                         ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
                         ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
                    {
                        // We don't need other flags if this method cannot be invoked
                        invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
                    }
                    else
                    {
                        // this should be an invocable method, determine the other flags that participate in invocation
                        invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this);

                        if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0)
                        {
                            if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
                                 (declaringType != null && declaringType.NeedsReflectionSecurityCheck) )
                            {
                                // If method is non-public, or declaring type is not visible
                                invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
                            }
                            else if (IsGenericMethod)
                            {
                                Type[] genericArguments = GetGenericArguments();

                                for (int i = 0; i < genericArguments.Length; i++)
                                {
                                    if (genericArguments[i].NeedsReflectionSecurityCheck)
                                    {
                                        invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
                                        break;
                                    }
                                }
                            }
                        }
                    }

#if FEATURE_APPX
                    if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
                        invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX

                    m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
                }

                return m_invocationFlags;
            }
        }
        #endregion

        #region Constructor
        internal RuntimeMethodInfo(
            RuntimeMethodHandleInternal handle, RuntimeType declaringType, 
            RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
        {
            Contract.Ensures(!m_handle.IsNull());

            Debug.Assert(!handle.IsNullHandle());
            Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));            

            m_bindingFlags = bindingFlags;
            m_declaringType = declaringType;
            m_keepalive = keepalive;
            m_handle = handle.Value;
            m_reflectedTypeCache = reflectedTypeCache;
            m_methodAttributes = methodAttributes;
        }
        #endregion

        #region Private Methods
        RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
        {
            get
            {
                return new RuntimeMethodHandleInternal(m_handle);
            }
        }

        private RuntimeType ReflectedTypeInternal
        { 
            get 
            { 
                return m_reflectedTypeCache.GetRuntimeType(); 
            } 
        }

        private ParameterInfo[] FetchNonReturnParameters()
        {
            if (m_parameters == null)
                m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);

            return m_parameters;
        }

        private ParameterInfo FetchReturnParameter()
        {
            if (m_returnParameter == null)
                m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature);

            return m_returnParameter;
        }
        #endregion

        #region Internal Members
        internal override string FormatNameAndSig(bool serialization)
        {
            // Serialization uses ToString to resolve MethodInfo overloads.
            StringBuilder sbName = new StringBuilder(Name);

            // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
            // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
            TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;

            if (IsGenericMethod)
                sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));

            sbName.Append("(");
            sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
            sbName.Append(")");

            return sbName.ToString();
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        internal override bool CacheEquals(object o) 
        { 
            RuntimeMethodInfo m = o as RuntimeMethodInfo;

            if ((object)m == null)
                return false;

            return m.m_handle == m_handle;
        } 

        internal Signature Signature
        {
            get
            {
                if (m_signature == null)
                    m_signature = new Signature(this, m_declaringType);

                return m_signature;
            }
        }

        internal BindingFlags BindingFlags { get { return m_bindingFlags; } }

        // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
        internal RuntimeMethodHandle GetMethodHandle()
        {
            return new RuntimeMethodHandle(this);
        }

        internal RuntimeMethodInfo GetParentDefinition()
        {
            if (!IsVirtual || m_declaringType.IsInterface)
                return null;

            RuntimeType parent = (RuntimeType)m_declaringType.BaseType;

            if (parent == null)
                return null;

            int slot = RuntimeMethodHandle.GetSlot(this);

            if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
                return null;

            return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
        }

        // Unlike DeclaringType, this will return a valid type even for global methods
        internal RuntimeType GetDeclaringTypeInternal()
        {
            return m_declaringType;
        }

        #endregion

        #region Object Overrides
        public override String ToString() 
        {
            if (m_toString == null)
                m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig();

            return m_toString;
        }

        public override int GetHashCode()
        {
            // See RuntimeMethodInfo.Equals() below.
            if (IsGenericMethod)
                return ValueType.GetHashCodeOfPtr(m_handle);
            else
                return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (!IsGenericMethod)
                return obj == (object)this;

            // We cannot do simple object identity comparisons for generic methods.
            // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
            // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable.

            RuntimeMethodInfo mi = obj as RuntimeMethodInfo;

            if (mi == null || !mi.IsGenericMethod)
                return false;

            // now we know that both operands are generic methods

            IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this);
            IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi);
            if (handle1.Value.Value != handle2.Value.Value)
                return false;

            Type[] lhs = GetGenericArguments();
            Type[] rhs = mi.GetGenericArguments();

            if (lhs.Length != rhs.Length)
                return false;

            for (int i = 0; i < lhs.Length; i++)
            {
                if (lhs[i] != rhs[i])
                    return false;
            }

            if (DeclaringType != mi.DeclaringType)
                return false;

            if (ReflectedType != mi.ReflectedType)
                return false;

            return true;
        }
        #endregion

        #region ICustomAttributeProvider
        public override Object[] GetCustomAttributes(bool inherit)
        {
            return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
        }

        public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
        {
            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));
            Contract.EndContractBlock();

            RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;

            if (attributeRuntimeType == null) 
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));

            return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
        }

        public override bool IsDefined(Type attributeType, bool inherit)
        {
            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));
            Contract.EndContractBlock();

            RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;

            if (attributeRuntimeType == null) 
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));

            return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
        }

        public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return CustomAttributeData.GetCustomAttributesInternal(this);
        }
        #endregion

        #region MemberInfo Overrides
        public override String Name 
        {
            get
            {
                if (m_name == null)
                    m_name = RuntimeMethodHandle.GetName(this);

                return m_name;
            }
        }

        public override Type DeclaringType 
        {
            get
            {
                if (m_reflectedTypeCache.IsGlobal)
                    return null;

                return m_declaringType;
            }
        }

        public override Type ReflectedType 
        {
            get
            {
                if (m_reflectedTypeCache.IsGlobal)
                    return null;

                return m_reflectedTypeCache.GetRuntimeType();
            }
        }

        public override MemberTypes MemberType { get { return MemberTypes.Method; } }
        public override int MetadataToken
        {
            get { return RuntimeMethodHandle.GetMethodDef(this); }
        }        
        public override Module Module { get { return GetRuntimeModule(); } }
        internal RuntimeType GetRuntimeType() { return m_declaringType; }
        internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
        internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }

        public override bool IsSecurityCritical 
        {
            get { return true; }
        }
        public override bool IsSecuritySafeCritical
        {
            get { return false; }
        }
        public override bool IsSecurityTransparent
        {
            get { return false; }
        }
#endregion

#region MethodBase Overrides
        internal override ParameterInfo[] GetParametersNoCopy()
        {
            FetchNonReturnParameters();

            return m_parameters;
        }

        [System.Diagnostics.Contracts.Pure]
        public override ParameterInfo[] GetParameters()
        {
            FetchNonReturnParameters();

            if (m_parameters.Length == 0)
                return m_parameters;

            ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];

            Array.Copy(m_parameters, ret, m_parameters.Length);

            return ret;
        }

        public override MethodImplAttributes GetMethodImplementationFlags()
        {
            return RuntimeMethodHandle.GetImplAttributes(this);
        }

        internal bool IsOverloaded
        {
            get 
            {
                return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1;
            }
        }

        public override RuntimeMethodHandle MethodHandle 
        { 
            get 
            { 
                Type declaringType = DeclaringType;
                if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
                return new RuntimeMethodHandle(this); 
            } 
        }

        public override MethodAttributes Attributes { get { return m_methodAttributes; } }
        
        public override CallingConventions CallingConvention 
        { 
            get 
            { 
                return Signature.CallingConvention; 
            } 
        }

        public override MethodBody GetMethodBody()
        {
            MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
            if (mb != null) 
                mb.m_methodBase = this;
            return mb;
        }        
#endregion

#region Invocation Logic(On MemberBase)
        private void CheckConsistency(Object target) 
        {
            // only test instance methods
            if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) 
            {
                if (!m_declaringType.IsInstanceOfType(target))
                {
                    if (target == null) 
                        throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
                    else
                        throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
                }
            }
        }

        private void ThrowNoInvokeException()
        {
            // method is ReflectionOnly
            Type declaringType = DeclaringType;
            if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
            {
                throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
            }
            // method is on a class that contains stack pointers
            else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
            {
                throw new NotSupportedException();
            }
            // method is vararg
            else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
            {
                throw new NotSupportedException();
            }
            // method is generic or on a generic class
            else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
            {
                throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam"));
            }
            // method is abstract class
            else if (IsAbstract)
            {
                throw new MemberAccessException();
            }
            // ByRef return are not allowed in reflection
            else if (ReturnType.IsByRef)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn"));
            }

            throw new TargetException();
        }
        
        [DebuggerStepThroughAttribute]
        [Diagnostics.DebuggerHidden]
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        {
            object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);

#region Security Check
            INVOCATION_FLAGS invocationFlags = InvocationFlags;

#if FEATURE_APPX
            if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
            {
                StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
                RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
                if (caller != null && !caller.IsSafeForReflection())
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
            }
#endif
#endregion

            return UnsafeInvokeInternal(obj, parameters, arguments);
        }

        [DebuggerStepThroughAttribute]
        [Diagnostics.DebuggerHidden]
        internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        {
            object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);

            return UnsafeInvokeInternal(obj, parameters, arguments);
        }

        [DebuggerStepThroughAttribute]
        [Diagnostics.DebuggerHidden]
        private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
        {
            if (arguments == null || arguments.Length == 0)
                return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false);
            else
            {
                Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false);

                // copy out. This should be made only if ByRef are present.
                for (int index = 0; index < arguments.Length; index++)
                    parameters[index] = arguments[index];

                return retValue;
            }
        }

        [DebuggerStepThroughAttribute]
        [Diagnostics.DebuggerHidden]
        private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        {
            Signature sig = Signature;

            // get the signature 
            int formalCount = sig.Arguments.Length;
            int actualCount = (parameters != null) ? parameters.Length : 0;

            INVOCATION_FLAGS invocationFlags = InvocationFlags;

            // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type)
            // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot
            // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects.
            if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0)
                ThrowNoInvokeException();

            // check basic method consistency. This call will throw if there are problems in the target/method relationship
            CheckConsistency(obj);

            if (formalCount != actualCount)
                throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));

            if (actualCount != 0)
                return CheckArguments(parameters, binder, invokeAttr, culture, sig);
            else
                return null;
        }

#endregion

#region MethodInfo Overrides
        public override Type ReturnType 
        { 
            get { return Signature.ReturnType; } 
        }

        public override ICustomAttributeProvider ReturnTypeCustomAttributes 
        { 
            get { return ReturnParameter; } 
        }

        public override ParameterInfo ReturnParameter 
        {
            get
            {
                Contract.Ensures(m_returnParameter != null);

                FetchReturnParameter();
                return m_returnParameter as ParameterInfo;
            }
        }

        public override MethodInfo GetBaseDefinition()
        {
            if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
                return this;

            int slot = RuntimeMethodHandle.GetSlot(this);
            RuntimeType declaringType = (RuntimeType)DeclaringType;
            RuntimeType baseDeclaringType = declaringType;
            RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();

            do {
                int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);

                if (cVtblSlots <= slot)
                    break;

                baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
                baseDeclaringType = declaringType;

                declaringType = (RuntimeType)declaringType.BaseType;
            } while (declaringType != null);

            return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
        }

        public override Delegate CreateDelegate(Type delegateType)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;

            // This API existed in v1/v1.1 and only expected to create closed
            // instance delegates. Constrain the call to BindToMethodInfo to
            // open delegates only for backwards compatibility. But we'll allow
            // relaxed signature checking and open static delegates because
            // there's no ambiguity there (the caller would have to explicitly
            // pass us a static method or a method with a non-exact signature
            // and the only change in behavior from v1.1 there is that we won't
            // fail the call).
            return CreateDelegateInternal(
                delegateType,
                null,
                DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
                ref stackMark);
        }

        public override Delegate CreateDelegate(Type delegateType, Object target)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;

            // This API is new in Whidbey and allows the full range of delegate
            // flexability (open or closed delegates binding to static or
            // instance methods with relaxed signature checking). The delegate
            // can also be closed over null. There's no ambiguity with all these
            // options since the caller is providing us a specific MethodInfo.
            return CreateDelegateInternal(
                delegateType,
                target,
                DelegateBindingFlags.RelaxedSignature,
                ref stackMark);
        }

        private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
        {
            // Validate the parameters.
            if (delegateType == null)
                throw new ArgumentNullException(nameof(delegateType));
            Contract.EndContractBlock();

            RuntimeType rtType = delegateType as RuntimeType;
            if (rtType == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType));

            if (!rtType.IsDelegate())
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType));

            Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
            if (d == null)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
            }

            return d;
        }

#endregion

#region Generics
        public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
        {
          if (methodInstantiation == null)
                throw new ArgumentNullException(nameof(methodInstantiation));
          Contract.EndContractBlock();

            RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];

            if (!IsGenericMethodDefinition)
                throw new InvalidOperationException(
                    Environment.GetResourceString("Arg_NotGenericMethodDefinition", this));

            for (int i = 0; i < methodInstantiation.Length; i++)
            {
                Type methodInstantiationElem = methodInstantiation[i];

                if (methodInstantiationElem == null)
                    throw new ArgumentNullException();

                RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;

                if (rtMethodInstantiationElem == null)
                {
                    Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
                    for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++)
                        methodInstantiationCopy[iCopy] = methodInstantiation[iCopy];
                    methodInstantiation = methodInstantiationCopy;
                    return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation);
                }

                methodInstantionRuntimeType[i] = rtMethodInstantiationElem;
            }

            RuntimeType[] genericParameters = GetGenericArgumentsInternal();

            RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);

            MethodInfo ret = null;
                
            try
            {
                ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
                    RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
            }
            catch (VerificationException e)
            {
                RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
                throw;
            }
            
            return ret;
        }

        internal RuntimeType[] GetGenericArgumentsInternal()
        {
            return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
        }

        public override Type[] GetGenericArguments() 
        {
            Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);

            if (types == null)
            {
                types = EmptyArray<Type>.Value;
            }
            return types;
        }

        public override MethodInfo GetGenericMethodDefinition() 
        {
            if (!IsGenericMethod)
                throw new InvalidOperationException();
            Contract.EndContractBlock();
            
            return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
        }

        public override bool IsGenericMethod
        {
            get { return RuntimeMethodHandle.HasMethodInstantiation(this); }
        }

        public override bool IsGenericMethodDefinition
        {
            get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); }
        } 

        public override bool ContainsGenericParameters 
        { 
            get 
            {
                if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
                    return true;

                if (!IsGenericMethod)
                    return false;

                Type[] pis = GetGenericArguments(); 
                for (int i = 0; i < pis.Length; i++)
                {
                    if (pis[i].ContainsGenericParameters)
                        return true;
                }

                return false;
            } 
        }
#endregion

#region ISerializable Implementation
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException(nameof(info));
            Contract.EndContractBlock();

            if (m_reflectedTypeCache.IsGlobal)
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));

            MemberInfoSerializationHolder.GetSerializationInfo(
                info,
                Name,
                ReflectedTypeInternal,
                ToString(),
                SerializationToString(),
                MemberTypes.Method,
                IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
        }

        internal string SerializationToString()
        {
            return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
        }
#endregion

#region Legacy Internal
        internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
        {
            IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);

            if (method == null) 
                return null;
            
            return RuntimeType.GetMethodBase(method);
        }
#endregion
    }
}