main /Runtime/Microsoft.Dynamic/Actions/EventTracker.cs

Language C# Lines 307
MD5 Hash 7008f2e0e1b11d298ab6b09c7cd50146 Estimated Cost $5,143 (why?)
Repository git://github.com/IronLanguages/main.git View Raw File View Project SPDX
  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
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Apache License, Version 2.0, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Apache License, Version 2.0.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;

namespace Microsoft.Scripting.Actions {
    public class EventTracker : MemberTracker {
        // For each instance of the class that declares the event there is a list of pairs in a table 
        // (like if we added an instance field for each instance event into its declaring class). 
        // We use _staticTarget for a static event (it is bound to its declaring type).
        // Each pair in the list holds on the stub handler that was added to the event delegate chain and the callable 
        // object that is passed to +=/-= operators. 
        private WeakDictionary<object, NormalHandlerList> _handlerLists;
        private static readonly object _staticTarget = new object();

        private readonly EventInfo _eventInfo;
        private MethodInfo _addMethod;
        private MethodInfo _removeMethod;

        internal EventTracker(EventInfo eventInfo) {
            Assert.NotNull(eventInfo);
            _eventInfo = eventInfo;
        }

        public override Type DeclaringType {
            get { return _eventInfo.DeclaringType; }
        }

        public override TrackerTypes MemberType {
            get { return TrackerTypes.Event; }
        }

        public override string Name {
            get { return _eventInfo.Name; }
        }

