Merge pull request #487 from mayerwin/patch-1
[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 new ParameterInfo (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                         ParameterInfo[] src = MonoMethodInfo.GetParametersInfo (mhandle, this);
174                         ParameterInfo[] res = new ParameterInfo [src.Length];
175                         src.CopyTo (res, 0);
176                         return res;
177                 }
178                 
179                 internal override int GetParameterCount ()
180                 {
181                         var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
182                         return pi == null ? 0 : pi.Length;
183                 }
184
185                 /*
186                  * InternalInvoke() receives the parameters correctly converted by the 
187                  * binder to match the types of the method signature.
188                  */
189                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
190                 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
191
192                 [DebuggerHidden]
193                 [DebuggerStepThrough]
194                 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
195                 {
196                         if (binder == null)
197                                 binder = Binder.DefaultBinder;
198
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");
203
204 #if !NET_2_1
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);
210                         }
211 #endif
212
213                         if (ContainsGenericParameters)
214                                 throw new InvalidOperationException ("Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.");
215
216                         Exception exc;
217                         object o = null;
218
219                         try {
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) {
225                                 throw;
226 #if NET_2_1
227                         } catch (MethodAccessException) {
228                                 throw;
229 #endif
230                         } catch (Exception e) {
231                                 throw new TargetInvocationException (e);
232                         }
233
234                         if (exc != null)
235                                 throw exc;
236                         return o;
237                 }
238
239                 public override RuntimeMethodHandle MethodHandle { 
240                         get {
241                                 return new RuntimeMethodHandle (mhandle);
242                         } 
243                 }
244                 
245                 public override MethodAttributes Attributes { 
246                         get {
247                                 return MonoMethodInfo.GetAttributes (mhandle);
248                         } 
249                 }
250
251                 public override CallingConventions CallingConvention { 
252                         get {
253                                 return MonoMethodInfo.GetCallingConvention (mhandle);
254                         }
255                 }
256                 
257                 public override Type ReflectedType {
258                         get {
259                                 return reftype;
260                         }
261                 }
262                 public override Type DeclaringType {
263                         get {
264                                 return MonoMethodInfo.GetDeclaringType (mhandle);
265                         }
266                 }
267                 public override string Name {
268                         get {
269                                 if (name != null)
270                                         return name;
271                                 return get_name (this);
272                         }
273                 }
274                 
275                 public override bool IsDefined (Type attributeType, bool inherit) {
276                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
277                 }
278
279                 public override object[] GetCustomAttributes( bool inherit) {
280                         return MonoCustomAttrs.GetCustomAttributes (this, inherit);
281                 }
282                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
283                         return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
284                 }
285
286                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
287                 internal static extern DllImportAttribute GetDllImportAttribute (IntPtr mhandle);
288
289                 internal object[] GetPseudoCustomAttributes ()
290                 {
291                         int count = 0;
292
293                         /* MS.NET doesn't report MethodImplAttribute */
294
295                         MonoMethodInfo info = MonoMethodInfo.GetMethodInfo (mhandle);
296                         if ((info.iattrs & MethodImplAttributes.PreserveSig) != 0)
297                                 count ++;
298                         if ((info.attrs & MethodAttributes.PinvokeImpl) != 0)
299                                 count ++;
300                         
301                         if (count == 0)
302                                 return null;
303                         object[] attrs = new object [count];
304                         count = 0;
305
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;
313                         }
314
315                         return attrs;
316                 }
317
318                 static bool ShouldPrintFullName (Type type) {
319                         return type.IsClass && (!type.IsPointer ||
320                                 (!type.GetElementType ().IsPrimitive && !type.GetElementType ().IsNested));
321                 }
322
323                 public override string ToString () {
324                         StringBuilder sb = new StringBuilder ();
325                         Type retType = ReturnType;
326                         if (ShouldPrintFullName (retType))
327                                 sb.Append (retType.ToString ());
328                         else
329                                 sb.Append (retType.Name);
330                         sb.Append (" ");
331                         sb.Append (Name);
332                         if (IsGenericMethod) {
333                                 Type[] gen_params = GetGenericArguments ();
334                                 sb.Append ("[");
335                                 for (int j = 0; j < gen_params.Length; j++) {
336                                         if (j > 0)
337                                                 sb.Append (",");
338                                         sb.Append (gen_params [j].Name);
339                                 }
340                                 sb.Append ("]");
341                         }
342                         sb.Append ("(");
343                         ParameterInfo[] p = GetParameters ();
344                         for (int i = 0; i < p.Length; ++i) {
345                                 if (i > 0)
346                                         sb.Append (", ");
347                                 Type pt = p[i].ParameterType;
348                                 bool byref = pt.IsByRef;
349                                 if (byref)
350                                         pt = pt.GetElementType ();
351                                 if (ShouldPrintFullName (pt))
352                                         sb.Append (pt.ToString ());
353                                 else
354                                         sb.Append (pt.Name);
355                                 if (byref)
356                                         sb.Append (" ByRef");
357                         }
358                         if ((CallingConvention & CallingConventions.VarArgs) != 0) {
359                                 if (p.Length > 0)
360                                         sb.Append (", ");
361                                 sb.Append ("...");
362                         }
363                         
364                         sb.Append (")");
365                         return sb.ToString ();
366                 }
367
368         
369                 // ISerializable
370                 public void GetObjectData(SerializationInfo info, StreamingContext context) 
371                 {
372                         Type[] genericArguments = IsGenericMethod && !IsGenericMethodDefinition
373                                 ? GetGenericArguments () : null;
374                         MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Method, genericArguments);
375                 }
376
377                 public override MethodInfo MakeGenericMethod (Type [] methodInstantiation)
378                 {
379                         if (methodInstantiation == null)
380                                 throw new ArgumentNullException ("methodInstantiation");
381
382                         if (!IsGenericMethodDefinition)
383                                 throw new InvalidOperationException ("not a generic method definition");
384
385                         /*FIXME add GetGenericArgumentsLength() internal vcall to speed this up*/
386                         if (GetGenericArguments ().Length != methodInstantiation.Length)
387                                 throw new ArgumentException ("Incorrect length");
388
389                         bool hasUserType = false;
390                         foreach (Type type in methodInstantiation) {
391                                 if (type == null)
392                                         throw new ArgumentNullException ();
393                                 if (!(type is MonoType))
394                                         hasUserType = true;
395                         }
396
397 #if !FULL_AOT_RUNTIME
398                         if (hasUserType)
399                                 return new MethodOnTypeBuilderInst (this, methodInstantiation);
400 #endif
401
402                         MethodInfo ret = MakeGenericMethod_impl (methodInstantiation);
403                         if (ret == null)
404                                 throw new ArgumentException (String.Format ("The method has {0} generic parameter(s) but {1} generic argument(s) were provided.", GetGenericArguments ().Length, methodInstantiation.Length));
405                         return ret;
406                 }
407
408                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
409                 extern MethodInfo MakeGenericMethod_impl (Type [] types);
410
411                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
412                 public override extern Type [] GetGenericArguments ();
413
414                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
415                 extern MethodInfo GetGenericMethodDefinition_impl ();
416
417                 public override MethodInfo GetGenericMethodDefinition ()
418                 {
419                         MethodInfo res = GetGenericMethodDefinition_impl ();
420                         if (res == null)
421                                 throw new InvalidOperationException ();
422
423                         return res;
424                 }
425
426                 public override extern bool IsGenericMethodDefinition {
427                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
428                         get;
429                 }
430
431                 public override extern bool IsGenericMethod {
432                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
433                         get;
434                 }
435
436                 public override bool ContainsGenericParameters {
437                         get {
438                                 if (IsGenericMethod) {
439                                         foreach (Type arg in GetGenericArguments ())
440                                                 if (arg.ContainsGenericParameters)
441                                                         return true;
442                                 }
443                                 return DeclaringType.ContainsGenericParameters;
444                         }
445                 }
446
447                 public override MethodBody GetMethodBody () {
448                         return GetMethodBody (mhandle);
449                 }
450
451 #if NET_4_0
452                 public override IList<CustomAttributeData> GetCustomAttributesData () {
453                         return CustomAttributeData.GetCustomAttributes (this);
454                 }
455 #endif
456         }
457         
458         [StructLayout (LayoutKind.Sequential)]
459         internal class MonoCMethod : ConstructorInfo, ISerializable
460         {
461 #pragma warning disable 649             
462                 internal IntPtr mhandle;
463                 string name;
464                 Type reftype;
465 #pragma warning restore 649             
466                 
467                 public override MethodImplAttributes GetMethodImplementationFlags ()
468                 {
469                         return MonoMethodInfo.GetMethodImplementationFlags (mhandle);
470                 }
471
472                 public override ParameterInfo[] GetParameters ()
473                 {
474                         return MonoMethodInfo.GetParametersInfo (mhandle, this);
475                 }
476
477                 internal override int GetParameterCount ()
478                 {
479                         var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
480                         return pi == null ? 0 : pi.Length;
481                 }
482
483                 /*
484                  * InternalInvoke() receives the parameters corretcly converted by the binder
485                  * to match the types of the method signature.
486                  */
487                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
488                 internal extern Object InternalInvoke (Object obj, Object[] parameters, out Exception exc);
489
490                 [DebuggerHidden]
491                 [DebuggerStepThrough]
492                 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
493                 {
494                         if (binder == null)
495                                 binder = Binder.DefaultBinder;
496
497                         ParameterInfo[] pinfo = MonoMethodInfo.GetParametersInfo (mhandle, this);
498
499                         if (!binder.ConvertArgs (parameters, pinfo, culture, (invokeAttr & BindingFlags.ExactBinding) != 0))
500                                 throw new ArgumentException ("failed to convert parameters");
501
502 #if !NET_2_1
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);
508                         }
509 #endif
510
511                         if (obj == null && DeclaringType.ContainsGenericParameters)
512                                 throw new MemberAccessException ("Cannot create an instance of " + DeclaringType + " because Type.ContainsGenericParameters is true.");
513
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));
516                         }
517
518                         Exception exc = null;
519                         object o = null;
520
521                         try {
522                                 o = InternalInvoke (obj, parameters, out exc);
523 #if NET_2_1
524                         } catch (MethodAccessException) {
525                                 throw;
526 #endif
527                         } catch (Exception e) {
528                                 throw new TargetInvocationException (e);
529                         }
530
531                         if (exc != null)
532                                 throw exc;
533                         return (obj == null) ? o : null;
534                 }
535
536                 [DebuggerHidden]
537                 [DebuggerStepThrough]
538                 public override Object Invoke (BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
539                 {
540                         return Invoke (null, invokeAttr, binder, parameters, culture);
541                 }
542
543                 public override RuntimeMethodHandle MethodHandle { 
544                         get {
545                                 return new RuntimeMethodHandle (mhandle);
546                         } 
547                 }
548                 
549                 public override MethodAttributes Attributes { 
550                         get {
551                                 return MonoMethodInfo.GetAttributes (mhandle);
552                         } 
553                 }
554
555                 public override CallingConventions CallingConvention { 
556                         get {
557                                 return MonoMethodInfo.GetCallingConvention (mhandle);
558                         }
559                 }
560                 
561                 public override Type ReflectedType {
562                         get {
563                                 return reftype;
564                         }
565                 }
566                 public override Type DeclaringType {
567                         get {
568                                 return MonoMethodInfo.GetDeclaringType (mhandle);
569                         }
570                 }
571                 public override string Name {
572                         get {
573                                 if (name != null)
574                                         return name;
575                                 return MonoMethod.get_name (this);
576                         }
577                 }
578
579                 public override bool IsDefined (Type attributeType, bool inherit) {
580                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
581                 }
582
583                 public override object[] GetCustomAttributes( bool inherit) {
584                         return MonoCustomAttrs.GetCustomAttributes (this, inherit);
585                 }
586
587                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
588                         return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
589                 }
590
591                 public override MethodBody GetMethodBody () {
592                         return GetMethodBody (mhandle);
593                 }
594
595                 public override string ToString () {
596                         StringBuilder sb = new StringBuilder ();
597                         sb.Append ("Void ");
598                         sb.Append (Name);
599                         sb.Append ("(");
600                         ParameterInfo[] p = GetParameters ();
601                         for (int i = 0; i < p.Length; ++i) {
602                                 if (i > 0)
603                                         sb.Append (", ");
604                                 sb.Append (p[i].ParameterType.Name);
605                         }
606                         if (CallingConvention == CallingConventions.Any)
607                                 sb.Append (", ...");
608                         sb.Append (")");
609                         return sb.ToString ();
610                 }
611
612                 // ISerializable
613                 public void GetObjectData(SerializationInfo info, StreamingContext context) 
614                 {
615                         MemberInfoSerializationHolder.Serialize ( info, Name, ReflectedType, ToString(), MemberTypes.Constructor);
616                 }
617
618 #if NET_4_0
619                 public override IList<CustomAttributeData> GetCustomAttributesData () {
620                         return CustomAttributeData.GetCustomAttributes (this);
621                 }
622 #endif
623         }
624 }