summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Delegate.cs
blob: de0ff6532c2e004ae45c0228be24a24236e2dba1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System
{
    using System;
    using System.Reflection;
    using System.Runtime;
    using System.Threading;
    using System.Runtime.Serialization;
    using System.Runtime.InteropServices;
    using System.Runtime.CompilerServices;
    using System.Runtime.Versioning;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;

    [Serializable]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [System.Runtime.InteropServices.ComVisible(true)]
    public abstract class Delegate : ICloneable, ISerializable
    {
        // _target is the object we will invoke on
        internal Object _target;

        // MethodBase, either cached after first request or assigned from a DynamicMethod
        // For open delegates to collectible types, this may be a LoaderAllocator object
        internal Object _methodBase;

        // _methodPtr is a pointer to the method we will invoke
        // It could be a small thunk if this is a static or UM call
        internal IntPtr _methodPtr;

        // In the case of a static method passed to a delegate, this field stores
        // whatever _methodPtr would have stored: and _methodPtr points to a
        // small thunk which removes the "this" pointer before going on
        // to _methodPtrAux.
        internal IntPtr _methodPtrAux;

        // This constructor is called from the class generated by the
        //  compiler generated code
        protected Delegate(Object target, String method)
        {
            if (target == null)
                throw new ArgumentNullException(nameof(target));

            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            // This API existed in v1/v1.1 and only expected to create closed
            // instance delegates. Constrain the call to BindToMethodName to
            // such and don't allow relaxed signature matching (which could make
            // the choice of target method ambiguous) for backwards
            // compatibility. The name matching was case sensitive and we
            // preserve that as well.
            if (!BindToMethodName(target, (RuntimeType)target.GetType(), method,
                                  DelegateBindingFlags.InstanceMethodOnly |
                                  DelegateBindingFlags.ClosedDelegateOnly))
                throw new ArgumentException(SR.Arg_DlgtTargMeth);
        }

        // This constructor is called from a class to generate a 
        // delegate based upon a static method name and the Type object
        // for the class defining the method.
        protected unsafe Delegate(Type target, String method)
        {
            if (target == null)
                throw new ArgumentNullException(nameof(target));

            if (target.IsGenericType && target.ContainsGenericParameters)
                throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));

            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            RuntimeType rtTarget = target as RuntimeType;
            if (rtTarget == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));

            // This API existed in v1/v1.1 and only expected to create open
            // static delegates. Constrain the call to BindToMethodName to such
            // and don't allow relaxed signature matching (which could make the
            // choice of target method ambiguous) for backwards compatibility.
            // The name matching was case insensitive (no idea why this is
            // different from the constructor above) and we preserve that as
            // well.
            BindToMethodName(null, rtTarget, method,
                             DelegateBindingFlags.StaticMethodOnly |
                             DelegateBindingFlags.OpenDelegateOnly |
                             DelegateBindingFlags.CaselessMatching);
        }

        // Protect the default constructor so you can't build a delegate
        private Delegate()
        {
        }

        public Object DynamicInvoke(params Object[] args)
        {
            // Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
            // But to maintain backward compatibility we can't switch to calling an 
            // internal overload of DynamicInvokeImpl that takes a stack mark.
            // Fortunately the stack walker skips all the reflection invocation frames including this one.
            // So this method will never be returned by the stack walker as the caller.
            // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
            return DynamicInvokeImpl(args);
        }

        protected virtual object DynamicInvokeImpl(object[] args)
        {
            RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
            RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);

            return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null);
        }


        public override bool Equals(Object obj)
        {
            if (obj == null || !InternalEqualTypes(this, obj))
                return false;

            Delegate d = (Delegate)obj;

            // do an optimistic check first. This is hopefully cheap enough to be worth
            if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
                return true;

            // even though the fields were not all equals the delegates may still match
            // When target carries the delegate itself the 2 targets (delegates) may be different instances
            // but the delegates are logically the same
            // It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other 
            // if that's the case the delegates may still be equals but we need to make a more complicated check

            if (_methodPtrAux.IsNull())
            {
                if (!d._methodPtrAux.IsNull())
                    return false; // different delegate kind
                // they are both closed over the first arg
                if (_target != d._target)
                    return false;
                // fall through method handle check
            }
            else
            {
                if (d._methodPtrAux.IsNull())
                    return false; // different delegate kind

                // Ignore the target as it will be the delegate instance, though it may be a different one
                /*
                if (_methodPtr != d._methodPtr)
                    return false;
                    */

                if (_methodPtrAux == d._methodPtrAux)
                    return true;
                // fall through method handle check
            }

            // method ptrs don't match, go down long path
            // 
            if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo))
                return Delegate.InternalEqualMethodHandles(this, d);
            else
                return _methodBase.Equals(d._methodBase);
        }

        public override int GetHashCode()
        {
            //
            // this is not right in the face of a method being jitted in one delegate and not in another
            // in that case the delegate is the same and Equals will return true but GetHashCode returns a
            // different hashcode which is not true.
            /*
            if (_methodPtrAux.IsNull())
                return unchecked((int)((long)this._methodPtr));
            else
                return unchecked((int)((long)this._methodPtrAux));
            */
            return GetType().GetHashCode();
        }

        public static Delegate Combine(Delegate a, Delegate b)
        {
            if ((Object)a == null) // cast to object for a more efficient test
                return b;

            return a.CombineImpl(b);
        }

        public static Delegate Combine(params Delegate[] delegates)
        {
            if (delegates == null || delegates.Length == 0)
                return null;

            Delegate d = delegates[0];
            for (int i = 1; i < delegates.Length; i++)
                d = Combine(d, delegates[i]);

            return d;
        }

        public virtual Delegate[] GetInvocationList()
        {
            Delegate[] d = new Delegate[1];
            d[0] = this;
            return d;
        }

        // This routine will return the method
        public MethodInfo Method
        {
            get
            {
                return GetMethodImpl();
            }
        }

        protected virtual MethodInfo GetMethodImpl()
        {
            if ((_methodBase == null) || !(_methodBase is MethodInfo))
            {
                IRuntimeMethodInfo method = FindMethodHandle();
                RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
                // need a proper declaring type instance method on a generic type
                if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
                {
                    bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0;
                    if (!isStatic)
                    {
                        if (_methodPtrAux == (IntPtr)0)
                        {
                            // The target may be of a derived type that doesn't have visibility onto the
                            // target method. We don't want to call RuntimeType.GetMethodBase below with that
                            // or reflection can end up generating a MethodInfo where the ReflectedType cannot
                            // see the MethodInfo itself and that breaks an important invariant. But the
                            // target type could include important generic type information we need in order
                            // to work out what the exact instantiation of the method's declaring type is. So
                            // we'll walk up the inheritance chain (which will yield exactly instantiated
                            // types at each step) until we find the declaring type. Since the declaring type
                            // we get from the method is probably shared and those in the hierarchy we're
                            // walking won't be we compare using the generic type definition forms instead.
                            Type currentType = _target.GetType();
                            Type targetType = declaringType.GetGenericTypeDefinition();
                            while (currentType != null)
                            {
                                if (currentType.IsGenericType &&
                                    currentType.GetGenericTypeDefinition() == targetType)
                                {
                                    declaringType = currentType as RuntimeType;
                                    break;
                                }
                                currentType = currentType.BaseType;
                            }

                            // RCWs don't need to be "strongly-typed" in which case we don't find a base type
                            // that matches the declaring type of the method. This is fine because interop needs
                            // to work with exact methods anyway so declaringType is never shared at this point.
                            BCLDebug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method");
                        }
                        else
                        {
                            // it's an open one, need to fetch the first arg of the instantiation
                            MethodInfo invoke = this.GetType().GetMethod("Invoke");
                            declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType;
                        }
                    }
                }
                _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
            }
            return (MethodInfo)_methodBase;
        }

        public Object Target
        {
            get
            {
                return GetTarget();
            }
        }


        public static Delegate Remove(Delegate source, Delegate value)
        {
            if (source == null)
                return null;

            if (value == null)
                return source;

            if (!InternalEqualTypes(source, value))
                throw new ArgumentException(SR.Arg_DlgtTypeMis);

            return source.RemoveImpl(value);
        }

        public static Delegate RemoveAll(Delegate source, Delegate value)
        {
            Delegate newDelegate = null;

            do
            {
                newDelegate = source;
                source = Remove(source, value);
            }
            while (newDelegate != source);

            return newDelegate;
        }

        protected virtual Delegate CombineImpl(Delegate d)
        {
            throw new MulticastNotSupportedException(SR.Multicast_Combine);
        }

        protected virtual Delegate RemoveImpl(Delegate d)
        {
            return (d.Equals(this)) ? null : this;
        }


        public virtual Object Clone()
        {
            return MemberwiseClone();
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, Object target, String method)
        {
            return CreateDelegate(type, target, method, false, true);
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase)
        {
            return CreateDelegate(type, target, method, ignoreCase, true);
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            if (target == null)
                throw new ArgumentNullException(nameof(target));
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            RuntimeType rtType = type as RuntimeType;
            if (rtType == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
            if (!rtType.IsDelegate())
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));

            Delegate d = InternalAlloc(rtType);
            // This API existed in v1/v1.1 and only expected to create closed
            // instance delegates. Constrain the call to BindToMethodName to such
            // and don't allow relaxed signature matching (which could make the
            // choice of target method ambiguous) for backwards compatibility.
            // We never generate a closed over null delegate and this is
            // actually enforced via the check on target above, but we pass
            // NeverCloseOverNull anyway just for clarity.
            if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method,
                                    DelegateBindingFlags.InstanceMethodOnly |
                                    DelegateBindingFlags.ClosedDelegateOnly |
                                    DelegateBindingFlags.NeverCloseOverNull |
                                    (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
            {
                if (throwOnBindFailure)
                    throw new ArgumentException(SR.Arg_DlgtTargMeth);
                d = null;
            }

            return d;
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, Type target, String method)
        {
            return CreateDelegate(type, target, method, false, true);
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase)
        {
            return CreateDelegate(type, target, method, ignoreCase, true);
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            if (target == null)
                throw new ArgumentNullException(nameof(target));
            if (target.IsGenericType && target.ContainsGenericParameters)
                throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            RuntimeType rtType = type as RuntimeType;
            RuntimeType rtTarget = target as RuntimeType;
            if (rtType == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
            if (rtTarget == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
            if (!rtType.IsDelegate())
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));

            Delegate d = InternalAlloc(rtType);
            // This API existed in v1/v1.1 and only expected to create open
            // static delegates. Constrain the call to BindToMethodName to such
            // and don't allow relaxed signature matching (which could make the
            // choice of target method ambiguous) for backwards compatibility.
            if (!d.BindToMethodName(null, rtTarget, method,
                                    DelegateBindingFlags.StaticMethodOnly |
                                    DelegateBindingFlags.OpenDelegateOnly |
                                    (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
            {
                if (throwOnBindFailure)
                    throw new ArgumentException(SR.Arg_DlgtTargMeth);
                d = null;
            }

            return d;
        }

        // V1 API.
        [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
        public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
        {
            // Validate the parameters.
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            RuntimeType rtType = type as RuntimeType;
            if (rtType == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));

            RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
            if (rmi == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));

            if (!rtType.IsDelegate())
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));

            // This API existed in v1/v1.1 and only expected to create closed
            // instance delegates. Constrain the call to BindToMethodInfo to
            // open delegates only for backwards compatibility. But we'll allow
            // relaxed signature checking and open static delegates because
            // there's no ambiguity there (the caller would have to explicitly
            // pass us a static method or a method with a non-exact signature
            // and the only change in behavior from v1.1 there is that we won't
            // fail the call).
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            Delegate d = CreateDelegateInternal(
                rtType,
                rmi,
                null,
                DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
                ref stackMark);

            if (d == null && throwOnBindFailure)
                throw new ArgumentException(SR.Arg_DlgtTargMeth);

            return d;
        }

        // V2 API.
        public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
        {
            return CreateDelegate(type, firstArgument, method, true);
        }

        // V2 API.
        [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
        public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
        {
            // Validate the parameters.
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            RuntimeType rtType = type as RuntimeType;
            if (rtType == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));

            RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
            if (rmi == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));

            if (!rtType.IsDelegate())
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));

            // This API is new in Whidbey and allows the full range of delegate
            // flexability (open or closed delegates binding to static or
            // instance methods with relaxed signature checking. The delegate
            // can also be closed over null. There's no ambiguity with all these
            // options since the caller is providing us a specific MethodInfo.
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            Delegate d = CreateDelegateInternal(
                rtType,
                rmi,
                firstArgument,
                DelegateBindingFlags.RelaxedSignature,
               ref stackMark);

            if (d == null && throwOnBindFailure)
                throw new ArgumentException(SR.Arg_DlgtTargMeth);

            return d;
        }

        public static bool operator ==(Delegate d1, Delegate d2)
        {
            if ((Object)d1 == null)
                return (Object)d2 == null;

            return d1.Equals(d2);
        }

        public static bool operator !=(Delegate d1, Delegate d2)
        {
            if ((Object)d1 == null)
                return (Object)d2 != null;

            return !d1.Equals(d2);
        }

        //
        // Implementation of ISerializable
        //

        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            throw new NotSupportedException();
        }
        //
        // internal implementation details (FCALLS and utilities)
        //

        // V2 internal API.
        // This is Critical because it skips the security check when creating the delegate.
        internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
        {
            // Validate the parameters.
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            Contract.EndContractBlock();

            if (method.IsNullHandle())
                throw new ArgumentNullException(nameof(method));

            RuntimeType rtType = type as RuntimeType;
            if (rtType == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));

            if (!rtType.IsDelegate())
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));

            // Initialize the method...
            Delegate d = InternalAlloc(rtType);
            // This is a new internal API added in Whidbey. Currently it's only
            // used by the dynamic method code to generate a wrapper delegate.
            // Allow flexible binding options since the target method is
            // unambiguously provided to us.

            if (!d.BindToMethodInfo(target,
                                    method.GetMethodInfo(),
                                    RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()),
                                    DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks))
                throw new ArgumentException(SR.Arg_DlgtTargMeth);
            return d;
        }

        // Caution: this method is intended for deserialization only, no security checks are performed.
        internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
        {
            // Validate the parameters.
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            if (method == null)
                throw new ArgumentNullException(nameof(method));

            Contract.EndContractBlock();

            RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
            if (rtMethod == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));

            if (!type.IsDelegate())
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));

            // This API is used by the formatters when deserializing a delegate.
            // They pass us the specific target method (that was already the
            // target in a valid delegate) so we should bind with the most
            // relaxed rules available (the result will never be ambiguous, it
            // just increases the chance of success with minor (compatible)
            // signature changes). We explicitly skip security checks here --
            // we're not really constructing a delegate, we're cloning an
            // existing instance which already passed its checks.
            Delegate d = UnsafeCreateDelegate(type, rtMethod, firstArgument,
                                              DelegateBindingFlags.SkipSecurityChecks |
                                              DelegateBindingFlags.RelaxedSignature);

            if (d == null)
                throw new ArgumentException(SR.Arg_DlgtTargMeth);

            return d;
        }

        // V1 API.
        public static Delegate CreateDelegate(Type type, MethodInfo method)
        {
            return CreateDelegate(type, method, true);
        }

        internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
        {
            Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);

            return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
        }

        internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
        {
            Delegate d = InternalAlloc(rtType);

            if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags))
                return d;
            else
                return null;
        }

        //
        // internal implementation details (FCALLS and utilities)
        //

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern static MulticastDelegate InternalAlloc(RuntimeType type);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern static MulticastDelegate InternalAllocLike(Delegate d);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern static bool InternalEqualTypes(object a, object b);

        // Used by the ctor. Do not call directly.
        // The name of this function will appear in managed stacktraces as delegate constructor.
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern void DelegateConstruct(Object target, IntPtr slot);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IntPtr GetMulticastInvoke();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IntPtr GetInvokeMethod();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IRuntimeMethodInfo FindMethodHandle();

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern IntPtr GetCallStub(IntPtr methodPtr);

        internal virtual Object GetTarget()
        {
            return (_methodPtrAux.IsNull()) ? _target : null;
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal extern static bool CompareUnmanagedFunctionPtrs(Delegate d1, Delegate d2);
    }

    // These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
    // values must be kept in sync with the definition in vm\comdelegate.h.
    internal enum DelegateBindingFlags
    {
        StaticMethodOnly = 0x00000001, // Can only bind to static target methods
        InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
        OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
        ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
        NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
        CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
        SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
        RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
    }
}