security/sandbox/chromium/base/observer_list_threadsafe.h

Wed, 31 Dec 2014 07:16:47 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 07:16:47 +0100
branch
TOR_BUG_9701
changeset 3
141e0f1194b1
permissions
-rw-r--r--

Revert simplistic fix pending revisit of Mozilla integration attempt.

michael@0 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
michael@0 2 // Use of this source code is governed by a BSD-style license that can be
michael@0 3 // found in the LICENSE file.
michael@0 4
michael@0 5 #ifndef BASE_OBSERVER_LIST_THREADSAFE_H_
michael@0 6 #define BASE_OBSERVER_LIST_THREADSAFE_H_
michael@0 7
michael@0 8 #include <algorithm>
michael@0 9 #include <map>
michael@0 10
michael@0 11 #include "base/basictypes.h"
michael@0 12 #include "base/bind.h"
michael@0 13 #include "base/location.h"
michael@0 14 #include "base/logging.h"
michael@0 15 #include "base/memory/ref_counted.h"
michael@0 16 #include "base/message_loop/message_loop.h"
michael@0 17 #include "base/message_loop/message_loop_proxy.h"
michael@0 18 #include "base/observer_list.h"
michael@0 19 #include "base/stl_util.h"
michael@0 20 #include "base/threading/platform_thread.h"
michael@0 21
michael@0 22 ///////////////////////////////////////////////////////////////////////////////
michael@0 23 //
michael@0 24 // OVERVIEW:
michael@0 25 //
michael@0 26 // A thread-safe container for a list of observers.
michael@0 27 // This is similar to the observer_list (see observer_list.h), but it
michael@0 28 // is more robust for multi-threaded situations.
michael@0 29 //
michael@0 30 // The following use cases are supported:
michael@0 31 // * Observers can register for notifications from any thread.
michael@0 32 // Callbacks to the observer will occur on the same thread where
michael@0 33 // the observer initially called AddObserver() from.
michael@0 34 // * Any thread may trigger a notification via Notify().
michael@0 35 // * Observers can remove themselves from the observer list inside
michael@0 36 // of a callback.
michael@0 37 // * If one thread is notifying observers concurrently with an observer
michael@0 38 // removing itself from the observer list, the notifications will
michael@0 39 // be silently dropped.
michael@0 40 //
michael@0 41 // The drawback of the threadsafe observer list is that notifications
michael@0 42 // are not as real-time as the non-threadsafe version of this class.
michael@0 43 // Notifications will always be done via PostTask() to another thread,
michael@0 44 // whereas with the non-thread-safe observer_list, notifications happen
michael@0 45 // synchronously and immediately.
michael@0 46 //
michael@0 47 // IMPLEMENTATION NOTES
michael@0 48 // The ObserverListThreadSafe maintains an ObserverList for each thread
michael@0 49 // which uses the ThreadSafeObserver. When Notifying the observers,
michael@0 50 // we simply call PostTask to each registered thread, and then each thread
michael@0 51 // will notify its regular ObserverList.
michael@0 52 //
michael@0 53 ///////////////////////////////////////////////////////////////////////////////
michael@0 54
michael@0 55 // Forward declaration for ObserverListThreadSafeTraits.
michael@0 56 template <class ObserverType>
michael@0 57 class ObserverListThreadSafe;
michael@0 58
michael@0 59 // An UnboundMethod is a wrapper for a method where the actual object is
michael@0 60 // provided at Run dispatch time.
michael@0 61 template <class T, class Method, class Params>
michael@0 62 class UnboundMethod {
michael@0 63 public:
michael@0 64 UnboundMethod(Method m, const Params& p) : m_(m), p_(p) {
michael@0 65 COMPILE_ASSERT(
michael@0 66 (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value),
michael@0 67 badunboundmethodparams);
michael@0 68 }
michael@0 69 void Run(T* obj) const {
michael@0 70 DispatchToMethod(obj, m_, p_);
michael@0 71 }
michael@0 72 private:
michael@0 73 Method m_;
michael@0 74 Params p_;
michael@0 75 };
michael@0 76
michael@0 77 // This class is used to work around VS2005 not accepting:
michael@0 78 //
michael@0 79 // friend class
michael@0 80 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >;
michael@0 81 //
michael@0 82 // Instead of friending the class, we could friend the actual function
michael@0 83 // which calls delete. However, this ends up being
michael@0 84 // RefCountedThreadSafe::DeleteInternal(), which is private. So we
michael@0 85 // define our own templated traits class so we can friend it.
michael@0 86 template <class T>
michael@0 87 struct ObserverListThreadSafeTraits {
michael@0 88 static void Destruct(const ObserverListThreadSafe<T>* x) {
michael@0 89 delete x;
michael@0 90 }
michael@0 91 };
michael@0 92
michael@0 93 template <class ObserverType>
michael@0 94 class ObserverListThreadSafe
michael@0 95 : public base::RefCountedThreadSafe<
michael@0 96 ObserverListThreadSafe<ObserverType>,
michael@0 97 ObserverListThreadSafeTraits<ObserverType> > {
michael@0 98 public:
michael@0 99 typedef typename ObserverList<ObserverType>::NotificationType
michael@0 100 NotificationType;
michael@0 101
michael@0 102 ObserverListThreadSafe()
michael@0 103 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
michael@0 104 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
michael@0 105
michael@0 106 // Add an observer to the list. An observer should not be added to
michael@0 107 // the same list more than once.
michael@0 108 void AddObserver(ObserverType* obs) {
michael@0 109 // If there is not a current MessageLoop, it is impossible to notify on it,
michael@0 110 // so do not add the observer.
michael@0 111 if (!base::MessageLoop::current())
michael@0 112 return;
michael@0 113
michael@0 114 ObserverList<ObserverType>* list = NULL;
michael@0 115 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
michael@0 116 {
michael@0 117 base::AutoLock lock(list_lock_);
michael@0 118 if (observer_lists_.find(thread_id) == observer_lists_.end())
michael@0 119 observer_lists_[thread_id] = new ObserverListContext(type_);
michael@0 120 list = &(observer_lists_[thread_id]->list);
michael@0 121 }
michael@0 122 list->AddObserver(obs);
michael@0 123 }
michael@0 124
michael@0 125 // Remove an observer from the list if it is in the list.
michael@0 126 // If there are pending notifications in-transit to the observer, they will
michael@0 127 // be aborted.
michael@0 128 // If the observer to be removed is in the list, RemoveObserver MUST
michael@0 129 // be called from the same thread which called AddObserver.
michael@0 130 void RemoveObserver(ObserverType* obs) {
michael@0 131 ObserverListContext* context = NULL;
michael@0 132 ObserverList<ObserverType>* list = NULL;
michael@0 133 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
michael@0 134 {
michael@0 135 base::AutoLock lock(list_lock_);
michael@0 136 typename ObserversListMap::iterator it = observer_lists_.find(thread_id);
michael@0 137 if (it == observer_lists_.end()) {
michael@0 138 // This will happen if we try to remove an observer on a thread
michael@0 139 // we never added an observer for.
michael@0 140 return;
michael@0 141 }
michael@0 142 context = it->second;
michael@0 143 list = &context->list;
michael@0 144
michael@0 145 // If we're about to remove the last observer from the list,
michael@0 146 // then we can remove this observer_list entirely.
michael@0 147 if (list->HasObserver(obs) && list->size() == 1)
michael@0 148 observer_lists_.erase(it);
michael@0 149 }
michael@0 150 list->RemoveObserver(obs);
michael@0 151
michael@0 152 // If RemoveObserver is called from a notification, the size will be
michael@0 153 // nonzero. Instead of deleting here, the NotifyWrapper will delete
michael@0 154 // when it finishes iterating.
michael@0 155 if (list->size() == 0)
michael@0 156 delete context;
michael@0 157 }
michael@0 158
michael@0 159 // Verifies that the list is currently empty (i.e. there are no observers).
michael@0 160 void AssertEmpty() const {
michael@0 161 base::AutoLock lock(list_lock_);
michael@0 162 DCHECK(observer_lists_.empty());
michael@0 163 }
michael@0 164
michael@0 165 // Notify methods.
michael@0 166 // Make a thread-safe callback to each Observer in the list.
michael@0 167 // Note, these calls are effectively asynchronous. You cannot assume
michael@0 168 // that at the completion of the Notify call that all Observers have
michael@0 169 // been Notified. The notification may still be pending delivery.
michael@0 170 template <class Method>
michael@0 171 void Notify(Method m) {
michael@0 172 UnboundMethod<ObserverType, Method, Tuple0> method(m, MakeTuple());
michael@0 173 Notify<Method, Tuple0>(method);
michael@0 174 }
michael@0 175
michael@0 176 template <class Method, class A>
michael@0 177 void Notify(Method m, const A& a) {
michael@0 178 UnboundMethod<ObserverType, Method, Tuple1<A> > method(m, MakeTuple(a));
michael@0 179 Notify<Method, Tuple1<A> >(method);
michael@0 180 }
michael@0 181
michael@0 182 template <class Method, class A, class B>
michael@0 183 void Notify(Method m, const A& a, const B& b) {
michael@0 184 UnboundMethod<ObserverType, Method, Tuple2<A, B> > method(
michael@0 185 m, MakeTuple(a, b));
michael@0 186 Notify<Method, Tuple2<A, B> >(method);
michael@0 187 }
michael@0 188
michael@0 189 template <class Method, class A, class B, class C>
michael@0 190 void Notify(Method m, const A& a, const B& b, const C& c) {
michael@0 191 UnboundMethod<ObserverType, Method, Tuple3<A, B, C> > method(
michael@0 192 m, MakeTuple(a, b, c));
michael@0 193 Notify<Method, Tuple3<A, B, C> >(method);
michael@0 194 }
michael@0 195
michael@0 196 template <class Method, class A, class B, class C, class D>
michael@0 197 void Notify(Method m, const A& a, const B& b, const C& c, const D& d) {
michael@0 198 UnboundMethod<ObserverType, Method, Tuple4<A, B, C, D> > method(
michael@0 199 m, MakeTuple(a, b, c, d));
michael@0 200 Notify<Method, Tuple4<A, B, C, D> >(method);
michael@0 201 }
michael@0 202
michael@0 203 // TODO(mbelshe): Add more wrappers for Notify() with more arguments.
michael@0 204
michael@0 205 private:
michael@0 206 // See comment above ObserverListThreadSafeTraits' definition.
michael@0 207 friend struct ObserverListThreadSafeTraits<ObserverType>;
michael@0 208
michael@0 209 struct ObserverListContext {
michael@0 210 explicit ObserverListContext(NotificationType type)
michael@0 211 : loop(base::MessageLoopProxy::current()),
michael@0 212 list(type) {
michael@0 213 }
michael@0 214
michael@0 215 scoped_refptr<base::MessageLoopProxy> loop;
michael@0 216 ObserverList<ObserverType> list;
michael@0 217
michael@0 218 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
michael@0 219 };
michael@0 220
michael@0 221 ~ObserverListThreadSafe() {
michael@0 222 STLDeleteValues(&observer_lists_);
michael@0 223 }
michael@0 224
michael@0 225 template <class Method, class Params>
michael@0 226 void Notify(const UnboundMethod<ObserverType, Method, Params>& method) {
michael@0 227 base::AutoLock lock(list_lock_);
michael@0 228 typename ObserversListMap::iterator it;
michael@0 229 for (it = observer_lists_.begin(); it != observer_lists_.end(); ++it) {
michael@0 230 ObserverListContext* context = (*it).second;
michael@0 231 context->loop->PostTask(
michael@0 232 FROM_HERE,
michael@0 233 base::Bind(&ObserverListThreadSafe<ObserverType>::
michael@0 234 template NotifyWrapper<Method, Params>, this, context, method));
michael@0 235 }
michael@0 236 }
michael@0 237
michael@0 238 // Wrapper which is called to fire the notifications for each thread's
michael@0 239 // ObserverList. This function MUST be called on the thread which owns
michael@0 240 // the unsafe ObserverList.
michael@0 241 template <class Method, class Params>
michael@0 242 void NotifyWrapper(ObserverListContext* context,
michael@0 243 const UnboundMethod<ObserverType, Method, Params>& method) {
michael@0 244
michael@0 245 // Check that this list still needs notifications.
michael@0 246 {
michael@0 247 base::AutoLock lock(list_lock_);
michael@0 248 typename ObserversListMap::iterator it =
michael@0 249 observer_lists_.find(base::PlatformThread::CurrentId());
michael@0 250
michael@0 251 // The ObserverList could have been removed already. In fact, it could
michael@0 252 // have been removed and then re-added! If the master list's loop
michael@0 253 // does not match this one, then we do not need to finish this
michael@0 254 // notification.
michael@0 255 if (it == observer_lists_.end() || it->second != context)
michael@0 256 return;
michael@0 257 }
michael@0 258
michael@0 259 {
michael@0 260 typename ObserverList<ObserverType>::Iterator it(context->list);
michael@0 261 ObserverType* obs;
michael@0 262 while ((obs = it.GetNext()) != NULL)
michael@0 263 method.Run(obs);
michael@0 264 }
michael@0 265
michael@0 266 // If there are no more observers on the list, we can now delete it.
michael@0 267 if (context->list.size() == 0) {
michael@0 268 {
michael@0 269 base::AutoLock lock(list_lock_);
michael@0 270 // Remove |list| if it's not already removed.
michael@0 271 // This can happen if multiple observers got removed in a notification.
michael@0 272 // See http://crbug.com/55725.
michael@0 273 typename ObserversListMap::iterator it =
michael@0 274 observer_lists_.find(base::PlatformThread::CurrentId());
michael@0 275 if (it != observer_lists_.end() && it->second == context)
michael@0 276 observer_lists_.erase(it);
michael@0 277 }
michael@0 278 delete context;
michael@0 279 }
michael@0 280 }
michael@0 281
michael@0 282 // Key by PlatformThreadId because in tests, clients can attempt to remove
michael@0 283 // observers without a MessageLoop. If this were keyed by MessageLoop, that
michael@0 284 // operation would be silently ignored, leaving garbage in the ObserverList.
michael@0 285 typedef std::map<base::PlatformThreadId, ObserverListContext*>
michael@0 286 ObserversListMap;
michael@0 287
michael@0 288 mutable base::Lock list_lock_; // Protects the observer_lists_.
michael@0 289 ObserversListMap observer_lists_;
michael@0 290 const NotificationType type_;
michael@0 291
michael@0 292 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
michael@0 293 };
michael@0 294
michael@0 295 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_

mercurial