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 ParameterInfo[] src = MonoMethodInfo.GetParametersInfo (mhandle, this);
174 ParameterInfo[] res = new ParameterInfo [src.Length];
179 internal override int GetParameterCount ()
181 var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
182 return pi == null ? 0 : pi.Length;
186 * InternalInvoke() receives the parameters correctly converted by the
187 * binder to match the types of the method signature.
189 [MethodImplAttribute(MethodImplOptions.InternalCall)]
190 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
193 [DebuggerStepThrough]
194 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
197 binder = Binder.DefaultBinder;
199 /*Avoid allocating an array every time*/
200 ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
201 if (!binder.ConvertArgs (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0))
202 throw new ArgumentException ("failed to convert parameters");
205 if (SecurityManager.SecurityEnabled) {
206 // sadly Attributes doesn't tell us which kind of security action this is so
207 // we must do it the hard way - and it also means that we can skip calling
208 // Attribute (which is another an icall)
209 SecurityManager.ReflectedLinkDemandInvoke (this);
213 if (ContainsGenericParameters)
214 throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
220 // The ex argument is used to distinguish exceptions thrown by the icall
221 // from the exceptions thrown by the called method (which need to be
222 // wrapped in TargetInvocationException).
223 o = InternalInvoke (obj, parameters, out exc);
224 } catch (ThreadAbortException) {
227 } catch (MethodAccessException) {
230 } catch (Exception e) {
231 throw new TargetInvocationException (e);
239 public override RuntimeMethodHandle MethodHandle {
241 return new RuntimeMethodHandle (mhandle);
245 public override MethodAttributes Attributes {
247 return MonoMethodInfo.GetAttributes (mhandle);
251 public override CallingConventions CallingConvention {
253 return MonoMethodInfo.GetCallingConvention (mhandle);
257 public override Type ReflectedType {
262 public override Type DeclaringType {
264 return MonoMethodInfo.GetDeclaringType (mhandle);
267 public override string Name {
271 return get_name (this);
275 public override bool IsDefined (Type attributeType, bool inherit) {
276 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
279 public override object[] GetCustomAttributes( bool inherit) {
280 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
282 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
283 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
286 [MethodImplAttribute(MethodImplOptions.InternalCall)]
287 internal static extern DllImportAttribute GetDllImportAttribute (IntPtr mhandle);
289 internal object[] GetPseudoCustomAttributes ()
293 /* MS.NET doesn't report MethodImplAttribute */
295 MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
296 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
298 if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
303 object[] attrs = new object [count];
306 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
307 attrs [count ++] = new PreserveSigAttribute ();
308 if ((info.attrs & MethodAttributes.PinvokeImpl) != 0) {
309 DllImportAttribute attr = GetDllImportAttribute (mhandle);
310 if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
311 attr.PreserveSig = true;
312 attrs [count ++] = attr;
318 static bool ShouldPrintFullName (Type type) {
319 return type.IsClass && (!type.IsPointer ||
320 (!type.GetElementType ().IsPrimitive && !type.GetElementType ().IsNested));
323 public override string ToString () {
324 StringBuilder sb = new StringBuilder ();
325 Type retType = ReturnType;
326 if (ShouldPrintFullName (retType))
327 sb.Append (retType.ToString ());
329 sb.Append (retType.Name);
332 if (IsGenericMethod) {
333 Type[] gen_params = GetGenericArguments ();
335 for (int j = 0; j < gen_params.Length; j++) {
338 sb.Append (gen_params [j].Name);
343 ParameterInfo[] p = GetParameters ();
344 for (int i = 0; i < p.Length; ++i) {
347 Type pt = p[i].ParameterType;
348 bool byref = pt.IsByRef;
350 pt = pt.GetElementType ();
351 if (ShouldPrintFullName (pt))
352 sb.Append (pt.ToString ());
356 sb.Append (" ByRef");
358 if ((CallingConvention & CallingConventions.VarArgs) != 0) {
365 return sb.ToString ();
370 public void GetObjectData(SerializationInfo info, StreamingContext context)
372 Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
373 ? GetGenericArguments () : null;
374 MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
377 public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
379 if (methodInstantiation == null)
380 throw new ArgumentNullException ("methodInstantiation");
382 if (!IsGenericMethodDefinition)
383 throw new InvalidOperationException ("not a generic method definition");
385 /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
386 if (GetGenericArguments ().Length != methodInstantiation.Length)
387 throw new ArgumentException ("Incorrect length");
389 bool hasUserType = false;
390 foreach (Type type in methodInstantiation) {
392 throw new ArgumentNullException ();
393 if (!(type is MonoType))
397 #if !FULL_AOT_RUNTIME
399 return new MethodOnTypeBuilderInst (this, methodInstantiation);
402 MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
404 throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
408 [MethodImplAttribute(MethodImplOptions.InternalCall)]
409 extern MethodInfo MakeGenericMethod_impl (Type [] types);
411 [MethodImplAttribute(MethodImplOptions.InternalCall)]
412 public override extern Type [] GetGenericArguments ();
414 [MethodImplAttribute(MethodImplOptions.InternalCall)]
415 extern MethodInfo GetGenericMethodDefinition_impl ();
417 public override MethodInfo GetGenericMethodDefinition ()
419 MethodInfo res = GetGenericMethodDefinition_impl ();
421 throw new InvalidOperationException ();
426 public override extern bool IsGenericMethodDefinition {
427 [MethodImplAttribute(MethodImplOptions.InternalCall)]
431 public override extern bool IsGenericMethod {
432 [MethodImplAttribute(MethodImplOptions.InternalCall)]
436 public override bool ContainsGenericParameters {
438 if (IsGenericMethod) {
439 foreach (Type arg in GetGenericArguments ())
440 if (arg.ContainsGenericParameters)
443 return DeclaringType.ContainsGenericParameters;
447 public override MethodBody GetMethodBody () {
448 return GetMethodBody (mhandle);
452 public override IList<CustomAttributeData> GetCustomAttributesData () {
453 return CustomAttributeData.GetCustomAttributes (this);
458 [StructLayout (LayoutKind.Sequential)]
459 internal class MonoCMethod : ConstructorInfo, ISerializable
461 #pragma warning disable 649
462 internal IntPtr mhandle;
465 #pragma warning restore 649
467 public override MethodImplAttributes GetMethodImplementationFlags ()
469 return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
472 public override ParameterInfo[] GetParameters ()
474 return MonoMethodInfo.GetParametersInfo (mhandle, this);
477 internal override int GetParameterCount ()
479 var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
480 return pi == null ? 0 : pi.Length;
484 * InternalInvoke() receives the parameters corretcly converted by the binder
485 * to match the types of the method signature.
487 [MethodImplAttribute(MethodImplOptions.InternalCall)]
488 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
491 [DebuggerStepThrough]
492 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
495 binder = Binder.DefaultBinder;
497 ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
499 if (!binder.ConvertArgs (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0))
500 throw new ArgumentException ("failed to convert parameters");
503 if (SecurityManager.SecurityEnabled) {
504 // sadly Attributes doesn't tell us which kind of security action this is so
505 // we must do it the hard way - and it also means that we can skip calling
506 // Attribute (which is another an icall)
507 SecurityManager.ReflectedLinkDemandInvoke (this);
511 if (obj == null && DeclaringType.ContainsGenericParameters)
512 throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
514 if ((invokeAttr & BindingFlags.CreateInstance) != 0 && DeclaringType.IsAbstract) {
515 throw new MemberAccessException (String.Format ("Cannot create an instance of {0} because it is an abstract class", DeclaringType));
518 Exception exc = null;
522 o = InternalInvoke (obj, parameters, out exc);
524 } catch (MethodAccessException) {
527 } catch (Exception e) {
528 throw new TargetInvocationException (e);
533 return (obj == null) ? o : null;
537 [DebuggerStepThrough]
538 public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
540 return Invoke (null, invokeAttr, binder, parameters, culture);
543 public override RuntimeMethodHandle MethodHandle {
545 return new RuntimeMethodHandle (mhandle);
549 public override MethodAttributes Attributes {
551 return MonoMethodInfo.GetAttributes (mhandle);
555 public override CallingConventions CallingConvention {
557 return MonoMethodInfo.GetCallingConvention (mhandle);
561 public override Type ReflectedType {
566 public override Type DeclaringType {
568 return MonoMethodInfo.GetDeclaringType (mhandle);
571 public override string Name {
575 return MonoMethod.get_name (this);
579 public override bool IsDefined (Type attributeType, bool inherit) {
580 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
583 public override object[] GetCustomAttributes( bool inherit) {
584 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
587 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
588 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
591 public override MethodBody GetMethodBody () {
592 return GetMethodBody (mhandle);
595 public override string ToString () {
596 StringBuilder sb = new StringBuilder ();
600 ParameterInfo[] p = GetParameters ();
601 for (int i = 0; i < p.Length; ++i) {
604 sb.Append (p[i].ParameterType.Name);
606 if (CallingConvention == CallingConventions.Any)
609 return sb.ToString ();
613 public void GetObjectData(SerializationInfo info, StreamingContext context)
615 MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
619 public override IList<CustomAttributeData> GetCustomAttributesData () {
620 return CustomAttributeData.GetCustomAttributes (this);