Updates referencesource to .NET 4.7
[mono.git] / mcs / class / referencesource / mscorlib / system / reflection / ConstructorInfo.cs
1 // ==++==
2 // 
3 //   Copyright(c) Microsoft Corporation.  All rights reserved.
4 // 
5 // ==--==
6 // <OWNER>Microsoft</OWNER>
7 // 
8
9 namespace System.Reflection
10 {
11     using System;
12     using System.Collections.Generic;
13     using System.Diagnostics;
14     using System.Diagnostics.Contracts;
15     using System.Globalization;
16     using System.Runtime;
17     using System.Runtime.ConstrainedExecution;
18     using System.Runtime.InteropServices;
19 #if FEATURE_REMOTING
20     using System.Runtime.Remoting.Metadata;
21 #endif //FEATURE_REMOTING
22     using System.Runtime.Serialization;
23     using System.Security;
24     using System.Security.Permissions;
25     using System.Threading;
26     using MemberListType = System.RuntimeType.MemberListType;
27     using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
28     using System.Runtime.CompilerServices;
29
30     [Serializable]
31     [ClassInterface(ClassInterfaceType.None)]
32     [ComDefaultInterface(typeof(_ConstructorInfo))]
33 #pragma warning disable 618
34     [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
35 #pragma warning restore 618
36     [System.Runtime.InteropServices.ComVisible(true)]
37     public abstract class ConstructorInfo : MethodBase, _ConstructorInfo
38     {
39         #region Static Members
40         [System.Runtime.InteropServices.ComVisible(true)]
41         public readonly static String ConstructorName = ".ctor";
42
43         [System.Runtime.InteropServices.ComVisible(true)]
44         public readonly static String TypeConstructorName = ".cctor";
45         #endregion
46
47         #region Constructor
48         protected ConstructorInfo() { }
49         #endregion
50
51 #if !FEATURE_CORECLR
52         public static bool operator ==(ConstructorInfo left, ConstructorInfo right)
53         {
54             if (ReferenceEquals(left, right))
55                 return true;
56
57             if ((object)left == null || (object)right == null ||
58                 left is RuntimeConstructorInfo || right is RuntimeConstructorInfo)
59             {
60                 return false;
61             }
62             return left.Equals(right);
63         }
64
65         public static bool operator !=(ConstructorInfo left, ConstructorInfo right)
66         {
67             return !(left == right);
68         }
69 #endif // !FEATURE_CORECLR
70
71         public override bool Equals(object obj)
72         {
73             return base.Equals(obj);
74         }
75
76         public override int GetHashCode()
77         {
78             return base.GetHashCode();
79         }
80
81         #region Internal Members
82         internal virtual Type GetReturnType() { throw new NotImplementedException(); }
83         #endregion
84
85         #region MemberInfo Overrides
86         [System.Runtime.InteropServices.ComVisible(true)]
87         public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } }
88         #endregion
89     
90         #region Public Abstract\Virtual Members
91         public abstract Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
92         #endregion
93
94         #region Public Members
95         [DebuggerStepThroughAttribute]
96         [Diagnostics.DebuggerHidden]
97         public Object Invoke(Object[] parameters)
98         {
99             // Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
100             // But to maintain backward compatibility we can't switch to calling an 
101             // internal overload that takes a stack mark.
102             // Fortunately the stack walker skips all the reflection invocation frames including this one.
103             // So this method will never be returned by the stack walker as the caller.
104             // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
105             return Invoke(BindingFlags.Default, null, parameters, null);
106         }
107         #endregion
108
109 #if !FEATURE_CORECLR
110         #region COM Interop Support
111         Type _ConstructorInfo.GetType()
112         {
113             return base.GetType();
114         }
115         
116         Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
117         {
118             return Invoke(obj, invokeAttr, binder, parameters, culture);
119         }
120         
121         Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters)
122         {
123             return Invoke(obj, parameters);
124         }
125         
126         Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
127         {
128             return Invoke(invokeAttr, binder, parameters, culture);
129         }
130         
131         Object _ConstructorInfo.Invoke_5(Object[] parameters)
132         {
133             return Invoke(parameters);
134         }
135
136         void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo)
137         {
138             throw new NotImplementedException();
139         }
140
141         void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
142         {
143             throw new NotImplementedException();
144         }
145
146         void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
147         {
148             throw new NotImplementedException();
149         }
150
151         // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and 
152         // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
153         void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
154         {
155             throw new NotImplementedException();
156         }
157         #endregion
158 #endif
159     }
160
161     [Serializable]
162     internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo
163     {
164         #region Private Data Members
165         private volatile RuntimeType m_declaringType;
166         private RuntimeTypeCache m_reflectedTypeCache;
167         private string m_toString;
168         private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called.
169 #pragma warning disable 169
170         private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar
171         private object _empty2;
172         private object _empty3;
173 #pragma warning restore 169
174         private IntPtr m_handle;
175         private MethodAttributes m_methodAttributes;
176         private BindingFlags m_bindingFlags;
177         private volatile Signature m_signature;
178         private INVOCATION_FLAGS m_invocationFlags;
179
180 #if FEATURE_APPX
181         private bool IsNonW8PFrameworkAPI()
182         {
183             if (DeclaringType.IsArray && IsPublic && !IsStatic)
184                 return false;
185
186             RuntimeAssembly rtAssembly = GetRuntimeAssembly();
187             if (rtAssembly.IsFrameworkAssembly())
188             {
189                 int ctorToken = rtAssembly.InvocableAttributeCtorToken;
190                 if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || 
191                     !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
192                 return true;
193             }
194
195             if (GetRuntimeType().IsNonW8PFrameworkAPI())
196                 return true;
197
198             return false;
199         }
200
201         internal override bool IsDynamicallyInvokable
202         {
203             get
204             {
205                 return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
206             }
207         }
208 #endif // FEATURE_APPX
209
210         internal INVOCATION_FLAGS InvocationFlags
211         {
212             [System.Security.SecuritySafeCritical]
213             get
214             {
215                 if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
216                 {
217                     INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given
218
219                     Type declaringType = DeclaringType;
220
221                     //
222                     // first take care of all the NO_INVOKE cases. 
223                     if ( declaringType == typeof(void) ||
224                          (declaringType != null && declaringType.ContainsGenericParameters) ||
225                          ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
226                          ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
227                     {
228                         // We don't need other flags if this method cannot be invoked
229                         invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
230                     }
231                     else if (IsStatic || declaringType != null && declaringType.IsAbstract)
232                     {
233                         invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE;
234                     }
235                     else
236                     {
237                         // this should be an invocable method, determine the other flags that participate in invocation
238                         invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this);
239
240                         if ( (invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 &&
241                              ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
242                               (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) )
243                         {
244                             // If method is non-public, or declaring type is not visible
245                             invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
246                         }
247
248                         // Check for attempt to create a delegate class, we demand unmanaged
249                         // code permission for this since it's hard to validate the target address.
250                         if (typeof(Delegate).IsAssignableFrom(DeclaringType))
251                             invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;
252                     }
253
254 #if FEATURE_APPX
255                     if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
256                         invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
257 #endif // FEATURE_APPX
258
259                     m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
260                 }
261
262                 return m_invocationFlags;
263             }
264         }
265         #endregion
266
267         #region Constructor
268         [System.Security.SecurityCritical]  // auto-generated
269         internal RuntimeConstructorInfo(
270             RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,
271             MethodAttributes methodAttributes, BindingFlags bindingFlags)
272         {
273             Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
274
275             m_bindingFlags = bindingFlags;
276             m_reflectedTypeCache = reflectedTypeCache;
277             m_declaringType = declaringType;
278             m_handle = handle.Value;
279             m_methodAttributes = methodAttributes;
280         }
281         #endregion
282
283 #if FEATURE_REMOTING
284         #region Legacy Remoting Cache
285         // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
286         // This member is currently being used by Remoting for caching remoting data. If you
287         // need to cache data here, talk to the Remoting team to work out a mechanism, so that
288         // both caching systems can happily work together.
289         private RemotingMethodCachedData m_cachedData;
290
291         internal RemotingMethodCachedData RemotingCache
292         {
293             get
294             {
295                 // This grabs an internal copy of m_cachedData and uses
296                 // that instead of looking at m_cachedData directly because
297                 // the cache may get cleared asynchronously.  This prevents
298                 // us from having to take a lock.
299                 RemotingMethodCachedData cache = m_cachedData;
300                 if (cache == null)
301                 {
302                     cache = new RemotingMethodCachedData(this);
303                     RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
304                     if (ret != null)
305                         cache = ret;
306                 }
307                 return cache;
308             }
309         }
310         #endregion
311 #endif //FEATURE_REMOTING
312
313         #region NonPublic Methods
314         RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
315         {
316             [System.Security.SecuritySafeCritical]
317             get
318             {
319                 return new RuntimeMethodHandleInternal(m_handle);
320             }
321         }
322
323         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
324         internal override bool CacheEquals(object o)
325         {
326             RuntimeConstructorInfo m = o as RuntimeConstructorInfo;
327
328             if ((object)m == null)
329                 return false;
330
331             return m.m_handle == m_handle;
332         }
333
334         private Signature Signature
335         {
336             get
337             {
338                 if (m_signature == null)
339                     m_signature = new Signature(this, m_declaringType);
340
341                 return m_signature;
342             }
343         }
344
345         private RuntimeType ReflectedTypeInternal
346         { 
347             get 
348             { 
349                 return m_reflectedTypeCache.GetRuntimeType(); 
350             } 
351         }
352
353         private void CheckConsistency(Object target) 
354         {
355             if (target == null && IsStatic)
356                 return;
357
358             if (!m_declaringType.IsInstanceOfType(target))
359             {
360                 if (target == null) 
361                     throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
362
363                 throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
364             }
365         }
366
367         internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
368
369         // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
370         internal RuntimeMethodHandle GetMethodHandle()
371         {
372             return new RuntimeMethodHandle(this);
373         }
374
375         internal bool IsOverloaded
376         { 
377             get 
378             { 
379                 return m_reflectedTypeCache.GetConstructorList(MemberListType.CaseSensitive, Name).Length > 1;
380             }
381         }
382         #endregion
383
384         #region Object Overrides
385         public override String ToString() 
386         {
387             // "Void" really doesn't make sense here. But we'll keep it for compat reasons.
388             if (m_toString == null)
389                 m_toString = "Void " + FormatNameAndSig();
390
391             return m_toString;
392         }
393         #endregion
394
395         #region ICustomAttributeProvider
396         public override Object[] GetCustomAttributes(bool inherit)
397         {
398             return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
399         }
400
401         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
402         {
403             if (attributeType == null)
404                 throw new ArgumentNullException("attributeType");
405             Contract.EndContractBlock();
406
407             RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
408
409             if (attributeRuntimeType == null) 
410                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
411
412             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
413         }
414
415         [System.Security.SecuritySafeCritical]  // auto-generated
416         public override bool IsDefined(Type attributeType, bool inherit)
417         {
418             if (attributeType == null)
419                 throw new ArgumentNullException("attributeType");
420             Contract.EndContractBlock();
421
422             RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
423
424             if (attributeRuntimeType == null) 
425                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
426
427             return CustomAttribute.IsDefined(this, attributeRuntimeType);
428         }
429         
430         public override IList<CustomAttributeData> GetCustomAttributesData()
431         {
432             return CustomAttributeData.GetCustomAttributesInternal(this);
433         }
434         #endregion
435
436
437         #region MemberInfo Overrides
438         public override String Name
439         {
440             [System.Security.SecuritySafeCritical]  // auto-generated
441             get { return RuntimeMethodHandle.GetName(this); }
442         }
443 [System.Runtime.InteropServices.ComVisible(true)]
444         public override MemberTypes MemberType { get { return MemberTypes.Constructor; } }
445         
446         public override Type DeclaringType 
447         { 
448             get 
449             { 
450                 return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; 
451             }
452         }
453
454         public override Type ReflectedType
455         {
456             get
457             {
458                 return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
459             }
460         }
461
462         public override int MetadataToken
463         {
464             [System.Security.SecuritySafeCritical]  // auto-generated
465             get { return RuntimeMethodHandle.GetMethodDef(this); }
466         }
467         public override Module Module
468         {
469             get { return GetRuntimeModule(); }
470         }
471
472         internal RuntimeType GetRuntimeType() { return m_declaringType; }
473         internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); }
474         internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
475         #endregion
476
477         #region MethodBase Overrides
478
479         // This seems to always returns System.Void.
480         internal override Type GetReturnType() { return Signature.ReturnType; } 
481         
482         [System.Security.SecuritySafeCritical]  // auto-generated
483         internal override ParameterInfo[] GetParametersNoCopy()
484         {
485             if (m_parameters == null)
486                 m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
487
488             return m_parameters;
489         }
490
491         [Pure]
492         public override ParameterInfo[] GetParameters()
493         {
494             ParameterInfo[] parameters = GetParametersNoCopy();
495
496             if (parameters.Length == 0)
497                 return parameters;
498             
499             ParameterInfo[] ret = new ParameterInfo[parameters.Length];
500             Array.Copy(parameters, ret, parameters.Length);
501             return ret;
502         }
503
504         public override MethodImplAttributes GetMethodImplementationFlags()
505         {
506             return RuntimeMethodHandle.GetImplAttributes(this);
507         }
508
509         public override RuntimeMethodHandle MethodHandle 
510         {
511             get
512             {
513                 Type declaringType = DeclaringType;
514                 if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
515                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
516                 return new RuntimeMethodHandle(this);
517             }
518         }
519
520         public override MethodAttributes Attributes 
521         {
522             get
523             {
524                 return m_methodAttributes;
525             }
526         }
527
528         public override CallingConventions CallingConvention 
529         {
530             get
531             {
532                 return Signature.CallingConvention;
533             }
534         }
535
536         internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg)
537         {
538             if (declaringType == null)
539                 throw new ArgumentNullException("declaringType");
540             Contract.EndContractBlock();
541             
542             // ctor is ReflectOnly
543             if (declaringType is ReflectionOnlyType)
544                 throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
545             
546             // ctor is declared on interface class
547             else if (declaringType.IsInterface)
548                 throw new MemberAccessException(
549                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType));
550             
551             // ctor is on an abstract class
552             else if (declaringType.IsAbstract)
553                 throw new MemberAccessException(
554                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType));
555             
556             // ctor is on a class that contains stack pointers
557             else if (declaringType.GetRootElementType() == typeof(ArgIterator))
558                 throw new NotSupportedException();
559             
560             // ctor is vararg
561             else if (isVarArg)
562                 throw new NotSupportedException();
563                         
564             // ctor is generic or on a generic class
565             else if (declaringType.ContainsGenericParameters)
566             {
567 #if FEATURE_LEGACYNETCF
568                 if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
569                     throw new ArgumentException(
570                         String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType));
571                 else
572 #endif
573                 throw new MemberAccessException(
574                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType));
575             }
576
577             // ctor is declared on System.Void
578             else if (declaringType == typeof(void))
579                 throw new MemberAccessException(Environment.GetResourceString("Access_Void"));
580         }
581
582         internal void ThrowNoInvokeException()
583         {
584             CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
585
586             // ctor is .cctor
587             if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
588                 throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit"));
589             
590             throw new TargetException();
591         }
592
593         [System.Security.SecuritySafeCritical]  // auto-generated
594         [DebuggerStepThroughAttribute]
595         [Diagnostics.DebuggerHidden]
596         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
597         public override Object Invoke(
598             Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
599         {
600             INVOCATION_FLAGS invocationFlags = InvocationFlags;
601
602             if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) 
603                 ThrowNoInvokeException();
604
605             // check basic method consistency. This call will throw if there are problems in the target/method relationship
606             CheckConsistency(obj);
607
608 #if FEATURE_APPX
609             if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) 
610             {
611                 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
612                 RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
613                 if (caller != null && !caller.IsSafeForReflection())
614                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
615             }
616 #endif
617
618             if (obj != null)
619             {
620
621 #if FEATURE_CORECLR
622                 // For unverifiable code, we require the caller to be critical.
623                 // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
624                 invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
625 #else // FEATURE_CORECLR
626                 new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
627 #endif // FEATURE_CORECLR
628
629             }
630
631             if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) 
632             {
633 #if !FEATURE_CORECLR
634                 if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
635                     CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
636                 if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
637 #endif // !FEATURE_CORECLR
638                     RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
639             }
640
641             Signature sig = Signature;
642
643             // get the signature
644             int formalCount = sig.Arguments.Length;
645             int actualCount =(parameters != null) ? parameters.Length : 0;
646             if (formalCount != actualCount)
647                 throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
648             
649             // if we are here we passed all the previous checks. Time to look at the arguments
650             if (actualCount > 0) 
651             {
652                 Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
653                 Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false);
654                 // copy out. This should be made only if ByRef are present.
655                 for (int index = 0; index < arguments.Length; index++) 
656                     parameters[index] = arguments[index];
657                 return retValue;
658             }
659             return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false);
660         }
661         
662
663         [System.Security.SecuritySafeCritical] // overrides SC member
664 #pragma warning disable 618
665         [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
666 #pragma warning restore 618
667         public override MethodBody GetMethodBody()
668         {
669             MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
670             if (mb != null) 
671                 mb.m_methodBase = this;
672             return mb;
673         }
674
675         public override bool IsSecurityCritical
676         {
677             get { return RuntimeMethodHandle.IsSecurityCritical(this); }
678         }
679
680         public override bool IsSecuritySafeCritical
681         {
682             get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
683         }
684
685         public override bool IsSecurityTransparent
686         {
687             get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
688         }
689
690         public override bool ContainsGenericParameters
691         {
692             get
693             {
694                 return (DeclaringType != null && DeclaringType.ContainsGenericParameters);
695             }
696         }
697         #endregion
698
699         #region ConstructorInfo Overrides
700         [System.Security.SecuritySafeCritical]  // auto-generated
701         [DebuggerStepThroughAttribute]
702         [Diagnostics.DebuggerHidden]
703         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
704         public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
705         {
706             INVOCATION_FLAGS invocationFlags = InvocationFlags;
707
708             // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context
709             RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle;
710             
711             if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0)
712                 ThrowNoInvokeException();
713
714 #if FEATURE_APPX
715             if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) 
716             {
717                 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
718                 RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
719                 if (caller != null && !caller.IsSafeForReflection())
720                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
721             }
722 #endif
723
724             if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) 
725             {
726 #if !FEATURE_CORECLR
727                 if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) 
728                     CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
729                 if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)  != 0) 
730 #endif // !FEATURE_CORECLR
731                     RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE));
732 #if !FEATURE_CORECLR
733                 if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0)
734                     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
735 #endif // !FEATURE_CORECLR
736             }
737
738             // get the signature
739             Signature sig = Signature;
740
741             int formalCount = sig.Arguments.Length;
742             int actualCount =(parameters != null) ? parameters.Length : 0;
743             if (formalCount != actualCount)
744                 throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
745
746             // We don't need to explicitly invoke the class constructor here,
747             // JIT/NGen will insert the call to .cctor in the instance ctor.
748
749             // if we are here we passed all the previous checks. Time to look at the arguments
750             if (actualCount > 0) 
751             {
752                 Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
753                 Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true);
754                 // copy out. This should be made only if ByRef are present.
755                 for (int index = 0; index < arguments.Length; index++) 
756                     parameters[index] = arguments[index];
757                 return retValue;
758             }
759             return RuntimeMethodHandle.InvokeMethod(null, null, sig, true);
760         }
761         #endregion
762     
763         #region ISerializable Implementation
764         [System.Security.SecurityCritical]  // auto-generated
765         public void GetObjectData(SerializationInfo info, StreamingContext context)
766         {
767             if (info == null)
768                 throw new ArgumentNullException("info");
769             Contract.EndContractBlock();
770             MemberInfoSerializationHolder.GetSerializationInfo(
771                 info,
772                 Name,
773                 ReflectedTypeInternal,
774                 ToString(),
775                 SerializationToString(),
776                 MemberTypes.Constructor,
777                 null);
778         }
779
780         internal string SerializationToString()
781         {
782             // We don't need the return type for constructors.
783             return FormatNameAndSig(true);
784         }
785
786         internal void SerializationInvoke(Object target, SerializationInfo info, StreamingContext context)
787         {
788             RuntimeMethodHandle.SerializationInvoke(this, target, info, ref context);
789         }
790        #endregion
791     }
792
793 }