5 // Miguel de Icaza (miguel@ximian.com)
6 // Daniel Stodden (stodden@in.tum.de)
7 // Dietmar Maurer (dietmar@ximian.com)
8 // Marek Safar (marek.safar@gmail.com)
10 // (C) Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 // Copyright 2014 Xamarin, Inc (http://www.xamarin.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Reflection;
35 using System.Runtime.Remoting;
36 using System.Runtime.Serialization;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
42 /* Contains the rarely used fields of Delegate */
43 sealed class DelegateData
45 public Type target_type;
46 public string method_name;
47 public bool curried_first_arg;
50 [ClassInterface (ClassInterfaceType.AutoDual)]
51 [System.Runtime.InteropServices.ComVisible (true)]
53 [StructLayout (LayoutKind.Sequential)]
54 public abstract class Delegate : ICloneable, ISerializable
56 #region Sync with object-internals.h
57 #pragma warning disable 169, 414, 649
58 private IntPtr method_ptr;
59 private IntPtr invoke_impl;
60 private object m_target;
61 private IntPtr method;
62 private IntPtr delegate_trampoline;
63 private IntPtr method_code;
64 private MethodInfo method_info;
66 // Keep a ref of the MethodInfo passed to CreateDelegate.
67 // Used to keep DynamicMethods alive.
68 private MethodInfo original_method_info;
70 private DelegateData data;
71 #pragma warning restore 169, 414, 649
74 protected Delegate (object target, string method)
77 throw new ArgumentNullException ("target");
80 throw new ArgumentNullException ("method");
82 this.m_target = target;
83 this.data = new DelegateData ();
84 this.data.method_name = method;
87 protected Delegate (Type target, string method)
90 throw new ArgumentNullException ("target");
93 throw new ArgumentNullException ("method");
95 this.data = new DelegateData ();
96 this.data.method_name = method;
97 this.data.target_type = target;
100 public MethodInfo Method {
102 if (method_info != null) {
105 if (method != IntPtr.Zero) {
106 method_info = (MethodInfo)MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (method));
113 public object Target {
123 [MethodImplAttribute (MethodImplOptions.InternalCall)]
124 internal static extern Delegate CreateDelegate_internal (Type type, object target, MethodInfo info, bool throwOnBindFailure);
126 [MethodImplAttribute (MethodImplOptions.InternalCall)]
127 internal extern void SetMulticastInvoke ();
129 private static bool arg_type_match (Type delArgType, Type argType) {
130 bool match = delArgType == argType;
132 // Delegate contravariance
134 if (!argType.IsValueType && argType.IsAssignableFrom (delArgType))
139 if (delArgType.IsEnum && Enum.GetUnderlyingType (delArgType) == argType)
146 private static bool arg_type_match_this (Type delArgType, Type argType, bool boxedThis) {
148 if (argType.IsValueType)
149 match = delArgType.IsByRef && delArgType.GetElementType () == argType ||
150 (boxedThis && delArgType == argType);
152 match = delArgType == argType || argType.IsAssignableFrom (delArgType);
156 private static bool return_type_match (Type delReturnType, Type returnType) {
157 bool returnMatch = returnType == delReturnType;
160 // Delegate covariance
161 if (!returnType.IsValueType && delReturnType.IsAssignableFrom (returnType))
168 public static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure)
170 return CreateDelegate (type, firstArgument, method, throwOnBindFailure, true);
173 static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure, bool allowClosed)
175 // The name of the parameter changed in 2.0
176 object target = firstArgument;
179 throw new ArgumentNullException ("type");
182 throw new ArgumentNullException ("method");
184 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
185 throw new ArgumentException ("type is not a subclass of Multicastdelegate");
187 MethodInfo invoke = type.GetMethod ("Invoke");
189 if (!return_type_match (invoke.ReturnType, method.ReturnType))
190 if (throwOnBindFailure)
191 throw new ArgumentException ("method return type is incompatible");
195 ParameterInfo[] delargs = invoke.GetParametersInternal ();
196 ParameterInfo[] args = method.GetParametersInternal ();
200 if (target != null) {
201 // delegate closed over target
202 if (!method.IsStatic)
203 // target is passed as this
204 argLengthMatch = (args.Length == delargs.Length);
206 // target is passed as the first argument to the static method
207 argLengthMatch = (args.Length == delargs.Length + 1);
209 if (!method.IsStatic) {
211 // Net 2.0 feature. The first argument of the delegate is passed
212 // as the 'this' argument to the method.
214 argLengthMatch = (args.Length + 1 == delargs.Length);
217 // closed over a null reference
218 argLengthMatch = (args.Length == delargs.Length);
220 argLengthMatch = (args.Length == delargs.Length);
223 // closed over a null reference
224 argLengthMatch = args.Length == delargs.Length + 1;
228 if (throwOnBindFailure)
229 throw new ArgumentException ("method argument length mismatch");
234 DelegateData delegate_data = new DelegateData ();
236 if (target != null) {
237 if (!method.IsStatic) {
238 argsMatch = arg_type_match_this (target.GetType (), method.DeclaringType, true);
239 for (int i = 0; i < args.Length; i++)
240 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
242 argsMatch = arg_type_match (target.GetType (), args [0].ParameterType);
243 for (int i = 1; i < args.Length; i++)
244 argsMatch &= arg_type_match (delargs [i - 1].ParameterType, args [i].ParameterType);
246 delegate_data.curried_first_arg = true;
249 if (!method.IsStatic) {
250 if (args.Length + 1 == delargs.Length) {
251 // The first argument should match this
252 argsMatch = arg_type_match_this (delargs [0].ParameterType, method.DeclaringType, false);
253 for (int i = 0; i < args.Length; i++)
254 argsMatch &= arg_type_match (delargs [i + 1].ParameterType, args [i].ParameterType);
256 // closed over a null reference
257 argsMatch = allowClosed;
258 for (int i = 0; i < args.Length; i++)
259 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
262 if (delargs.Length + 1 == args.Length) {
263 // closed over a null reference
264 argsMatch = !(args [0].ParameterType.IsValueType || args [0].ParameterType.IsByRef) && allowClosed;
265 for (int i = 0; i < delargs.Length; i++)
266 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i + 1].ParameterType);
268 delegate_data.curried_first_arg = true;
271 for (int i = 0; i < args.Length; i++)
272 argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
278 if (throwOnBindFailure)
279 throw new ArgumentException ("method arguments are incompatible");
283 Delegate d = CreateDelegate_internal (type, target, method, throwOnBindFailure);
285 d.original_method_info = method;
286 if (delegate_data != null)
287 d.data = delegate_data;
291 public static Delegate CreateDelegate (Type type, object firstArgument, MethodInfo method)
293 return CreateDelegate (type, firstArgument, method, true, true);
296 public static Delegate CreateDelegate (Type type, MethodInfo method, bool throwOnBindFailure)
298 return CreateDelegate (type, null, method, throwOnBindFailure, false);
301 public static Delegate CreateDelegate (Type type, MethodInfo method)
303 return CreateDelegate (type, method, true);
306 public static Delegate CreateDelegate (Type type, object target, string method)
308 return CreateDelegate (type, target, method, false);
311 static MethodInfo GetCandidateMethod (Type type, Type target, string method, BindingFlags bflags, bool ignoreCase, bool throwOnBindFailure)
314 throw new ArgumentNullException ("type");
317 throw new ArgumentNullException ("method");
319 if (!type.IsSubclassOf (typeof (MulticastDelegate)))
320 throw new ArgumentException ("type is not subclass of MulticastDelegate.");
322 MethodInfo invoke = type.GetMethod ("Invoke");
323 ParameterInfo [] delargs = invoke.GetParametersInternal ();
324 Type[] delargtypes = new Type [delargs.Length];
326 for (int i=0; i<delargs.Length; i++)
327 delargtypes [i] = delargs [i].ParameterType;
330 * FIXME: we should check the caller has reflection permission
331 * or if it lives in the same assembly...
335 * since we need to walk the inheritance chain anyway to
336 * find private methods, adjust the bindingflags to ignore
339 BindingFlags flags = BindingFlags.ExactBinding |
340 BindingFlags.Public | BindingFlags.NonPublic |
341 BindingFlags.DeclaredOnly | bflags;
344 flags |= BindingFlags.IgnoreCase;
346 MethodInfo info = null;
348 for (Type targetType = target; targetType != null; targetType = targetType.BaseType) {
349 MethodInfo mi = targetType.GetMethod (method, flags,
350 null, delargtypes, EmptyArray<ParameterModifier>.Value);
351 if (mi != null && return_type_match (invoke.ReturnType, mi.ReturnType)) {
358 if (throwOnBindFailure)
359 throw new ArgumentException ("Couldn't bind to method '" + method + "'.");
367 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure)
370 throw new ArgumentNullException ("target");
372 MethodInfo info = GetCandidateMethod (type, target, method,
373 BindingFlags.Static, ignoreCase, throwOnBindFailure);
377 return CreateDelegate_internal (type, null, info, throwOnBindFailure);
380 public static Delegate CreateDelegate (Type type, Type target, string method) {
381 return CreateDelegate (type, target, method, false, true);
384 public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase) {
385 return CreateDelegate (type, target, method, ignoreCase, true);
388 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure)
391 throw new ArgumentNullException ("target");
393 MethodInfo info = GetCandidateMethod (type, target.GetType (), method,
394 BindingFlags.Instance, ignoreCase, throwOnBindFailure);
398 return CreateDelegate_internal (type, target, info, throwOnBindFailure);
401 public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase) {
402 return CreateDelegate (type, target, method, ignoreCase, true);
405 public object DynamicInvoke (params object[] args)
407 return DynamicInvokeImpl (args);
410 void InitializeDelegateData ()
412 DelegateData delegate_data = new DelegateData ();
413 if (method_info.IsStatic) {
414 if (m_target != null) {
415 delegate_data.curried_first_arg = true;
417 MethodInfo invoke = GetType ().GetMethod ("Invoke");
418 if (invoke.GetParametersCount () + 1 == method_info.GetParametersCount ())
419 delegate_data.curried_first_arg = true;
422 this.data = delegate_data;
425 protected virtual object DynamicInvokeImpl (object[] args)
427 if (Method == null) {
428 Type[] mtypes = new Type [args.Length];
429 for (int i = 0; i < args.Length; ++i) {
430 mtypes [i] = args [i].GetType ();
432 method_info = m_target.GetType ().GetMethod (data.method_name, mtypes);
435 var target = m_target;
436 if (this.data == null)
437 InitializeDelegateData ();
439 if (Method.IsStatic) {
441 // The delegate is bound to m_target
443 if (data.curried_first_arg) {
445 args = new [] { target };
447 Array.Resize (ref args, args.Length + 1);
448 Array.Copy (args, 0, args, 1, args.Length - 1);
455 if (m_target == null && args != null && args.Length > 0) {
457 Array.Copy (args, 1, args, 0, args.Length - 1);
458 Array.Resize (ref args, args.Length - 1);
462 return Method.Invoke (target, args);
465 public virtual object Clone ()
467 return MemberwiseClone ();
470 internal bool Compare (Delegate d)
475 // Do not compare method_ptr, since it can point to a trampoline
476 if (d.m_target == m_target && d.method == method) {
477 if (d.data != null || data != null) {
479 if (d.data != null && data != null)
480 return (d.data.target_type == data.target_type && d.data.method_name == data.method_name);
483 return d.data.target_type == null;
485 return data.target_type == null;
495 public override bool Equals (object obj)
497 return Compare (obj as Delegate);
500 public override int GetHashCode ()
502 return method.GetHashCode () ^ (m_target != null ? m_target.GetHashCode () : 0);
505 protected virtual MethodInfo GetMethodImpl ()
510 // This is from ISerializable
511 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
513 DelegateSerializationHolder.GetDelegateData (this, info, context);
516 public virtual Delegate[] GetInvocationList()
518 return new Delegate[] { this };
522 /// Returns a new MulticastDelegate holding the
523 /// concatenated invocation lists of MulticastDelegates a and b
525 public static Delegate Combine (Delegate a, Delegate b)
530 return a.CombineImpl (b);
534 /// Returns a new MulticastDelegate holding the
535 /// concatenated invocation lists of an Array of MulticastDelegates
537 [System.Runtime.InteropServices.ComVisible (true)]
538 public static Delegate Combine (params Delegate[] delegates)
540 if (delegates == null)
543 Delegate retval = null;
545 foreach (Delegate next in delegates)
546 retval = Combine (retval, next);
551 protected virtual Delegate CombineImpl (Delegate d)
553 throw new MulticastNotSupportedException (String.Empty);
556 public static Delegate Remove (Delegate source, Delegate value)
564 if (source.GetType () != value.GetType ())
565 throw new ArgumentException (Locale.GetText ("Incompatible Delegate Types. First is {0} second is {1}.", source.GetType ().FullName, value.GetType ().FullName));
567 return source.RemoveImpl (value);
570 protected virtual Delegate RemoveImpl (Delegate d)
578 public static Delegate RemoveAll (Delegate source, Delegate value)
580 Delegate tmp = source;
581 while ((source = Delegate.Remove (source, value)) != tmp)
587 public static bool operator == (Delegate d1, Delegate d2)
589 if ((object)d1 == null) {
590 if ((object)d2 == null)
593 } else if ((object) d2 == null)
596 return d1.Equals (d2);
599 public static bool operator != (Delegate d1, Delegate d2)
604 internal bool IsTransparentProxy ()
609 return RemotingServices.IsTransparentProxy (m_target);