        public EventInfo Event {
            get {
                return _eventInfo;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public MethodInfo GetCallableAddMethod() {
            if (_addMethod == null) {
                _addMethod = _eventInfo.GetAddMethod(true);
            }
            return _addMethod;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public MethodInfo GetCallableRemoveMethod() {
            if (_removeMethod == null) {
                _removeMethod = _eventInfo.GetRemoveMethod(true);
            }
            return _removeMethod;
        }

        /// <summary>
        /// Doesn't need to check PrivateBinding setting: no method that is part of the event is public the entire event is private. 
        /// If the code has already a reference to the event tracker instance for a private event its "static-ness" is not influenced 
        /// by private-binding setting.
        /// </summary>
        public bool IsStatic {
            get {
                MethodInfo mi = Event.GetAddMethod(false) ??
                    Event.GetRemoveMethod(false) ??
                    Event.GetRaiseMethod(false) ??
                    Event.GetAddMethod(true) ??
                    Event.GetRemoveMethod(true) ??
                    Event.GetRaiseMethod(true);

                MethodInfo m;
                Debug.Assert(
                    ((m = Event.GetAddMethod(true)) == null || m.IsStatic == mi.IsStatic) &&
                    ((m = Event.GetRaiseMethod(true)) == null || m.IsStatic == mi.IsStatic) &&
                    ((m = Event.GetRaiseMethod(true)) == null || m.IsStatic == mi.IsStatic),
                    "Methods are either all static or all instance."
                );
                
                return mi.IsStatic;
            }
        }

        protected internal override DynamicMetaObject GetBoundValue(OverloadResolverFactory resolverFactory, ActionBinder binder, Type type, DynamicMetaObject instance) {
            return binder.ReturnMemberTracker(type, new BoundMemberTracker(this, instance));
        }

        public override MemberTracker BindToInstance(DynamicMetaObject instance) {
            if (IsStatic) {
                return this;
            }

            return new BoundMemberTracker(this, instance);
        }

        public override string ToString() {
            return _eventInfo.ToString();
        }

        public void AddHandler(object target, object handler, DynamicDelegateCreator delegateCreator) {
            ContractUtils.RequiresNotNull(handler, "handler");
            ContractUtils.RequiresNotNull(delegateCreator, "delegateCreator");

            Delegate delegateHandler;
            HandlerList stubs;

            // we can add event directly (signature does match):
            if (_eventInfo.EventHandlerType.IsAssignableFrom(handler.GetType())) {
                delegateHandler = (Delegate)handler;
                stubs = null;
            } else {
                // create signature converting stub:
                delegateHandler = delegateCreator.GetDelegate(handler, _eventInfo.EventHandlerType);
                stubs = GetHandlerList(target);
            }

            var add = GetCallableAddMethod();

            // TODO (tomat): this used to use event.ReflectedType, is it still correct?
            if (target != null) {
                add = CompilerHelpers.TryGetCallableMethod(target.GetType(), add);
            }

            add.Invoke(target, new object[] { delegateHandler });

            if (stubs != null) {
                // remember the stub so that we could search for it on removal:
                stubs.AddHandler(handler, delegateHandler);
            }
        }

        public void RemoveHandler(object target, object handler, IEqualityComparer<object> objectComparer) {
            ContractUtils.RequiresNotNull(handler, "handler");
            ContractUtils.RequiresNotNull(objectComparer, "objectComparer");

            Delegate delegateHandler;
            if (_eventInfo.EventHandlerType.IsAssignableFrom(handler.GetType())) {
                delegateHandler = (Delegate)handler;
            } else {
                delegateHandler = GetHandlerList(target).RemoveHandler(handler, objectComparer);
            }

            if (delegateHandler != null) {
                GetCallableRemoveMethod().Invoke(target, new object[] { delegateHandler });
            }
        }

        #region Private Implementation Details

        private HandlerList GetHandlerList(object instance) {
#if FEATURE_COM
            if (TypeUtils.IsComObject(instance)) {
                return GetComHandlerList(instance);
            }
#endif

            if (_handlerLists == null) {
                Interlocked.CompareExchange(ref _handlerLists, new WeakDictionary<object, NormalHandlerList>(), null);
            }

            if (instance == null) {
                // targetting a static method, we'll use a random object
                // as our place holder here...
                instance = _staticTarget;
            }

            lock (_handlerLists) {
                NormalHandlerList result;
                if (_handlerLists.TryGetValue(instance, out result)) {
                    return result;
                }

                result = new NormalHandlerList();
                _handlerLists[instance] = result;
                return result;
            }
        }

#if FEATURE_COM
        /// <summary>
        /// Gets the stub list for a COM Object.  For COM objects we store the stub list
        /// directly on the object using the Marshal APIs.  This allows us to not have
        /// any circular references to deal with via weak references which are challenging
        /// in the face of COM.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
        private HandlerList GetComHandlerList(object instance) {
            HandlerList hl = (HandlerList)Marshal.GetComObjectData(instance, this);
            if (hl == null) {
                lock (_staticTarget) {
                    hl = (HandlerList)Marshal.GetComObjectData(instance, this);
                    if (hl == null) {
                        hl = new ComHandlerList();
                        if (!Marshal.SetComObjectData(instance, this, hl)) {
                            throw new COMException("Failed to set COM Object Data");
                        }
                    }
                }
            }

            return hl;
        }
#endif

        /// <summary>
        /// Holds on a list of delegates hooked to the event. 
        /// We need the list because we cannot enumerate the delegates hooked to CLR event and we need to do so in 
        /// handler removal (we need to do custom delegate comparison there). If BCL enables the enumeration we could remove this.
        /// </summary>
        private abstract class HandlerList {
            public abstract void AddHandler(object callableObject, Delegate handler);
            public abstract Delegate RemoveHandler(object callableObject, IEqualityComparer<object> comparer);
        }

#if !SILVERLIGHT
        private sealed class ComHandlerList : HandlerList {
            /// <summary>
            /// Storage for the handlers - a key value pair of the callable object and the delegate handler.
            /// </summary>
            private readonly CopyOnWriteList<KeyValuePair<object, object>> _handlers = new CopyOnWriteList<KeyValuePair<object, object>>();

            public override void AddHandler(object callableObject, Delegate handler) {
                Assert.NotNull(handler);
                _handlers.Add(new KeyValuePair<object, object>(callableObject, handler));
            }

            public override Delegate RemoveHandler(object callableObject, IEqualityComparer<object> comparer) {
                List<KeyValuePair<object, object>> copyOfHandlers = _handlers.GetCopyForRead();
                for (int i = copyOfHandlers.Count - 1; i >= 0; i--) {
                    object key = copyOfHandlers[i].Key;
                    object value = copyOfHandlers[i].Value;

                    if (comparer.Equals(key, callableObject)) {
                        Delegate handler = (Delegate)value;
                        _handlers.RemoveAt(i);
                        return handler;
                    }
                }

                return null;
            }
        }
#endif

        private sealed class NormalHandlerList : HandlerList {
            /// <summary>
            /// Storage for the handlers - a key value pair of the callable object and the delegate handler.
            /// 
            /// The delegate handler is closed over the callable object.  Therefore as long as the object is alive the
            /// delegate will stay alive and so will the callable object.  That means it's fine to have a weak reference
            /// to both of these objects.
            /// </summary>
            private readonly CopyOnWriteList<KeyValuePair<WeakReference, WeakReference>> _handlers = new CopyOnWriteList<KeyValuePair<WeakReference, WeakReference>>();

            public NormalHandlerList() {
            }

            public override void AddHandler(object callableObject, Delegate handler) {
                Assert.NotNull(handler);
                _handlers.Add(new KeyValuePair<WeakReference, WeakReference>(new WeakReference(callableObject), new WeakReference(handler)));
            }

            public override Delegate RemoveHandler(object callableObject, IEqualityComparer<object> comparer) {
                List<KeyValuePair<WeakReference, WeakReference>> copyOfHandlers = _handlers.GetCopyForRead();
                for (int i = copyOfHandlers.Count - 1; i >= 0; i--) {
                    object key = copyOfHandlers[i].Key.Target;
                    object value = copyOfHandlers[i].Value.Target;

                    if (key != null && value != null && comparer.Equals(key, callableObject)) {
                        Delegate handler = (Delegate)value;
                        _handlers.RemoveAt(i);
                        return handler;
                    }
                }

                return null;
            }
        }

        #endregion
    }
}
Back to Top