Merge branch 'master' of github.com:tgiphil/mono
[mono.git] / mcs / class / corlib / System / Delegate.cs
1 //
2 // System.Delegate.cs
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Daniel Stodden (stodden@in.tum.de)
7 //   Dietmar Maurer (dietmar@ximian.com)
8 //
9 // (C) Ximian, Inc.  http://www.ximian.com
10 //
11
12 //
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using System.Reflection;
36 using System.Runtime.Remoting;
37 using System.Runtime.Serialization;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40
41 namespace System
42 {
43         /* Contains the rarely used fields of Delegate */
44         class DelegateData {
45                 public Type target_type;
46                 public string method_name;
47         }
48
49         [ClassInterface (ClassInterfaceType.AutoDual)]
50         [System.Runtime.InteropServices.ComVisible (true)]
51         [Serializable]
52         public abstract class Delegate : ICloneable, ISerializable
53         {
54                 #region Sync with object-internals.h
55 #pragma warning disable 169, 414, 649
56                 private IntPtr method_ptr;
57                 private IntPtr invoke_impl;
58                 private object m_target;
59                 private IntPtr method;
60                 private IntPtr delegate_trampoline;
61                 private IntPtr method_code;
62                 private MethodInfo method_info;
63
64                 // Keep a ref of the MethodInfo passed to CreateDelegate.
65                 // Used to keep DynamicMethods alive.
66                 private MethodInfo original_method_info;
67
68                 private DelegateData data;
69 #pragma warning restore 169, 414, 649
70                 #endregion
71
72                 protected Delegate (object target, string method)
73                 {
74                         if (target == null)
75                                 throw new ArgumentNullException ("target");
76
77                         if (method == null)
78                                 throw new ArgumentNullException ("method");
79
80                         this.m_target = target;
81                         this.data = new DelegateData ();
82                         this.data.method_name = method;
83                 }
84
85                 protected Delegate (Type target, string method)
86                 {
87                         if (target == null)
88                                 throw new ArgumentNullException ("target");
89
90                         if (method == null)
91                                 throw new ArgumentNullException ("method");
92
93                         this.data = new DelegateData ();
94                         this.data.method_name = method;
95                         this.data.target_type = target;
96                 }
97
98                 public MethodInfo Method {
99                         get {
100                                 if (method_info != null) {
101                                         return method_info;
102                                 } else {
103                                         if (method != IntPtr.Zero) {
104                                                 method_info = (MethodInfo)MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (method));
105                                         }
106                                         return method_info;
107                                 }
108                         }
109                 }
110
111                 public object Target {
112                         get {
113                                 return m_target;
114                         }
115                 }
116
117                 //
118                 // Methods
119                 //
120
121                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
122                 internal static extern Delegate CreateDelegate_internal (Type type, object target, MethodInfo info, bool throwOnBindFailure);
123
124                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
125                 internal extern void SetMulticastInvoke ();
126
127                 private static bool arg_type_match (Type delArgType, Type argType) {
128                         bool match = delArgType == argType;
129
130                         // Delegate contravariance
131                         if (!match) {
132                                 if (!argType.IsValueType && argType.IsAssignableFrom (delArgType))
133                                         match = true;
134                         }
135
136                         return match;
137                 }
138
139                 private static bool return_type_match (Type delReturnType, Type returnType) {
140                         bool returnMatch = returnType == delReturnType;
141
142                         if (!returnMatch) {
143                                 // Delegate covariance
144                                 if (!returnType.IsValueType && delReturnType.IsAssignableFrom (returnType))
145                                         returnMatch = true;
146                         }
147
148                         return returnMatch;
149                 }
150
151                 public static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure)
152                 {
153                         // The name of the parameter changed in 2.0
154                         object target = firstArgument;
155
156                         if (type == null)
157                                 throw new ArgumentNullException ("type");
158
159                         if (method == null)
160                                 throw new ArgumentNullException ("method");
161
162                         if (!type.IsSubclassOf (typeof (MulticastDelegate)))
163                                 throw new ArgumentException ("type is not a subclass of Multicastdelegate");
164
165                         MethodInfo invoke = type.GetMethod ("Invoke");
166
167                         if (!return_type_match (invoke.ReturnType, method.ReturnType))
168                                 if (throwOnBindFailure)
169                                         throw new ArgumentException ("method return type is incompatible");
170                                 else
171                                         return null;
172
173                         ParameterInfo[] delargs = invoke.GetParameters ();
174                         ParameterInfo[] args = method.GetParameters ();
175
176                         bool argLengthMatch;
177
178                         if (target != null) {
179                                 // delegate closed over target
180                                 if (!method.IsStatic)
181                                         // target is passed as this
182                                         argLengthMatch = (args.Length == delargs.Length);
183                                 else
184                                         // target is passed as the first argument to the static method
185                                         argLengthMatch = (args.Length == delargs.Length + 1);
186                         } else {
187                                 if (!method.IsStatic)
188                                         //
189                                         // Net 2.0 feature. The first argument of the delegate is passed
190                                         // as the 'this' argument to the method.
191                                         //
192                                         argLengthMatch = (args.Length + 1 == delargs.Length);
193                                 else {
194                                         argLengthMatch = (args.Length == delargs.Length);
195
196                                         if (!argLengthMatch)
197                                                 // closed over a null reference
198                                                 argLengthMatch = args.Length == delargs.Length + 1;
199                                 }
200                         }
201                         if (!argLengthMatch)
202                                 if (throwOnBindFailure)
203                                         throw new ArgumentException ("method argument length mismatch");
204                                 else
205                                         return null;
206
207                         bool argsMatch;
208                         if (target != null) {
209                                 if (!method.IsStatic) {
210                                         argsMatch = arg_type_match (target.GetType (), method.DeclaringType);
211                                         for (int i = 0; i < args.Length; i++)
212                                                 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
213                                 } else {
214                                         argsMatch = arg_type_match (target.GetType (), args [0].ParameterType);
215                                         for (int i = 1; i < args.Length; i++)
216                                                 argsMatch &= arg_type_match (delargs [i - 1].ParameterType, args [i].ParameterType);                                    
217                                 }
218                         } else {
219                                 if (!method.IsStatic) {
220                                         // The first argument should match this
221                                         argsMatch = arg_type_match (delargs [0].ParameterType, method.DeclaringType);
222                                         for (int i = 0; i < args.Length; i++)
223                                                 argsMatch &= arg_type_match (delargs [i + 1].ParameterType, args [i].ParameterType);
224                                 } else {
225                                         if (delargs.Length + 1 == args.Length) {
226                                                 // closed over a null reference
227                                                 argsMatch = !args [0].ParameterType.IsValueType;
228                                                 for (int i = 0; i < delargs.Length; i++)
229                                                         argsMatch &= arg_type_match (delargs [i].ParameterType, args [i + 1].ParameterType);
230                                         } else {
231                                                 argsMatch = true;
232                                                 for (int i = 0; i < args.Length; i++)
233                                                         argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
234                                         }
235                                 }
236                         }
237
238                         if (!argsMatch)
239                                 if (throwOnBindFailure)
240                                         throw new ArgumentException ("method arguments are incompatible");
241                                 else
242                                         return null;
243
244                         Delegate d = CreateDelegate_internal (type, target, method, throwOnBindFailure);
245                         if (d != null)
246                                 d.original_method_info = method;
247                         return d;
248                 }
249
250                 public static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method) {
251                         return CreateDelegate (type, firstArgument, method, true);
252                 }
253
254                 public static Delegate CreateDelegate (Type type, MethodInfo method, bool throwOnBindFailure)
255                 {
256                         return CreateDelegate (type, null, method, throwOnBindFailure);
257                 }
258
259                 public static Delegate CreateDelegate (Type type, MethodInfo method) {
260                         return CreateDelegate (type, method, true);
261                 }
262
263                 public static Delegate CreateDelegate (Type type, object target, string method)
264                 {
265                         return CreateDelegate(type, target, method, false);
266                 }
267
268                 static MethodInfo GetCandidateMethod (Type type, Type target, string method, BindingFlags bflags, bool ignoreCase, bool throwOnBindFailure)
269                 {
270                         if (type == null)
271                                 throw new ArgumentNullException ("type");
272
273                         if (method == null)
274                                 throw new ArgumentNullException ("method");
275
276                         if (!type.IsSubclassOf (typeof (MulticastDelegate)))
277                                 throw new ArgumentException ("type is not subclass of MulticastDelegate.");
278
279                         MethodInfo invoke = type.GetMethod ("Invoke");
280                         ParameterInfo [] delargs = invoke.GetParameters ();
281                         Type[] delargtypes = new Type [delargs.Length];
282
283                         for (int i=0; i<delargs.Length; i++)
284                                 delargtypes [i] = delargs [i].ParameterType;
285
286                         /* 
287                          * FIXME: we should check the caller has reflection permission
288                          * or if it lives in the same assembly...
289                          */
290
291                         /*
292                          * since we need to walk the inheritance chain anyway to
293                          * find private methods, adjust the bindingflags to ignore
294                          * inherited methods
295                          */
296                         BindingFlags flags = BindingFlags.ExactBinding |
297                                 BindingFlags.Public | BindingFlags.NonPublic |
298                                 BindingFlags.DeclaredOnly | bflags;
299
300                         if (ignoreCase)
301                                 flags |= BindingFlags.IgnoreCase;
302
303                         MethodInfo info = null;
304
305                         for (Type targetType = target; targetType != null; targetType = targetType.BaseType) {
306                                 MethodInfo mi = targetType.GetMethod (method, flags,
307                                         null, delargtypes, new ParameterModifier [0]);
308                                 if (mi != null && return_type_match (invoke.ReturnType, mi.ReturnType)) {
309                                         info = mi;
310                                         break;
311                                 }
312                         }
313
314                         if (info == null) {
315                                 if (throwOnBindFailure)
316                                         throw new ArgumentException ("Couldn't bind to method '" + method + "'.");
317                                 else
318                                         return null;
319                         }
320
321                         return info;
322                 }
323
324                 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure)
325                 {
326                         if (target == null)
327                                 throw new ArgumentNullException ("target");
328
329                         MethodInfo info = GetCandidateMethod (type, target, method,
330                                 BindingFlags.Static, ignoreCase, throwOnBindFailure);
331                         if (info == null)
332                                 return null;
333
334                         return CreateDelegate_internal (type, null, info, throwOnBindFailure);
335                 }
336
337                 public static Delegate CreateDelegate (Type type, Type target, string method) {
338                         return CreateDelegate (type, target, method, false, true);
339                 }
340
341                 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase) {
342                         return CreateDelegate (type, target, method, ignoreCase, true);
343                 }
344
345                 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure)
346                 {
347                         if (target == null)
348                                 throw new ArgumentNullException ("target");
349
350                         MethodInfo info = GetCandidateMethod (type, target.GetType (), method,
351                                 BindingFlags.Instance, ignoreCase, throwOnBindFailure);
352                         if (info == null)
353                                 return null;
354
355                         return CreateDelegate_internal (type, target, info, throwOnBindFailure);
356                 }
357
358                 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase) {
359                         return CreateDelegate (type, target, method, ignoreCase, true);
360                 }
361
362                 public object DynamicInvoke (params object[] args)
363                 {
364                         return DynamicInvokeImpl (args);
365                 }
366
367                 protected virtual object DynamicInvokeImpl (object[] args)
368                 {
369                         if (Method == null) {
370                                 Type[] mtypes = new Type [args.Length];
371                                 for (int i = 0; i < args.Length; ++i) {
372                                         mtypes [i] = args [i].GetType ();
373                                 }
374                                 method_info = m_target.GetType ().GetMethod (data.method_name, mtypes);
375                         }
376
377                         if ((m_target != null) && Method.IsStatic) {
378                                 // The delegate is bound to m_target
379                                 if (args != null) {
380                                         object[] newArgs = new object [args.Length + 1];
381                                         args.CopyTo (newArgs, 1);
382                                         newArgs [0] = m_target;
383                                         args = newArgs;
384                                 } else {
385                                         args = new object [] { m_target };
386                                 }
387                                 return Method.Invoke (null, args);
388                         }
389
390                         return Method.Invoke (m_target, args);
391                 }
392
393                 public virtual object Clone ()
394                 {
395                         return MemberwiseClone ();
396                 }
397
398                 public override bool Equals (object obj)
399                 {
400                         Delegate d = obj as Delegate;
401                         
402                         if (d == null)
403                                 return false;
404                         
405                         // Do not compare method_ptr, since it can point to a trampoline
406                         if (d.m_target == m_target && d.method == method) {
407                                 if (d.data != null || data != null) {
408                                         /* Uncommon case */
409                                         if (d.data != null && data != null)
410                                                 return (d.data.target_type == data.target_type && d.data.method_name == data.method_name);
411                                         else
412                                                 return false;
413                                 }
414                                 return true;
415                         }
416
417                         return false;
418                 }
419
420                 public override int GetHashCode ()
421                 {
422                         return method.GetHashCode () ^ (m_target != null ? m_target.GetHashCode () : 0);
423                 }
424
425                 protected virtual MethodInfo GetMethodImpl ()
426                 {
427                         return Method;
428                 }
429
430                 // This is from ISerializable
431                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
432                 {
433                         DelegateSerializationHolder.GetDelegateData (this, info, context);
434                 }
435
436                 public virtual Delegate[] GetInvocationList()
437                 {
438                         return new Delegate[] { this };
439                 }
440
441                 /// <symmary>
442                 ///   Returns a new MulticastDelegate holding the
443                 ///   concatenated invocation lists of MulticastDelegates a and b
444                 /// </symmary>
445                 public static Delegate Combine (Delegate a, Delegate b)
446                 {
447                         if (a == null) {
448                                 if (b == null)
449                                         return null;
450                                 return b;
451                         } else 
452                                 if (b == null)
453                                         return a;
454
455                         if (a.GetType () != b.GetType ())
456                                 throw new ArgumentException (Locale.GetText ("Incompatible Delegate Types."));
457                         
458                         return a.CombineImpl (b);
459                 }
460
461                 /// <symmary>
462                 ///   Returns a new MulticastDelegate holding the
463                 ///   concatenated invocation lists of an Array of MulticastDelegates
464                 /// </symmary>
465                 [System.Runtime.InteropServices.ComVisible (true)]
466                 public static Delegate Combine (params Delegate[] delegates)
467                 {
468                         if (delegates == null)
469                                 return null;
470
471                         Delegate retval = null;
472
473                         foreach (Delegate next in delegates)
474                                 retval = Combine (retval, next);
475
476                         return retval;
477                 }
478
479                 protected virtual Delegate CombineImpl (Delegate d)
480                 {
481                         throw new MulticastNotSupportedException (String.Empty);
482                 }
483
484                 public static Delegate Remove (Delegate source, Delegate value) 
485                 {
486                         if (source == null)
487                                 return null;
488
489                         return source.RemoveImpl (value);
490                 }
491
492                 protected virtual Delegate RemoveImpl (Delegate d)
493                 {
494                         if (this.Equals (d))
495                                 return null;
496
497                         return this;
498                 }
499
500                 public static Delegate RemoveAll (Delegate source, Delegate value)
501                 {
502                         Delegate tmp = source;
503                         while ((source = Delegate.Remove (source, value)) != tmp)
504                                 tmp = source;
505
506                         return tmp;
507                 }
508
509                 public static bool operator == (Delegate d1, Delegate d2)
510                 {
511                         if ((object)d1 == null) {
512                                 if ((object)d2 == null)
513                                         return true;
514                                 return false;
515                         } else if ((object) d2 == null)
516                                 return false;
517                         
518                         return d1.Equals (d2);
519                 }
520
521                 public static bool operator != (Delegate d1, Delegate d2)
522                 {
523                         return !(d1 == d2);
524                 }
525
526                 internal bool IsTransparentProxy ()
527                 {
528                         return RemotingServices.IsTransparentProxy (m_target);
529                 }
530         }
531 }