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 new ParameterInfo (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 static bool ShouldPrintFullName (Type type) {
326 return type.IsClass && (!type.IsPointer ||
327 (!type.GetElementType ().IsPrimitive && !type.GetElementType ().IsNested));
330 public override string ToString () {
331 StringBuilder sb = new StringBuilder ();
332 Type retType = ReturnType;
333 if (ShouldPrintFullName (retType))
334 sb.Append (retType.ToString ());
336 sb.Append (retType.Name);
339 if (IsGenericMethod) {
340 Type[] gen_params = GetGenericArguments ();
342 for (int j = 0; j < gen_params.Length; j++) {
345 sb.Append (gen_params [j].Name);
350 ParameterInfo[] p = GetParametersInternal ();
351 for (int i = 0; i < p.Length; ++i) {
354 Type pt = p[i].ParameterType;
355 bool byref = pt.IsByRef;
357 pt = pt.GetElementType ();
358 if (ShouldPrintFullName (pt))
359 sb.Append (pt.ToString ());
363 sb.Append (" ByRef");
365 if ((CallingConvention & CallingConventions.VarArgs) != 0) {
372 return sb.ToString ();
377 public void GetObjectData(SerializationInfo info, StreamingContext context)
379 Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
380 ? GetGenericArguments () : null;
381 MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
384 public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
386 if (methodInstantiation == null)
387 throw new ArgumentNullException ("methodInstantiation");
389 if (!IsGenericMethodDefinition)
390 throw new InvalidOperationException ("not a generic method definition");
392 /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
393 if (GetGenericArguments ().Length != methodInstantiation.Length)
394 throw new ArgumentException ("Incorrect length");
396 bool hasUserType = false;
397 foreach (Type type in methodInstantiation) {
399 throw new ArgumentNullException ();
400 if (!(type is MonoType))
406 throw new NotSupportedException ("User types are not supported under full aot");
408 return new MethodOnTypeBuilderInst (this, methodInstantiation);
411 MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
413 throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
417 [MethodImplAttribute(MethodImplOptions.InternalCall)]
418 extern MethodInfo MakeGenericMethod_impl (Type [] types);
420 [MethodImplAttribute(MethodImplOptions.InternalCall)]
421 public override extern Type [] GetGenericArguments ();
423 [MethodImplAttribute(MethodImplOptions.InternalCall)]
424 extern MethodInfo GetGenericMethodDefinition_impl ();
426 public override MethodInfo GetGenericMethodDefinition ()
428 MethodInfo res = GetGenericMethodDefinition_impl ();
430 throw new InvalidOperationException ();
435 public override extern bool IsGenericMethodDefinition {
436 [MethodImplAttribute(MethodImplOptions.InternalCall)]
440 public override extern bool IsGenericMethod {
441 [MethodImplAttribute(MethodImplOptions.InternalCall)]
445 public override bool ContainsGenericParameters {
447 if (IsGenericMethod) {
448 foreach (Type arg in GetGenericArguments ())
449 if (arg.ContainsGenericParameters)
452 return DeclaringType.ContainsGenericParameters;
456 public override MethodBody GetMethodBody () {
457 return GetMethodBody (mhandle);
461 public override IList<CustomAttributeData> GetCustomAttributesData () {
462 return CustomAttributeData.GetCustomAttributes (this);
467 [StructLayout (LayoutKind.Sequential)]
468 internal class MonoCMethod : ConstructorInfo, ISerializable
470 #pragma warning disable 649
471 internal IntPtr mhandle;
474 #pragma warning restore 649
476 public override MethodImplAttributes GetMethodImplementationFlags ()
478 return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
481 public override ParameterInfo[] GetParameters ()
483 return MonoMethodInfo.GetParametersInfo (mhandle, this);
486 internal override ParameterInfo[] GetParametersInternal ()
488 return MonoMethodInfo.GetParametersInfo (mhandle, this);
491 internal override int GetParametersCount ()
493 var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
494 return pi == null ? 0 : pi.Length;
498 * InternalInvoke() receives the parameters correctly converted by the binder
499 * to match the types of the method signature.
501 [MethodImplAttribute(MethodImplOptions.InternalCall)]
502 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
505 [DebuggerStepThrough]
506 public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
510 throw new TargetException ("Instance constructor requires a target");
511 } else if (!DeclaringType.IsInstanceOfType (obj)) {
512 throw new TargetException ("Constructor does not match target type");
515 return DoInvoke (obj, invokeAttr, binder, parameters, culture);
518 object DoInvoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
521 binder = Binder.DefaultBinder;
523 ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
525 binder.ConvertValues (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0);
528 if (SecurityManager.SecurityEnabled) {
529 // sadly Attributes doesn't tell us which kind of security action this is so
530 // we must do it the hard way - and it also means that we can skip calling
531 // Attribute (which is another an icall)
532 SecurityManager.ReflectedLinkDemandInvoke (this);
536 if (obj == null && DeclaringType.ContainsGenericParameters)
537 throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
539 if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
540 throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
543 return InternalInvoke (obj, parameters);
546 public object InternalInvoke (object obj, object[] parameters)
552 o = InternalInvoke (obj, parameters, out exc);
554 } catch (MethodAccessException) {
557 } catch (Exception e) {
558 throw new TargetInvocationException (e);
564 return obj == null ? o : null;
568 [DebuggerStepThrough]
569 public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
571 return DoInvoke (null, invokeAttr, binder, parameters, culture);
574 public override RuntimeMethodHandle MethodHandle {
576 return new RuntimeMethodHandle (mhandle);
580 public override MethodAttributes Attributes {
582 return MonoMethodInfo.GetAttributes (mhandle);
586 public override CallingConventions CallingConvention {
588 return MonoMethodInfo.GetCallingConvention (mhandle);
592 public override Type ReflectedType {
597 public override Type DeclaringType {
599 return MonoMethodInfo.GetDeclaringType (mhandle);
602 public override string Name {
606 return MonoMethod.get_name (this);
610 public override bool IsDefined (Type attributeType, bool inherit) {
611 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
614 public override object[] GetCustomAttributes( bool inherit) {
615 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
618 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
619 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
622 public override MethodBody GetMethodBody () {
623 return GetMethodBody (mhandle);
626 public override string ToString () {
627 StringBuilder sb = new StringBuilder ();
631 ParameterInfo[] p = GetParameters ();
632 for (int i = 0; i < p.Length; ++i) {
635 sb.Append (p[i].ParameterType.Name);
637 if (CallingConvention == CallingConventions.Any)
640 return sb.ToString ();
644 public void GetObjectData(SerializationInfo info, StreamingContext context)
646 MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
650 public override IList<CustomAttributeData> GetCustomAttributesData () {
651 return CustomAttributeData.GetCustomAttributes (this);