2 // MonoMethod.cs: The class used to represent methods from the mono runtime.
5 // Paolo Molaro (lupus@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // (C) 2001 Ximian, Inc. http://www.ximian.com
9 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
10 // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections.Generic;
33 using System.Globalization;
34 using System.Runtime.CompilerServices;
35 using System.Runtime.InteropServices;
36 using System.Runtime.Serialization;
38 using System.Reflection.Emit;
40 using System.Security;
41 using System.Threading;
43 using System.Diagnostics;
44 using System.Diagnostics.Contracts;
46 namespace System.Reflection {
48 internal struct MonoMethodInfo
50 #pragma warning disable 649
53 internal MethodAttributes attrs;
54 internal MethodImplAttributes iattrs;
55 private CallingConventions callconv;
56 #pragma warning restore 649
58 [MethodImplAttribute(MethodImplOptions.InternalCall)]
59 static extern void get_method_info (IntPtr handle, out MonoMethodInfo info);
61 [MethodImplAttribute(MethodImplOptions.InternalCall)]
62 static extern int get_method_attributes (IntPtr handle);
64 internal static MonoMethodInfo GetMethodInfo (IntPtr handle)
67 MonoMethodInfo.get_method_info (handle, out info);
71 internal static Type GetDeclaringType (IntPtr handle)
73 return GetMethodInfo (handle).parent;
76 internal static Type GetReturnType (IntPtr handle)
78 return GetMethodInfo (handle).ret;
81 internal static MethodAttributes GetAttributes (IntPtr handle)
83 return (MethodAttributes)get_method_attributes (handle);
86 internal static CallingConventions GetCallingConvention (IntPtr handle)
88 return GetMethodInfo (handle).callconv;
91 internal static MethodImplAttributes GetMethodImplementationFlags (IntPtr handle)
93 return GetMethodInfo (handle).iattrs;
96 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97 static extern ParameterInfo[] get_parameter_info (IntPtr handle, MemberInfo member);
99 static internal ParameterInfo[] GetParametersInfo (IntPtr handle, MemberInfo member)
101 return get_parameter_info (handle, member);
104 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105 static extern MarshalAsAttribute get_retval_marshal (IntPtr handle);
107 static internal ParameterInfo GetReturnParameterInfo (MonoMethod method)
109 return ParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle));
113 abstract class RuntimeMethodInfo : MethodInfo, ISerializable
115 internal BindingFlags BindingFlags {
121 public override Module Module {
123 return GetRuntimeModule ();
127 RuntimeType ReflectedTypeInternal {
129 return (RuntimeType) ReflectedType;
133 internal override string FormatNameAndSig (bool serialization)
135 // Serialization uses ToString to resolve MethodInfo overloads.
136 StringBuilder sbName = new StringBuilder(Name);
138 // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
139 // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
140 TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;
143 sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));
146 ParameterInfo.FormatParameters (sbName, GetParametersNoCopy (), CallingConvention, serialization);
149 return sbName.ToString();
152 public override String ToString()
154 return ReturnType.FormatTypeName() + " " + FormatNameAndSig(false);
157 internal RuntimeModule GetRuntimeModule ()
159 return ((RuntimeType)DeclaringType).GetRuntimeModule();
162 #region ISerializable Implementation
163 public void GetObjectData(SerializationInfo info, StreamingContext context)
166 throw new ArgumentNullException("info");
167 Contract.EndContractBlock();
169 MemberInfoSerializationHolder.GetSerializationInfo(
172 ReflectedTypeInternal,
174 SerializationToString(),
176 IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
179 internal string SerializationToString()
181 return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
187 * Note: most of this class needs to be duplicated for the contructor, since
188 * the .NET reflection class hierarchy is so broken.
191 [StructLayout (LayoutKind.Sequential)]
192 internal class MonoMethod : RuntimeMethodInfo
194 #pragma warning disable 649
195 internal IntPtr mhandle;
198 #pragma warning restore 649
200 internal MonoMethod () {
203 internal MonoMethod (RuntimeMethodHandle mhandle) {
204 this.mhandle = mhandle.Value;
207 [MethodImplAttribute(MethodImplOptions.InternalCall)]
208 internal static extern string get_name (MethodBase method);
210 [MethodImplAttribute(MethodImplOptions.InternalCall)]
211 internal static extern MonoMethod get_base_method (MonoMethod method, bool definition);
213 public override MethodInfo GetBaseDefinition ()
215 return get_base_method (this, true);
218 internal override MethodInfo GetBaseMethod ()
220 return get_base_method (this, false);
223 public override ParameterInfo ReturnParameter {
225 return MonoMethodInfo.GetReturnParameterInfo (this);
229 public override Type ReturnType {
231 return MonoMethodInfo.GetReturnType (mhandle);
234 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
236 return MonoMethodInfo.GetReturnParameterInfo (this);
240 public override MethodImplAttributes GetMethodImplementationFlags ()
242 return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
245 public override ParameterInfo[] GetParameters ()
247 var src = MonoMethodInfo.GetParametersInfo (mhandle, this);
251 // Have to clone because GetParametersInfo icall returns cached value
252 var dest = new ParameterInfo [src.Length];
253 Array.FastCopy (src, 0, dest, 0, src.Length);
257 internal override ParameterInfo[] GetParametersInternal ()
259 return MonoMethodInfo.GetParametersInfo (mhandle, this);
262 internal override int GetParametersCount ()
264 return MonoMethodInfo.GetParametersInfo (mhandle, this).Length;
268 * InternalInvoke() receives the parameters correctly converted by the
269 * binder to match the types of the method signature.
271 [MethodImplAttribute(MethodImplOptions.InternalCall)]
272 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
275 [DebuggerStepThrough]
276 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
279 binder = Type.DefaultBinder;
281 /*Avoid allocating an array every time*/
282 ParameterInfo[] pinfo = GetParametersInternal ();
283 ConvertValues (binder, parameters, pinfo, culture, invokeAttr);
285 if (ContainsGenericParameters)
286 throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
292 // The ex argument is used to distinguish exceptions thrown by the icall
293 // from the exceptions thrown by the called method (which need to be
294 // wrapped in TargetInvocationException).
295 o = InternalInvoke (obj, parameters, out exc);
296 } catch (ThreadAbortException) {
299 } catch (MethodAccessException) {
302 } catch (Exception e) {
303 throw new TargetInvocationException (e);
311 internal static void ConvertValues (Binder binder, object[] args, ParameterInfo[] pinfo, CultureInfo culture, BindingFlags invokeAttr)
314 if (pinfo.Length == 0)
317 throw new TargetParameterCountException ();
320 if (pinfo.Length != args.Length)
321 throw new TargetParameterCountException ();
323 for (int i = 0; i < args.Length; ++i) {
326 if (arg == Type.Missing) {
327 if (pi.DefaultValue == System.DBNull.Value)
328 throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters");
330 args [i] = pi.DefaultValue;
334 var rt = (RuntimeType) pi.ParameterType;
335 args [i] = rt.CheckValue (arg, binder, culture, invokeAttr);
339 public override RuntimeMethodHandle MethodHandle {
341 return new RuntimeMethodHandle (mhandle);
345 public override MethodAttributes Attributes {
347 return MonoMethodInfo.GetAttributes (mhandle);
351 public override CallingConventions CallingConvention {
353 return MonoMethodInfo.GetCallingConvention (mhandle);
357 public override Type ReflectedType {
362 public override Type DeclaringType {
364 return MonoMethodInfo.GetDeclaringType (mhandle);
367 public override string Name {
371 return get_name (this);
375 public override bool IsDefined (Type attributeType, bool inherit) {
376 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
379 public override object[] GetCustomAttributes( bool inherit) {
380 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
382 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
383 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
386 [MethodImplAttribute(MethodImplOptions.InternalCall)]
387 internal extern void GetPInvoke (out PInvokeAttributes flags, out string entryPoint, out string dllName);
389 internal object[] GetPseudoCustomAttributes ()
393 /* MS.NET doesn't report MethodImplAttribute */
395 MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
396 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
398 if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
403 object[] attrs = new object [count];
406 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
407 attrs [count ++] = new PreserveSigAttribute ();
408 if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) {
409 attrs [count ++] = DllImportAttribute.GetCustomAttribute (this);
415 public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
417 if (methodInstantiation == null)
418 throw new ArgumentNullException ("methodInstantiation");
420 if (!IsGenericMethodDefinition)
421 throw new InvalidOperationException ("not a generic method definition");
423 /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
424 if (GetGenericArguments ().Length != methodInstantiation.Length)
425 throw new ArgumentException ("Incorrect length");
427 bool hasUserType = false;
428 foreach (Type type in methodInstantiation) {
430 throw new ArgumentNullException ();
431 if (!(type is MonoType))
437 throw new NotSupportedException ("User types are not supported under full aot");
439 return new MethodOnTypeBuilderInst (this, methodInstantiation);
442 MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
444 throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
448 [MethodImplAttribute(MethodImplOptions.InternalCall)]
449 extern MethodInfo MakeGenericMethod_impl (Type [] types);
451 [MethodImplAttribute(MethodImplOptions.InternalCall)]
452 public override extern Type [] GetGenericArguments ();
454 [MethodImplAttribute(MethodImplOptions.InternalCall)]
455 extern MethodInfo GetGenericMethodDefinition_impl ();
457 public override MethodInfo GetGenericMethodDefinition ()
459 MethodInfo res = GetGenericMethodDefinition_impl ();
461 throw new InvalidOperationException ();
466 public override extern bool IsGenericMethodDefinition {
467 [MethodImplAttribute(MethodImplOptions.InternalCall)]
471 public override extern bool IsGenericMethod {
472 [MethodImplAttribute(MethodImplOptions.InternalCall)]
476 public override bool ContainsGenericParameters {
478 if (IsGenericMethod) {
479 foreach (Type arg in GetGenericArguments ())
480 if (arg.ContainsGenericParameters)
483 return DeclaringType.ContainsGenericParameters;
487 public override MethodBody GetMethodBody () {
488 return GetMethodBody (mhandle);
491 public override IList<CustomAttributeData> GetCustomAttributesData () {
492 return CustomAttributeData.GetCustomAttributes (this);
495 //seclevel { transparent = 0, safe-critical = 1, critical = 2}
496 [MethodImplAttribute(MethodImplOptions.InternalCall)]
497 public extern int get_core_clr_security_level ();
499 public override bool IsSecurityTransparent {
500 get { return get_core_clr_security_level () == 0; }
503 public override bool IsSecurityCritical {
504 get { return get_core_clr_security_level () > 0; }
507 public override bool IsSecuritySafeCritical {
508 get { return get_core_clr_security_level () == 1; }
513 abstract class RuntimeConstructorInfo : ConstructorInfo, ISerializable
515 public override Module Module {
517 return GetRuntimeModule ();
521 internal RuntimeModule GetRuntimeModule ()
523 return RuntimeTypeHandle.GetModule((RuntimeType)DeclaringType);
526 internal BindingFlags BindingFlags {
532 RuntimeType ReflectedTypeInternal {
534 return (RuntimeType) ReflectedType;
538 #region ISerializable Implementation
539 public void GetObjectData(SerializationInfo info, StreamingContext context)
542 throw new ArgumentNullException("info");
543 Contract.EndContractBlock();
544 MemberInfoSerializationHolder.GetSerializationInfo(
547 ReflectedTypeInternal,
549 SerializationToString(),
550 MemberTypes.Constructor,
554 internal string SerializationToString()
556 // We don't need the return type for constructors.
557 return FormatNameAndSig(true);
560 internal void SerializationInvoke (Object target, SerializationInfo info, StreamingContext context)
562 Invoke (target, new object[] { info, context });
568 [StructLayout (LayoutKind.Sequential)]
569 internal class MonoCMethod : RuntimeConstructorInfo
571 #pragma warning disable 649
572 internal IntPtr mhandle;
575 #pragma warning restore 649
577 public override MethodImplAttributes GetMethodImplementationFlags ()
579 return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
582 public override ParameterInfo[] GetParameters ()
584 return MonoMethodInfo.GetParametersInfo (mhandle, this);
587 internal override ParameterInfo[] GetParametersInternal ()
589 return MonoMethodInfo.GetParametersInfo (mhandle, this);
592 internal override int GetParametersCount ()
594 var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
595 return pi == null ? 0 : pi.Length;
599 * InternalInvoke() receives the parameters correctly converted by the binder
600 * to match the types of the method signature.
602 [MethodImplAttribute(MethodImplOptions.InternalCall)]
603 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
606 [DebuggerStepThrough]
607 public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
611 throw new TargetException ("Instance constructor requires a target");
612 } else if (!DeclaringType.IsInstanceOfType (obj)) {
613 throw new TargetException ("Constructor does not match target type");
616 return DoInvoke (obj, invokeAttr, binder, parameters, culture);
619 object DoInvoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
622 binder = Type.DefaultBinder;
624 ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
626 MonoMethod.ConvertValues (binder, parameters, pinfo, culture, invokeAttr);
628 if (obj == null && DeclaringType.ContainsGenericParameters)
629 throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
631 if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
632 throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
635 return InternalInvoke (obj, parameters);
638 public object InternalInvoke (object obj, object[] parameters)
644 o = InternalInvoke (obj, parameters, out exc);
646 } catch (MethodAccessException) {
649 } catch (Exception e) {
650 throw new TargetInvocationException (e);
656 return obj == null ? o : null;
660 [DebuggerStepThrough]
661 public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
663 return DoInvoke (null, invokeAttr, binder, parameters, culture);
666 public override RuntimeMethodHandle MethodHandle {
668 return new RuntimeMethodHandle (mhandle);
672 public override MethodAttributes Attributes {
674 return MonoMethodInfo.GetAttributes (mhandle);
678 public override CallingConventions CallingConvention {
680 return MonoMethodInfo.GetCallingConvention (mhandle);
684 public override bool ContainsGenericParameters {
686 return DeclaringType.ContainsGenericParameters;
690 public override Type ReflectedType {
695 public override Type DeclaringType {
697 return MonoMethodInfo.GetDeclaringType (mhandle);
700 public override string Name {
704 return MonoMethod.get_name (this);
708 public override bool IsDefined (Type attributeType, bool inherit) {
709 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
712 public override object[] GetCustomAttributes( bool inherit) {
713 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
716 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
717 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
720 public override MethodBody GetMethodBody () {
721 return GetMethodBody (mhandle);
724 public override string ToString () {
725 StringBuilder sb = new StringBuilder ();
729 ParameterInfo[] p = GetParameters ();
730 for (int i = 0; i < p.Length; ++i) {
733 sb.Append (p[i].ParameterType.Name);
735 if (CallingConvention == CallingConventions.Any)
738 return sb.ToString ();
741 public override IList<CustomAttributeData> GetCustomAttributesData () {
742 return CustomAttributeData.GetCustomAttributes (this);