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;
45 namespace System.Reflection {
47 internal struct MonoMethodInfo
49 #pragma warning disable 649
52 internal MethodAttributes attrs;
53 internal MethodImplAttributes iattrs;
54 private CallingConventions callconv;
55 #pragma warning restore 649
57 [MethodImplAttribute(MethodImplOptions.InternalCall)]
58 static extern void get_method_info (IntPtr handle, out MonoMethodInfo info);
60 [MethodImplAttribute(MethodImplOptions.InternalCall)]
61 static extern int get_method_attributes (IntPtr handle);
63 internal static MonoMethodInfo GetMethodInfo (IntPtr handle)
66 MonoMethodInfo.get_method_info (handle, out info);
70 internal static Type GetDeclaringType (IntPtr handle)
72 return GetMethodInfo (handle).parent;
75 internal static Type GetReturnType (IntPtr handle)
77 return GetMethodInfo (handle).ret;
80 internal static MethodAttributes GetAttributes (IntPtr handle)
82 return (MethodAttributes)get_method_attributes (handle);
85 internal static CallingConventions GetCallingConvention (IntPtr handle)
87 return GetMethodInfo (handle).callconv;
90 internal static MethodImplAttributes GetMethodImplementationFlags (IntPtr handle)
92 return GetMethodInfo (handle).iattrs;
95 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96 static extern ParameterInfo[] get_parameter_info (IntPtr handle, MemberInfo member);
98 static internal ParameterInfo[] GetParametersInfo (IntPtr handle, MemberInfo member)
100 return get_parameter_info (handle, member);
103 [MethodImplAttribute(MethodImplOptions.InternalCall)]
104 static extern MarshalAsAttribute get_retval_marshal (IntPtr handle);
106 static internal ParameterInfo GetReturnParameterInfo (MonoMethod method)
108 return ParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle));
113 * Note: most of this class needs to be duplicated for the contructor, since
114 * the .NET reflection class hierarchy is so broken.
117 [StructLayout (LayoutKind.Sequential)]
118 internal class MonoMethod : MethodInfo, ISerializable
120 #pragma warning disable 649
121 internal IntPtr mhandle;
124 #pragma warning restore 649
126 internal MonoMethod () {
129 internal MonoMethod (RuntimeMethodHandle mhandle) {
130 this.mhandle = mhandle.Value;
133 [MethodImplAttribute(MethodImplOptions.InternalCall)]
134 internal static extern string get_name (MethodBase method);
136 [MethodImplAttribute(MethodImplOptions.InternalCall)]
137 internal static extern MonoMethod get_base_method (MonoMethod method, bool definition);
139 public override MethodInfo GetBaseDefinition ()
141 return get_base_method (this, true);
144 internal override MethodInfo GetBaseMethod ()
146 return get_base_method (this, false);
149 public override ParameterInfo ReturnParameter {
151 return MonoMethodInfo.GetReturnParameterInfo (this);
155 public override Type ReturnType {
157 return MonoMethodInfo.GetReturnType (mhandle);
160 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
162 return MonoMethodInfo.GetReturnParameterInfo (this);
166 public override MethodImplAttributes GetMethodImplementationFlags ()
168 return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
171 public override ParameterInfo[] GetParameters ()
173 var src = MonoMethodInfo.GetParametersInfo (mhandle, this);
177 // Have to clone because GetParametersInfo icall returns cached value
178 var dest = new ParameterInfo [src.Length];
179 Array.FastCopy (src, 0, dest, 0, src.Length);
183 internal override ParameterInfo[] GetParametersInternal ()
185 return MonoMethodInfo.GetParametersInfo (mhandle, this);
188 internal override int GetParametersCount ()
190 return MonoMethodInfo.GetParametersInfo (mhandle, this).Length;
194 * InternalInvoke() receives the parameters correctly converted by the
195 * binder to match the types of the method signature.
197 [MethodImplAttribute(MethodImplOptions.InternalCall)]
198 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
201 [DebuggerStepThrough]
202 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
205 binder = Binder.DefaultBinder;
207 /*Avoid allocating an array every time*/
208 ParameterInfo[] pinfo = GetParametersInternal ();
209 binder.ConvertValues (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0);
212 if (SecurityManager.SecurityEnabled) {
213 // sadly Attributes doesn't tell us which kind of security action this is so
214 // we must do it the hard way - and it also means that we can skip calling
215 // Attribute (which is another an icall)
216 SecurityManager.ReflectedLinkDemandInvoke (this);
220 if (ContainsGenericParameters)
221 throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
227 // The ex argument is used to distinguish exceptions thrown by the icall
228 // from the exceptions thrown by the called method (which need to be
229 // wrapped in TargetInvocationException).
230 o = InternalInvoke (obj, parameters, out exc);
231 } catch (ThreadAbortException) {
234 } catch (MethodAccessException) {
237 } catch (Exception e) {
238 throw new TargetInvocationException (e);
246 public override RuntimeMethodHandle MethodHandle {
248 return new RuntimeMethodHandle (mhandle);
252 public override MethodAttributes Attributes {
254 return MonoMethodInfo.GetAttributes (mhandle);
258 public override CallingConventions CallingConvention {
260 return MonoMethodInfo.GetCallingConvention (mhandle);
264 public override Type ReflectedType {
269 public override Type DeclaringType {
271 return MonoMethodInfo.GetDeclaringType (mhandle);
274 public override string Name {
278 return get_name (this);
282 public override bool IsDefined (Type attributeType, bool inherit) {
283 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
286 public override object[] GetCustomAttributes( bool inherit) {
287 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
289 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
290 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
293 [MethodImplAttribute(MethodImplOptions.InternalCall)]
294 internal static extern DllImportAttribute GetDllImportAttribute (IntPtr mhandle);
296 internal object[] GetPseudoCustomAttributes ()
300 /* MS.NET doesn't report MethodImplAttribute */
302 MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
303 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
305 if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
310 object[] attrs = new object [count];
313 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
314 attrs [count ++] = new PreserveSigAttribute ();
315 if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) {
316 DllImportAttribute attr = GetDllImportAttribute (mhandle);
317 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
318 attr.PreserveSig = true;
319 attrs [count ++] = attr;
325 public override string ToString () {
326 StringBuilder sb = new StringBuilder ();
327 Type retType = ReturnType;
328 if (Type.ShouldPrintFullName (retType))
329 sb.Append (retType.ToString ());
331 sb.Append (retType.Name);
334 if (IsGenericMethod) {
335 Type[] gen_params = GetGenericArguments ();
337 for (int j = 0; j < gen_params.Length; j++) {
340 sb.Append (gen_params [j].Name);
346 var p = GetParametersInternal ();
347 ParameterInfo.FormatParameters (sb, p);
349 if ((CallingConvention & CallingConventions.VarArgs) != 0) {
356 return sb.ToString ();
361 public void GetObjectData(SerializationInfo info, StreamingContext context)
363 Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
364 ? GetGenericArguments () : null;
365 MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
368 public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
370 if (methodInstantiation == null)
371 throw new ArgumentNullException ("methodInstantiation");
373 if (!IsGenericMethodDefinition)
374 throw new InvalidOperationException ("not a generic method definition");
376 /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
377 if (GetGenericArguments ().Length != methodInstantiation.Length)
378 throw new ArgumentException ("Incorrect length");
380 bool hasUserType = false;
381 foreach (Type type in methodInstantiation) {
383 throw new ArgumentNullException ();
384 if (!(type is MonoType))
390 throw new NotSupportedException ("User types are not supported under full aot");
392 return new MethodOnTypeBuilderInst (this, methodInstantiation);
395 MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
397 throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
401 [MethodImplAttribute(MethodImplOptions.InternalCall)]
402 extern MethodInfo MakeGenericMethod_impl (Type [] types);
404 [MethodImplAttribute(MethodImplOptions.InternalCall)]
405 public override extern Type [] GetGenericArguments ();
407 [MethodImplAttribute(MethodImplOptions.InternalCall)]
408 extern MethodInfo GetGenericMethodDefinition_impl ();
410 public override MethodInfo GetGenericMethodDefinition ()
412 MethodInfo res = GetGenericMethodDefinition_impl ();
414 throw new InvalidOperationException ();
419 public override extern bool IsGenericMethodDefinition {
420 [MethodImplAttribute(MethodImplOptions.InternalCall)]
424 public override extern bool IsGenericMethod {
425 [MethodImplAttribute(MethodImplOptions.InternalCall)]
429 public override bool ContainsGenericParameters {
431 if (IsGenericMethod) {
432 foreach (Type arg in GetGenericArguments ())
433 if (arg.ContainsGenericParameters)
436 return DeclaringType.ContainsGenericParameters;
440 public override MethodBody GetMethodBody () {
441 return GetMethodBody (mhandle);
445 public override IList<CustomAttributeData> GetCustomAttributesData () {
446 return CustomAttributeData.GetCustomAttributes (this);
452 [StructLayout (LayoutKind.Sequential)]
453 internal class MonoCMethod : ConstructorInfo, ISerializable
455 #pragma warning disable 649
456 internal IntPtr mhandle;
459 #pragma warning restore 649
461 public override MethodImplAttributes GetMethodImplementationFlags ()
463 return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
466 public override ParameterInfo[] GetParameters ()
468 return MonoMethodInfo.GetParametersInfo (mhandle, this);
471 internal override ParameterInfo[] GetParametersInternal ()
473 return MonoMethodInfo.GetParametersInfo (mhandle, this);
476 internal override int GetParametersCount ()
478 var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
479 return pi == null ? 0 : pi.Length;
483 * InternalInvoke() receives the parameters correctly converted by the binder
484 * to match the types of the method signature.
486 [MethodImplAttribute(MethodImplOptions.InternalCall)]
487 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
490 [DebuggerStepThrough]
491 public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
495 throw new TargetException ("Instance constructor requires a target");
496 } else if (!DeclaringType.IsInstanceOfType (obj)) {
497 throw new TargetException ("Constructor does not match target type");
500 return DoInvoke (obj, invokeAttr, binder, parameters, culture);
503 object DoInvoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
506 binder = Binder.DefaultBinder;
508 ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
510 binder.ConvertValues (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0);
513 if (SecurityManager.SecurityEnabled) {
514 // sadly Attributes doesn't tell us which kind of security action this is so
515 // we must do it the hard way - and it also means that we can skip calling
516 // Attribute (which is another an icall)
517 SecurityManager.ReflectedLinkDemandInvoke (this);
521 if (obj == null && DeclaringType.ContainsGenericParameters)
522 throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
524 if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
525 throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
528 return InternalInvoke (obj, parameters);
531 public object InternalInvoke (object obj, object[] parameters)
537 o = InternalInvoke (obj, parameters, out exc);
539 } catch (MethodAccessException) {
542 } catch (Exception e) {
543 throw new TargetInvocationException (e);
549 return obj == null ? o : null;
553 [DebuggerStepThrough]
554 public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
556 return DoInvoke (null, invokeAttr, binder, parameters, culture);
559 public override RuntimeMethodHandle MethodHandle {
561 return new RuntimeMethodHandle (mhandle);
565 public override MethodAttributes Attributes {
567 return MonoMethodInfo.GetAttributes (mhandle);
571 public override CallingConventions CallingConvention {
573 return MonoMethodInfo.GetCallingConvention (mhandle);
577 public override Type ReflectedType {
582 public override Type DeclaringType {
584 return MonoMethodInfo.GetDeclaringType (mhandle);
587 public override string Name {
591 return MonoMethod.get_name (this);
595 public override bool IsDefined (Type attributeType, bool inherit) {
596 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
599 public override object[] GetCustomAttributes( bool inherit) {
600 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
603 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
604 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
607 public override MethodBody GetMethodBody () {
608 return GetMethodBody (mhandle);
611 public override string ToString () {
612 StringBuilder sb = new StringBuilder ();
616 ParameterInfo[] p = GetParameters ();
617 for (int i = 0; i < p.Length; ++i) {
620 sb.Append (p[i].ParameterType.Name);
622 if (CallingConvention == CallingConventions.Any)
625 return sb.ToString ();
629 public void GetObjectData(SerializationInfo info, StreamingContext context)
631 MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
635 public override IList<CustomAttributeData> GetCustomAttributesData () {
636 return CustomAttributeData.GetCustomAttributes (this);