1 // Copyright 2011 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_OBSERVER_LIST_H_ 6 #define BASE_OBSERVER_LIST_H_ 7 8 #include <stddef.h> 9 10 #include <algorithm> 11 #include <iterator> 12 #include <limits> 13 #include <ostream> 14 #include <string> 15 #include <utility> 16 #include <vector> 17 18 #include "base/check.h" 19 #include "base/check_op.h" 20 #include "base/dcheck_is_on.h" 21 #include "base/debug/dump_without_crashing.h" 22 #include "base/notreached.h" 23 #include "base/observer_list_internal.h" 24 #include "base/ranges/algorithm.h" 25 #include "base/sequence_checker.h" 26 #include "build/build_config.h" 27 28 /////////////////////////////////////////////////////////////////////////////// 29 // 30 // OVERVIEW: 31 // 32 // A list of observers. Unlike a standard vector or list, this container can 33 // be modified during iteration without invalidating the iterator. So, it 34 // safely handles the case of an observer removing itself or other observers 35 // from the list while observers are being notified. 36 // 37 // 38 // WARNING: 39 // 40 // ObserverList is not thread-compatible. Iterating on the same ObserverList 41 // simultaneously in different threads is not safe, even when the ObserverList 42 // itself is not modified. 43 // 44 // For a thread-safe observer list, see ObserverListThreadSafe. 45 // 46 // 47 // TYPICAL USAGE: 48 // 49 // class MyWidget { 50 // public: 51 // ... 52 // 53 // class Observer : public base::CheckedObserver { 54 // public: 55 // virtual void OnFoo(MyWidget* w) = 0; 56 // virtual void OnBar(MyWidget* w, int x, int y) = 0; 57 // }; 58 // 59 // void AddObserver(Observer* obs) { 60 // observers_.AddObserver(obs); 61 // } 62 // 63 // void RemoveObserver(Observer* obs) { 64 // observers_.RemoveObserver(obs); 65 // } 66 // 67 // void NotifyFoo() { 68 // for (Observer& obs : observers_) 69 // obs.OnFoo(this); 70 // } 71 // 72 // void NotifyBar(int x, int y) { 73 // for (Observer& obs : observers_) 74 // obs.OnBar(this, x, y); 75 // } 76 // 77 // private: 78 // base::ObserverList<Observer> observers_; 79 // }; 80 // 81 // 82 /////////////////////////////////////////////////////////////////////////////// 83 84 namespace base { 85 86 // Enumeration of which observers are notified by ObserverList. 87 enum class ObserverListPolicy { 88 // Specifies that any observers added during notification are notified. 89 // This is the default policy if no policy is provided to the constructor. 90 ALL, 91 92 // Specifies that observers added while sending out notification are not 93 // notified. 94 EXISTING_ONLY, 95 }; 96 97 // When check_empty is true, assert that the list is empty on destruction. 98 // When allow_reentrancy is false, iterating throught the list while already in 99 // the iteration loop will result in DCHECK failure. 100 // TODO(oshima): Change the default to non reentrant. https://crbug.com/812109 101 template <class ObserverType, 102 bool check_empty = false, 103 bool allow_reentrancy = true, 104 class ObserverStorageType = internal::CheckedObserverAdapter> 105 class ObserverList { 106 public: 107 // Allow declaring an ObserverList<...>::Unchecked that replaces the default 108 // ObserverStorageType to use `raw_ptr<T>`. This is required to support legacy 109 // observers that do not inherit from CheckedObserver. The majority of new 110 // code should not use this, but it may be suited for performance-critical 111 // situations to avoid overheads of a CHECK(). Note the type can't be chosen 112 // based on ObserverType's definition because ObserverLists are often declared 113 // in headers using a forward-declare of ObserverType. 114 using Unchecked = ObserverList<ObserverType, 115 check_empty, 116 allow_reentrancy, 117 internal::UncheckedObserverAdapter<>>; 118 // Allow declaring an ObserverList<...>::UncheckedAndDanglingUntriaged that 119 // replaces the default ObserverStorageType to use 120 // `raw_ptr<T, DanglingUntriaged>`. New use of this alias is strongly 121 // discouraged. 122 // TODO(crbug.com/40212619): Triage existing dangling observer pointers and 123 // remove this alias. 124 using UncheckedAndDanglingUntriaged = 125 ObserverList<ObserverType, 126 check_empty, 127 allow_reentrancy, 128 internal::UncheckedObserverAdapter<DanglingUntriaged>>; 129 130 // An iterator class that can be used to access the list of observers. 131 class Iter { 132 public: 133 using iterator_category = std::forward_iterator_tag; 134 using value_type = ObserverType; 135 using difference_type = ptrdiff_t; 136 using pointer = ObserverType*; 137 using reference = ObserverType&; 138 Iter()139 Iter() : index_(0), max_index_(0) {} 140 Iter(const ObserverList * list)141 explicit Iter(const ObserverList* list) 142 : list_(const_cast<ObserverList*>(list)), 143 index_(0), 144 max_index_(list->policy_ == ObserverListPolicy::ALL 145 ? std::numeric_limits<size_t>::max() 146 : list->observers_.size()) { 147 DCHECK(list); 148 // TODO(crbug.com/1423093): Turn into CHECK once very prevalent failures 149 // are weeded out. 150 DUMP_WILL_BE_CHECK(allow_reentrancy || list_.IsOnlyRemainingNode()); 151 // Bind to this sequence when creating the first iterator. 152 DCHECK_CALLED_ON_VALID_SEQUENCE(list_->iteration_sequence_checker_); 153 EnsureValidIndex(); 154 } 155 ~Iter()156 ~Iter() { 157 if (list_.IsOnlyRemainingNode()) 158 list_->Compact(); 159 } 160 Iter(const Iter & other)161 Iter(const Iter& other) 162 : index_(other.index_), max_index_(other.max_index_) { 163 if (other.list_) 164 list_.SetList(other.list_.get()); 165 } 166 167 Iter& operator=(const Iter& other) { 168 if (&other == this) 169 return *this; 170 171 if (list_.IsOnlyRemainingNode()) 172 list_->Compact(); 173 174 list_.Invalidate(); 175 if (other.list_) 176 list_.SetList(other.list_.get()); 177 178 index_ = other.index_; 179 max_index_ = other.max_index_; 180 return *this; 181 } 182 183 bool operator==(const Iter& other) const { 184 return (is_end() && other.is_end()) || 185 (list_.get() == other.list_.get() && index_ == other.index_); 186 } 187 188 bool operator!=(const Iter& other) const { return !(*this == other); } 189 190 Iter& operator++() { 191 if (list_) { 192 ++index_; 193 EnsureValidIndex(); 194 } 195 return *this; 196 } 197 198 Iter operator++(int) { 199 Iter it(*this); 200 ++(*this); 201 return it; 202 } 203 204 ObserverType* operator->() const { 205 ObserverType* const current = GetCurrent(); 206 DCHECK(current); 207 return current; 208 } 209 210 ObserverType& operator*() const { 211 ObserverType* const current = GetCurrent(); 212 DCHECK(current); 213 return *current; 214 } 215 216 private: 217 friend class ObserverListTestBase; 218 GetCurrent()219 ObserverType* GetCurrent() const { 220 DCHECK(list_); 221 DCHECK_LT(index_, clamped_max_index()); 222 return ObserverStorageType::template Get<ObserverType>( 223 list_->observers_[index_]); 224 } 225 EnsureValidIndex()226 void EnsureValidIndex() { 227 DCHECK(list_); 228 const size_t max_index = clamped_max_index(); 229 while (index_ < max_index && 230 list_->observers_[index_].IsMarkedForRemoval()) { 231 ++index_; 232 } 233 } 234 clamped_max_index()235 size_t clamped_max_index() const { 236 return std::min(max_index_, list_->observers_.size()); 237 } 238 is_end()239 bool is_end() const { return !list_ || index_ == clamped_max_index(); } 240 241 // Lightweight weak pointer to the ObserverList. 242 internal::WeakLinkNode<ObserverList> list_; 243 244 // When initially constructed and each time the iterator is incremented, 245 // |index_| is guaranteed to point to a non-null index if the iterator 246 // has not reached the end of the ObserverList. 247 size_t index_; 248 size_t max_index_; 249 }; 250 251 using iterator = Iter; 252 using const_iterator = Iter; 253 using value_type = ObserverType; 254 begin()255 const_iterator begin() const { 256 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_); 257 // An optimization: do not involve weak pointers for empty list. 258 return observers_.empty() ? const_iterator() : const_iterator(this); 259 } 260 end()261 const_iterator end() const { return const_iterator(); } 262 263 explicit ObserverList(ObserverListPolicy policy = ObserverListPolicy::ALL) policy_(policy)264 : policy_(policy) { 265 // Sequence checks only apply when iterators are live. 266 DETACH_FROM_SEQUENCE(iteration_sequence_checker_); 267 } 268 ObserverList(const ObserverList&) = delete; 269 ObserverList& operator=(const ObserverList&) = delete; ~ObserverList()270 ~ObserverList() { 271 // If there are live iterators, ensure destruction is thread-safe. 272 if (!live_iterators_.empty()) 273 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_); 274 275 while (!live_iterators_.empty()) 276 live_iterators_.head()->value()->Invalidate(); 277 if (check_empty) { 278 Compact(); 279 // TODO(crbug.com/1423093): Turn into a CHECK once very prevalent failures 280 // are weeded out. 281 DUMP_WILL_BE_CHECK(observers_.empty()) 282 << "\n" 283 << GetObserversCreationStackString(); 284 } 285 } 286 287 // Add an observer to this list. An observer should not be added to the same 288 // list more than once. 289 // 290 // Precondition: obs != nullptr 291 // Precondition: !HasObserver(obs) AddObserver(ObserverType * obs)292 void AddObserver(ObserverType* obs) { 293 DCHECK(obs); 294 // TODO(crbug.com/1423093): Turn this into a CHECK once very prevalent 295 // failures are weeded out. 296 if (HasObserver(obs)) { 297 DUMP_WILL_BE_NOTREACHED_NORETURN() << "Observers can only be added once!"; 298 return; 299 } 300 observers_count_++; 301 observers_.emplace_back(ObserverStorageType(obs)); 302 } 303 304 // Removes the given observer from this list. Does nothing if this observer is 305 // not in this list. RemoveObserver(const ObserverType * obs)306 void RemoveObserver(const ObserverType* obs) { 307 DCHECK(obs); 308 const auto it = ranges::find_if( 309 observers_, [obs](const auto& o) { return o.IsEqual(obs); }); 310 if (it == observers_.end()) 311 return; 312 if (!it->IsMarkedForRemoval()) 313 observers_count_--; 314 if (live_iterators_.empty()) { 315 observers_.erase(it); 316 } else { 317 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_); 318 it->MarkForRemoval(); 319 } 320 } 321 322 // Determine whether a particular observer is in the list. HasObserver(const ObserverType * obs)323 bool HasObserver(const ObserverType* obs) const { 324 // Client code passing null could be confused by the treatment of observers 325 // removed mid-iteration. TODO(https://crbug.com/876588): This should 326 // probably DCHECK, but some client code currently does pass null. 327 if (obs == nullptr) 328 return false; 329 return ranges::find_if(observers_, [obs](const auto& o) { 330 return o.IsEqual(obs); 331 }) != observers_.end(); 332 } 333 334 // Removes all the observers from this list. Clear()335 void Clear() { 336 if (live_iterators_.empty()) { 337 observers_.clear(); 338 } else { 339 DCHECK_CALLED_ON_VALID_SEQUENCE(iteration_sequence_checker_); 340 for (auto& observer : observers_) 341 observer.MarkForRemoval(); 342 } 343 observers_count_ = 0; 344 } 345 empty()346 bool empty() const { return !observers_count_; } 347 348 private: 349 friend class internal::WeakLinkNode<ObserverList>; 350 351 // Compacts list of observers by removing those marked for removal. Compact()352 void Compact() { 353 // Detach whenever the last iterator is destroyed. Detaching is safe because 354 // Compact() is only ever called when the last iterator is destroyed. 355 DETACH_FROM_SEQUENCE(iteration_sequence_checker_); 356 357 std::erase_if(observers_, 358 [](const auto& o) { return o.IsMarkedForRemoval(); }); 359 } 360 GetObserversCreationStackString()361 std::string GetObserversCreationStackString() const { 362 #if DCHECK_IS_ON() 363 std::string result; 364 #if BUILDFLAG(IS_IOS) 365 result += "Use go/observer-list-empty to interpret.\n"; 366 #endif 367 for (const auto& observer : observers_) { 368 result += observer.GetCreationStackString(); 369 result += "\n"; 370 } 371 return result; 372 #else 373 return "For observer stack traces, build with `dcheck_always_on=true`."; 374 #endif // DCHECK_IS_ON() 375 } 376 377 std::vector<ObserverStorageType> observers_; 378 379 base::LinkedList<internal::WeakLinkNode<ObserverList>> live_iterators_; 380 381 size_t observers_count_{0}; 382 383 const ObserverListPolicy policy_; 384 385 SEQUENCE_CHECKER(iteration_sequence_checker_); 386 }; 387 388 template <class ObserverType, bool check_empty = false> 389 using ReentrantObserverList = ObserverList<ObserverType, check_empty, true>; 390 391 } // namespace base 392 393 #endif // BASE_OBSERVER_LIST_H_ 394