68dd9fb88734b0cd9f2ec78f2e63fcb9e51f35c6
[mono.git] / mcs / class / corlib / System.Reflection / MonoMethod.cs
1 //
2 // MonoMethod.cs: The class used to represent methods from the mono runtime.
3 //
4 // Authors:
5 //   Paolo Molaro (lupus@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
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)
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31
32 using System.Collections.Generic;
33 using System.Globalization;
34 using System.Runtime.CompilerServices;
35 using System.Runtime.InteropServices;
36 using System.Runtime.Serialization;
37 #if !FULL_AOT_RUNTIME
38 using System.Reflection.Emit;
39 #endif
40 using System.Security;
41 using System.Threading;
42 using System.Text;
43 using System.Diagnostics;
44
45 namespace System.Reflection {
46         
47         internal struct MonoMethodInfo 
48         {
49 #pragma warning disable 649     
50                 private Type parent;
51                 private Type ret;
52                 internal MethodAttributes attrs;
53                 internal MethodImplAttributes iattrs;
54                 private CallingConventions callconv;
55 #pragma warning restore 649             
56
57                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
58                 static extern void get_method_info (IntPtr handle, out MonoMethodInfo info);
59                 
60                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
61                 static extern int get_method_attributes (IntPtr handle);
62                 
63                 internal static MonoMethodInfo GetMethodInfo (IntPtr handle)
64                 {
65                         MonoMethodInfo info;
66                         MonoMethodInfo.get_method_info (handle, out info);
67                         return info;
68                 }
69
70                 internal static Type GetDeclaringType (IntPtr handle)
71                 {
72                         return GetMethodInfo (handle).parent;
73                 }
74
75                 internal static Type GetReturnType (IntPtr handle)
76                 {
77                         return GetMethodInfo (handle).ret;
78                 }
79
80                 internal static MethodAttributes GetAttributes (IntPtr handle)
81                 {
82                         return (MethodAttributes)get_method_attributes (handle);
83                 }
84
85                 internal static CallingConventions GetCallingConvention (IntPtr handle)
86                 {
87                         return GetMethodInfo (handle).callconv;
88                 }
89
90                 internal static MethodImplAttributes GetMethodImplementationFlags (IntPtr handle)
91                 {
92                         return GetMethodInfo (handle).iattrs;
93                 }
94
95                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96                 static extern ParameterInfo[] get_parameter_info (IntPtr handle, MemberInfo member);
97
98                 static internal ParameterInfo[] GetParametersInfo (IntPtr handle, MemberInfo member)
99                 {
100                         return get_parameter_info (handle, member);
101                 }
102
103                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
104                 static extern MarshalAsAttribute get_retval_marshal (IntPtr handle);
105
106                 static internal ParameterInfo GetReturnParameterInfo (MonoMethod method)
107                 {
108                         return ParameterInfo.New (GetReturnType (method.mhandle), method, get_retval_marshal (method.mhandle));
109                 }
110         };
111         
112         /*
113          * Note: most of this class needs to be duplicated for the contructor, since
114          * the .NET reflection class hierarchy is so broken.
115          */
116         [Serializable()]
117         [StructLayout (LayoutKind.Sequential)]
118         internal class MonoMethod : MethodInfo, ISerializable
119         {
120 #pragma warning disable 649
121                 internal IntPtr mhandle;
122                 string name;
123                 Type reftype;
124 #pragma warning restore 649
125
126                 internal MonoMethod () {
127                 }
128
129                 internal MonoMethod (RuntimeMethodHandle mhandle) {
130                         this.mhandle = mhandle.Value;
131                 }
132                 
133                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
134                 internal static extern string get_name (MethodBase method);
135
136                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
137                 internal static extern MonoMethod get_base_method (MonoMethod method, bool definition);
138
139                 public override MethodInfo GetBaseDefinition ()
140                 {
141                         return get_base_method (this, true);
142                 }
143
144                 internal override MethodInfo GetBaseMethod ()
145                 {
146                         return get_base_method (this, false);
147                 }
148
149                 public override ParameterInfo ReturnParameter {
150                         get {
151                                 return MonoMethodInfo.GetReturnParameterInfo (this);
152                         }
153                 }
154
155                 public override Type ReturnType {
156                         get {
157                                 return MonoMethodInfo.GetReturnType (mhandle);
158                         }
159                 }
160                 public override ICustomAttributeProvider ReturnTypeCustomAttributes { 
161                         get {
162                                 return MonoMethodInfo.GetReturnParameterInfo (this);
163                         }
164                 }
165                 
166                 public override MethodImplAttributes GetMethodImplementationFlags ()
167                 {
168                         return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
169                 }
170
171                 public override ParameterInfo[] GetParameters ()
172                 {
173                         var src = MonoMethodInfo.GetParametersInfo (mhandle, this);
174                         if (src.Length == 0)
175                                 return src;
176
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);
180                         return dest;
181                 }
182
183                 internal override ParameterInfo[] GetParametersInternal ()
184                 {
185                         return MonoMethodInfo.GetParametersInfo (mhandle, this);
186                 }
187                 
188                 internal override int GetParametersCount ()
189                 {
190                         return MonoMethodInfo.GetParametersInfo (mhandle, this).Length;
191                 }
192
193                 /*
194                  * InternalInvoke() receives the parameters correctly converted by the 
195                  * binder to match the types of the method signature.
196                  */
197                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
198                 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
199
200                 [DebuggerHidden]
201                 [DebuggerStepThrough]
202                 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
203                 {
204                         if (binder == null)
205                                 binder = Binder.DefaultBinder;
206
207                         /*Avoid allocating an array every time*/
208                         ParameterInfo[] pinfo = GetParametersInternal ();
209                         binder.ConvertValues (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0);
210
211 #if !NET_2_1
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);
217                         }
218 #endif
219
220                         if (ContainsGenericParameters)
221                                 throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
222
223                         Exception exc;
224                         object o = null;
225
226                         try {
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) {
232                                 throw;
233 #if NET_2_1
234                         } catch (MethodAccessException) {
235                                 throw;
236 #endif
237                         } catch (Exception e) {
238                                 throw new TargetInvocationException (e);
239                         }
240
241                         if (exc != null)
242                                 throw exc;
243                         return o;
244                 }
245
246                 public override RuntimeMethodHandle MethodHandle { 
247                         get {
248                                 return new RuntimeMethodHandle (mhandle);
249                         } 
250                 }
251                 
252                 public override MethodAttributes Attributes { 
253                         get {
254                                 return MonoMethodInfo.GetAttributes (mhandle);
255                         } 
256                 }
257
258                 public override CallingConventions CallingConvention { 
259                         get {
260                                 return MonoMethodInfo.GetCallingConvention (mhandle);
261                         }
262                 }
263                 
264                 public override Type ReflectedType {
265                         get {
266                                 return reftype;
267                         }
268                 }
269                 public override Type DeclaringType {
270                         get {
271                                 return MonoMethodInfo.GetDeclaringType (mhandle);
272                         }
273                 }
274                 public override string Name {
275                         get {
276                                 if (name != null)
277                                         return name;
278                                 return get_name (this);
279                         }
280                 }
281                 
282                 public override bool IsDefined (Type attributeType, bool inherit) {
283                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
284                 }
285
286                 public override object[] GetCustomAttributes( bool inherit) {
287                         return MonoCustomAttrs.GetCustomAttributes (this, inherit);
288                 }
289                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
290                         return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
291                 }
292
293                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
294                 internal static extern DllImportAttribute GetDllImportAttribute (IntPtr mhandle);
295
296                 internal object[] GetPseudoCustomAttributes ()
297                 {
298                         int count = 0;
299
300                         /* MS.NET doesn't report MethodImplAttribute */
301
302                         MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
303                         if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
304                                 count ++;
305                         if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
306                                 count ++;
307                         
308                         if (count == 0)
309                                 return null;
310                         object[] attrs = new object [count];
311                         count = 0;
312
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;
320                         }
321
322                         return attrs;
323                 }
324
325                 public override string ToString () {
326                         StringBuilder sb = new StringBuilder ();
327                         Type retType = ReturnType;
328                         if (Type.ShouldPrintFullName (retType))
329                                 sb.Append (retType.ToString ());
330                         else
331                                 sb.Append (retType.Name);
332                         sb.Append (" ");
333                         sb.Append (Name);
334                         if (IsGenericMethod) {
335                                 Type[] gen_params = GetGenericArguments ();
336                                 sb.Append ("[");
337                                 for (int j = 0; j < gen_params.Length; j++) {
338                                         if (j > 0)
339                                                 sb.Append (",");
340                                         sb.Append (gen_params [j].Name);
341                                 }
342                                 sb.Append ("]");
343                         }
344                         sb.Append ("(");
345
346                         var p = GetParametersInternal ();
347                         ParameterInfo.FormatParameters (sb, p);
348
349                         if ((CallingConvention & CallingConventions.VarArgs) != 0) {
350                                 if (p.Length > 0)
351                                         sb.Append (", ");
352                                 sb.Append ("...");
353                         }
354                         
355                         sb.Append (")");
356                         return sb.ToString ();
357                 }
358
359         
360                 // ISerializable
361                 public void GetObjectData(SerializationInfo info, StreamingContext context) 
362                 {
363                         Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
364                                 ? GetGenericArguments () : null;
365                         MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
366                 }
367
368                 public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
369                 {
370                         if (methodInstantiation == null)
371                                 throw new ArgumentNullException ("methodInstantiation");
372
373                         if (!IsGenericMethodDefinition)
374                                 throw new InvalidOperationException ("not a generic method definition");
375
376                         /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
377                         if (GetGenericArguments ().Length != methodInstantiation.Length)
378                                 throw new ArgumentException ("Incorrect length");
379
380                         bool hasUserType = false;
381                         foreach (Type type in methodInstantiation) {
382                                 if (type == null)
383                                         throw new ArgumentNullException ();
384                                 if (!(type is MonoType))
385                                         hasUserType = true;
386                         }
387
388                         if (hasUserType)
389 #if FULL_AOT_RUNTIME
390                                 throw new NotSupportedException ("User types are not supported under full aot");
391 #else
392                                 return new MethodOnTypeBuilderInst (this, methodInstantiation);
393 #endif
394
395                         MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
396                         if (ret == null)
397                                 throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
398                         return ret;
399                 }
400
401                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
402                 extern MethodInfo MakeGenericMethod_impl (Type [] types);
403
404                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
405                 public override extern Type [] GetGenericArguments ();
406
407                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
408                 extern MethodInfo GetGenericMethodDefinition_impl ();
409
410                 public override MethodInfo GetGenericMethodDefinition ()
411                 {
412                         MethodInfo res = GetGenericMethodDefinition_impl ();
413                         if (res == null)
414                                 throw new InvalidOperationException ();
415
416                         return res;
417                 }
418
419                 public override extern bool IsGenericMethodDefinition {
420                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
421                         get;
422                 }
423
424                 public override extern bool IsGenericMethod {
425                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
426                         get;
427                 }
428
429                 public override bool ContainsGenericParameters {
430                         get {
431                                 if (IsGenericMethod) {
432                                         foreach (Type arg in GetGenericArguments ())
433                                                 if (arg.ContainsGenericParameters)
434                                                         return true;
435                                 }
436                                 return DeclaringType.ContainsGenericParameters;
437                         }
438                 }
439
440                 public override MethodBody GetMethodBody () {
441                         return GetMethodBody (mhandle);
442                 }
443
444 #if NET_4_0
445                 public override IList<CustomAttributeData> GetCustomAttributesData () {
446                         return CustomAttributeData.GetCustomAttributes (this);
447                 }
448 #endif
449         }
450         
451         [Serializable()]
452         [StructLayout (LayoutKind.Sequential)]
453         internal class MonoCMethod : ConstructorInfo, ISerializable
454         {
455 #pragma warning disable 649             
456                 internal IntPtr mhandle;
457                 string name;
458                 Type reftype;
459 #pragma warning restore 649             
460                 
461                 public override MethodImplAttributes GetMethodImplementationFlags ()
462                 {
463                         return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
464                 }
465
466                 public override ParameterInfo[] GetParameters ()
467                 {
468                         return MonoMethodInfo.GetParametersInfo (mhandle, this);
469                 }
470
471                 internal override ParameterInfo[] GetParametersInternal ()
472                 {
473                         return MonoMethodInfo.GetParametersInfo (mhandle, this);
474                 }               
475
476                 internal override int GetParametersCount ()
477                 {
478                         var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
479                         return pi == null ? 0 : pi.Length;
480                 }
481
482                 /*
483                  * InternalInvoke() receives the parameters correctly converted by the binder
484                  * to match the types of the method signature.
485                  */
486                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
487                 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
488
489                 [DebuggerHidden]
490                 [DebuggerStepThrough]
491                 public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) 
492                 {
493                         if (obj == null) {
494                                 if (!IsStatic)
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");                           
498                         }
499
500                         return DoInvoke (obj, invokeAttr, binder, parameters, culture);
501                 }
502
503                 object DoInvoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) 
504                 {
505                         if (binder == null)
506                                 binder = Binder.DefaultBinder;
507
508                         ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
509
510                         binder.ConvertValues (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0);
511
512 #if !NET_2_1
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);
518                         }
519 #endif
520
521                         if (obj == null && DeclaringType.ContainsGenericParameters)
522                                 throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
523
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));
526                         }
527
528                         return InternalInvoke (obj, parameters);
529                 }
530
531                 public object InternalInvoke (object obj, object[] parameters)
532                 {
533                         Exception exc;
534                         object o = null;
535
536                         try {
537                                 o = InternalInvoke (obj, parameters, out exc);
538 #if NET_2_1
539                         } catch (MethodAccessException) {
540                                 throw;
541 #endif
542                         } catch (Exception e) {
543                                 throw new TargetInvocationException (e);
544                         }
545
546                         if (exc != null)
547                                 throw exc;
548
549                         return obj == null ? o : null;
550                 }
551
552                 [DebuggerHidden]
553                 [DebuggerStepThrough]
554                 public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
555                 {
556                         return DoInvoke (null, invokeAttr, binder, parameters, culture);
557                 }
558
559                 public override RuntimeMethodHandle MethodHandle { 
560                         get {
561                                 return new RuntimeMethodHandle (mhandle);
562                         } 
563                 }
564                 
565                 public override MethodAttributes Attributes { 
566                         get {
567                                 return MonoMethodInfo.GetAttributes (mhandle);
568                         } 
569                 }
570
571                 public override CallingConventions CallingConvention { 
572                         get {
573                                 return MonoMethodInfo.GetCallingConvention (mhandle);
574                         }
575                 }
576                 
577                 public override Type ReflectedType {
578                         get {
579                                 return reftype;
580                         }
581                 }
582                 public override Type DeclaringType {
583                         get {
584                                 return MonoMethodInfo.GetDeclaringType (mhandle);
585                         }
586                 }
587                 public override string Name {
588                         get {
589                                 if (name != null)
590                                         return name;
591                                 return MonoMethod.get_name (this);
592                         }
593                 }
594
595                 public override bool IsDefined (Type attributeType, bool inherit) {
596                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
597                 }
598
599                 public override object[] GetCustomAttributes( bool inherit) {
600                         return MonoCustomAttrs.GetCustomAttributes (this, inherit);
601                 }
602
603                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
604                         return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
605                 }
606
607                 public override MethodBody GetMethodBody () {
608                         return GetMethodBody (mhandle);
609                 }
610
611                 public override string ToString () {
612                         StringBuilder sb = new StringBuilder ();
613                         sb.Append ("Void ");
614                         sb.Append (Name);
615                         sb.Append ("(");
616                         ParameterInfo[] p = GetParameters ();
617                         for (int i = 0; i < p.Length; ++i) {
618                                 if (i > 0)
619                                         sb.Append (", ");
620                                 sb.Append (p[i].ParameterType.Name);
621                         }
622                         if (CallingConvention == CallingConventions.Any)
623                                 sb.Append (", ...");
624                         sb.Append (")");
625                         return sb.ToString ();
626                 }
627
628                 // ISerializable
629                 public void GetObjectData(SerializationInfo info, StreamingContext context) 
630                 {
631                         MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
632                 }
633
634 #if NET_4_0
635                 public override IList<CustomAttributeData> GetCustomAttributesData () {
636                         return CustomAttributeData.GetCustomAttributes (this);
637                 }
638 #endif
639         }
640 }