| 6 | #define BASE_MEMORY_REF_COUNTED_H_ |
| 7 |
| 8 | #include <stddef.h> |
| 9 |
| 10 | #include <utility> |
| 11 |
| 12 | #include "base/atomic_ref_count.h" |
| 13 | #include "base/base_export.h" |
| 14 | #include "base/compiler_specific.h" |
| 15 | #include "base/gtest_prod_util.h" |
| 16 | #include "base/logging.h" |
| 17 | #include "base/macros.h" |
| 18 | #include "base/memory/scoped_refptr.h" |
| 19 | #include "base/sequence_checker.h" |
| 20 | #include "base/threading/thread_collision_warner.h" |
| 21 | #include "build/build_config.h" |
| 22 |
| 23 | namespace base { |
| 24 | namespace subtle { |
| 25 |
| 26 | class BASE_EXPORT RefCountedBase { |
| 27 | public: |
| 28 | bool HasOneRef() const { return ref_count_ == 1; } |
| 29 | bool HasAtLeastOneRef() const { return ref_count_ >= 1; } |
| 30 |
| 31 | protected: |
| 32 | explicit RefCountedBase(StartRefCountFromZeroTag) { |
| 33 | #if DCHECK_IS_ON() |
| 34 | sequence_checker_.DetachFromSequence(); |
| 35 | #endif |
| 36 | } |
| 37 |
| 38 | explicit RefCountedBase(StartRefCountFromOneTag) : ref_count_(1) { |
| 39 | #if DCHECK_IS_ON() |
| 40 | needs_adopt_ref_ = true; |
| 41 | sequence_checker_.DetachFromSequence(); |
| 42 | #endif |
| 43 | } |
| 44 |
| 45 | ~RefCountedBase() { |
| 46 | #if DCHECK_IS_ON() |
| 47 | DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()"; |
| 48 | #endif |
| 49 | } |
| 50 |
| 51 | void AddRef() const { |
| 52 | // TODO(maruel): Add back once it doesn't assert 500 times/sec. |
| 53 | // Current thread books the critical section "AddRelease" |
| 54 | // without release it. |
| 55 | // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); |
| 56 | #if DCHECK_IS_ON() |
| 57 | DCHECK(!in_dtor_); |
| 58 | DCHECK(!needs_adopt_ref_) |
| 59 | << "This RefCounted object is created with non-zero reference count." |
| 60 | << " The first reference to such a object has to be made by AdoptRef or" |
| 61 | << " MakeRefCounted."; |
| 62 | if (ref_count_ >= 1) { |
| 63 | DCHECK(CalledOnValidSequence()); |
| 64 | } |
| 65 | #endif |
| 66 |
| 67 | AddRefImpl(); |
| 68 | } |
| 69 |
| 70 | // Returns true if the object should self-delete. |
| 71 | bool Release() const { |
| 72 | ReleaseImpl(); |
| 73 |
| 74 | // TODO(maruel): Add back once it doesn't assert 500 times/sec. |
| 75 | // Current thread books the critical section "AddRelease" |
| 76 | // without release it. |
| 77 | // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); |
| 78 |
| 79 | #if DCHECK_IS_ON() |
| 80 | DCHECK(!in_dtor_); |
| 81 | if (ref_count_ == 0) |
| 82 | in_dtor_ = true; |
| 83 |
| 84 | if (ref_count_ >= 1) |
| 85 | DCHECK(CalledOnValidSequence()); |
| 86 | if (ref_count_ == 1) |
| 87 | sequence_checker_.DetachFromSequence(); |
| 88 | #endif |
| 89 |
| 90 | return ref_count_ == 0; |
| 91 | } |
| 92 |
| 93 | // Returns true if it is safe to read or write the object, from a thread |
| 94 | // safety standpoint. Should be DCHECK'd from the methods of RefCounted |
| 95 | // classes if there is a danger of objects being shared across threads. |
| 96 | // |
| 97 | // This produces fewer false positives than adding a separate SequenceChecker |
| 98 | // into the subclass, because it automatically detaches from the sequence when |
| 99 | // the reference count is 1 (and never fails if there is only one reference). |
| 100 | // |
| 101 | // This means unlike a separate SequenceChecker, it will permit a singly |
| 102 | // referenced object to be passed between threads (not holding a reference on |
| 103 | // the sending thread), but will trap if the sending thread holds onto a |
| 104 | // reference, or if the object is accessed from multiple threads |
| 105 | // simultaneously. |
| 106 | bool IsOnValidSequence() const { |
| 107 | #if DCHECK_IS_ON() |
| 108 | return ref_count_ <= 1 || CalledOnValidSequence(); |
| 109 | #else |
| 110 | return true; |
| 111 | #endif |
| 112 | } |
| 113 |
| 114 | private: |
| 115 | template <typename U> |
| 116 | friend scoped_refptr<U> base::AdoptRef(U*); |
| 117 |
| 118 | FRIEND_TEST_ALL_PREFIXES(RefCountedDeathTest, TestOverflowCheck); |
| 119 |
| 120 | void Adopted() const { |
| 121 | #if DCHECK_IS_ON() |
| 122 | DCHECK(needs_adopt_ref_); |
| 123 | needs_adopt_ref_ = false; |
| 124 | #endif |
| 125 | } |
| 126 |
| 127 | #if defined(ARCH_CPU_64_BITS) |
| 128 | void AddRefImpl() const; |
| 129 | void ReleaseImpl() const; |
| 130 | #else |
| 131 | void AddRefImpl() const { ++ref_count_; } |
| 132 | void ReleaseImpl() const { --ref_count_; } |
| 133 | #endif |
| 134 |
| 135 | #if DCHECK_IS_ON() |
| 136 | bool CalledOnValidSequence() const; |
| 137 | #endif |
| 138 |
| 139 | mutable uint32_t ref_count_ = 0; |
| 140 | static_assert(std::is_unsigned<decltype(ref_count_)>::value, |
| 141 | "ref_count_ must be an unsigned type."); |
| 142 |
| 143 | #if DCHECK_IS_ON() |
| 144 | mutable bool needs_adopt_ref_ = false; |
| 145 | mutable bool in_dtor_ = false; |
| 146 | mutable SequenceChecker sequence_checker_; |
| 147 | #endif |
| 148 |
| 149 | DFAKE_MUTEX(add_release_); |
| 150 |
| 151 | DISALLOW_COPY_AND_ASSIGN(RefCountedBase); |
| 152 | }; |
| 153 |
| 154 | class BASE_EXPORT RefCountedThreadSafeBase { |
| 155 | public: |
| 156 | bool HasOneRef() const; |
| 157 | bool HasAtLeastOneRef() const; |
| 158 |
| 159 | protected: |
| 160 | explicit constexpr RefCountedThreadSafeBase(StartRefCountFromZeroTag) {} |
| 161 | explicit constexpr RefCountedThreadSafeBase(StartRefCountFromOneTag) |
| 162 | : ref_count_(1) { |
| 163 | #if DCHECK_IS_ON() |
| 164 | needs_adopt_ref_ = true; |
| 165 | #endif |
| 166 | } |
| 167 |
| 168 | #if DCHECK_IS_ON() |
| 169 | ~RefCountedThreadSafeBase(); |
| 170 | #else |
| 171 | ~RefCountedThreadSafeBase() = default; |
| 172 | #endif |
| 173 |
| 174 | // Release and AddRef are suitable for inlining on X86 because they generate |
| 175 | // very small code sequences. On other platforms (ARM), it causes a size |
| 176 | // regression and is probably not worth it. |
| 177 | #if defined(ARCH_CPU_X86_FAMILY) |
| 178 | // Returns true if the object should self-delete. |
| 179 | bool Release() const { return ReleaseImpl(); } |
| 180 | void AddRef() const { AddRefImpl(); } |
| 181 | void AddRefWithCheck() const { AddRefWithCheckImpl(); } |
| 182 | #else |
| 183 | // Returns true if the object should self-delete. |
| 184 | bool Release() const; |
| 185 | void AddRef() const; |
| 186 | void AddRefWithCheck() const; |
| 187 | #endif |
| 188 |
| 189 | private: |
| 190 | template <typename U> |
| 191 | friend scoped_refptr<U> base::AdoptRef(U*); |
| 192 |
| 193 | void Adopted() const { |
| 194 | #if DCHECK_IS_ON() |
| 195 | DCHECK(needs_adopt_ref_); |
| 196 | needs_adopt_ref_ = false; |
| 197 | #endif |
| 198 | } |
| 199 |
| 200 | ALWAYS_INLINE void AddRefImpl() const { |
| 201 | #if DCHECK_IS_ON() |
| 202 | DCHECK(!in_dtor_); |
| 203 | DCHECK(!needs_adopt_ref_) |
| 204 | << "This RefCounted object is created with non-zero reference count." |
| 205 | << " The first reference to such a object has to be made by AdoptRef or" |
| 206 | << " MakeRefCounted."; |
| 207 | #endif |
| 208 | ref_count_.Increment(); |
| 209 | } |
| 210 |
| 211 | ALWAYS_INLINE void AddRefWithCheckImpl() const { |
| 212 | #if DCHECK_IS_ON() |
| 213 | DCHECK(!in_dtor_); |
| 214 | DCHECK(!needs_adopt_ref_) |
| 215 | << "This RefCounted object is created with non-zero reference count." |
| 216 | << " The first reference to such a object has to be made by AdoptRef or" |
| 217 | << " MakeRefCounted."; |
| 218 | #endif |
| 219 | CHECK(ref_count_.Increment() > 0); |
| 220 | } |
| 221 |
| 222 | ALWAYS_INLINE bool ReleaseImpl() const { |
| 223 | #if DCHECK_IS_ON() |
| 224 | DCHECK(!in_dtor_); |
| 225 | DCHECK(!ref_count_.IsZero()); |
| 226 | #endif |
| 227 | if (!ref_count_.Decrement()) { |
| 228 | #if DCHECK_IS_ON() |
| 229 | in_dtor_ = true; |
| 230 | #endif |
| 231 | return true; |
| 232 | } |
| 233 | return false; |
| 234 | } |
| 235 |
| 236 | mutable AtomicRefCount ref_count_{0}; |
| 237 | #if DCHECK_IS_ON() |
| 238 | mutable bool needs_adopt_ref_ = false; |
| 239 | mutable bool in_dtor_ = false; |
| 240 | #endif |
| 241 |
| 242 | DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase); |
| 243 | }; |
| 244 |
| 245 | } // namespace subtle |
| 246 |
| 247 | // ScopedAllowCrossThreadRefCountAccess disables the check documented on |
| 248 | // RefCounted below for rare pre-existing use cases where thread-safety was |
| 249 | // guaranteed through other means (e.g. explicit sequencing of calls across |
| 250 | // execution sequences when bouncing between threads in order). New callers |
| 251 | // should refrain from using this (callsites handling thread-safety through |
| 252 | // locks should use RefCountedThreadSafe per the overhead of its atomics being |
| 253 | // negligible compared to locks anyways and callsites doing explicit sequencing |
| 254 | // should properly std::move() the ref to avoid hitting this check). |
| 255 | // TODO(tzik): Cleanup existing use cases and remove |
| 256 | // ScopedAllowCrossThreadRefCountAccess. |
| 257 | class BASE_EXPORT ScopedAllowCrossThreadRefCountAccess final { |
| 258 | public: |
| 259 | #if DCHECK_IS_ON() |
| 260 | ScopedAllowCrossThreadRefCountAccess(); |
| 261 | ~ScopedAllowCrossThreadRefCountAccess(); |
| 262 | #else |
| 263 | ScopedAllowCrossThreadRefCountAccess() {} |
| 264 | ~ScopedAllowCrossThreadRefCountAccess() {} |
| 265 | #endif |
| 266 | }; |
| 267 |
| 268 | // |
| 269 | // A base class for reference counted classes. Otherwise, known as a cheap |
| 270 | // knock-off of WebKit's RefCounted<T> class. To use this, just extend your |
| 271 | // class from it like so: |
| 272 | // |
| 273 | // class MyFoo : public base::RefCounted<MyFoo> { |
| 274 | // ... |
| 275 | // private: |
| 276 | // friend class base::RefCounted<MyFoo>; |
| 277 | // ~MyFoo(); |
| 278 | // }; |
| 279 | // |
| 280 | // You should always make your destructor non-public, to avoid any code deleting |
| 281 | // the object accidently while there are references to it. |
| 282 | // |
| 283 | // |
| 284 | // The ref count manipulation to RefCounted is NOT thread safe and has DCHECKs |
| 285 | // to trap unsafe cross thread usage. A subclass instance of RefCounted can be |
| 286 | // passed to another execution sequence only when its ref count is 1. If the ref |
| 287 | // count is more than 1, the RefCounted class verifies the ref updates are made |
| 288 | // on the same execution sequence as the previous ones. The subclass can also |
| 289 | // manually call IsOnValidSequence to trap other non-thread-safe accesses; see |
| 290 | // the documentation for that method. |
| 291 | // |
| 292 | // |
| 293 | // The reference count starts from zero by default, and we intended to migrate |
| 294 | // to start-from-one ref count. Put REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE() to |
| 295 | // the ref counted class to opt-in. |
| 296 | // |
| 297 | // If an object has start-from-one ref count, the first scoped_refptr need to be |
| 298 | // created by base::AdoptRef() or base::MakeRefCounted(). We can use |
| 299 | // base::MakeRefCounted() to create create both type of ref counted object. |
| 300 | // |
| 301 | // The motivations to use start-from-one ref count are: |
| 302 | // - Start-from-one ref count doesn't need the ref count increment for the |
| 303 | // first reference. |
| 304 | // - It can detect an invalid object acquisition for a being-deleted object |
| 305 | // that has zero ref count. That tends to happen on custom deleter that |
| 306 | // delays the deletion. |
| 307 | // TODO(tzik): Implement invalid acquisition detection. |
| 308 | // - Behavior parity to Blink's WTF::RefCounted, whose count starts from one. |
| 309 | // And start-from-one ref count is a step to merge WTF::RefCounted into |
| 310 | // base::RefCounted. |
| 311 | // |
| 312 | #define REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE() \ |
| 313 | static constexpr ::base::subtle::StartRefCountFromOneTag \ |
| 314 | kRefCountPreference = ::base::subtle::kStartRefCountFromOneTag |
| 315 |
| 316 | template <class T, typename Traits> |
| 317 | class RefCounted; |
| 318 |
| 319 | template <typename T> |
| 320 | struct DefaultRefCountedTraits { |
| 321 | static void Destruct(const T* x) { |
| 322 | RefCounted<T, DefaultRefCountedTraits>::DeleteInternal(x); |
| 323 | } |
| 324 | }; |
| 325 |
| 326 | template <class T, typename Traits = DefaultRefCountedTraits<T>> |
| 327 | class RefCounted : public subtle::RefCountedBase { |
| 328 | public: |
| 329 | static constexpr subtle::StartRefCountFromZeroTag kRefCountPreference = |
| 330 | subtle::kStartRefCountFromZeroTag; |
| 331 |
| 332 | RefCounted() : subtle::RefCountedBase(T::kRefCountPreference) {} |
| 333 |
| 334 | void AddRef() const { |
| 335 | subtle::RefCountedBase::AddRef(); |
| 336 | } |
| 337 |
| 338 | void Release() const { |
| 339 | if (subtle::RefCountedBase::Release()) { |
| 340 | // Prune the code paths which the static analyzer may take to simulate |
| 341 | // object destruction. Use-after-free errors aren't possible given the |
| 342 | // lifetime guarantees of the refcounting system. |
| 343 | ANALYZER_SKIP_THIS_PATH(); |
| 344 |
| 345 | Traits::Destruct(static_cast<const T*>(this)); |
| 346 | } |
| 347 | } |
| 348 |
| 349 | protected: |
| 350 | ~RefCounted() = default; |
| 351 |
| 352 | private: |
| 353 | friend struct DefaultRefCountedTraits<T>; |
| 354 | template <typename U> |
| 355 | static void DeleteInternal(const U* x) { |
| 356 | delete x; |
| 357 | } |
| 358 |
| 359 | DISALLOW_COPY_AND_ASSIGN(RefCounted); |
| 360 | }; |
| 361 |
| 362 | // Forward declaration. |
| 363 | template <class T, typename Traits> class RefCountedThreadSafe; |
| 364 |
| 365 | // Default traits for RefCountedThreadSafe<T>. Deletes the object when its ref |
| 366 | // count reaches 0. Overload to delete it on a different thread etc. |
| 367 | template<typename T> |
| 368 | struct DefaultRefCountedThreadSafeTraits { |
| 369 | static void Destruct(const T* x) { |
| 370 | // Delete through RefCountedThreadSafe to make child classes only need to be |
| 371 | // friend with RefCountedThreadSafe instead of this struct, which is an |
| 372 | // implementation detail. |
| 373 | RefCountedThreadSafe<T, |
| 374 | DefaultRefCountedThreadSafeTraits>::DeleteInternal(x); |
| 375 | } |
| 376 | }; |
| 377 |
| 378 | // |
| 379 | // A thread-safe variant of RefCounted<T> |
| 380 | // |
| 381 | // class MyFoo : public base::RefCountedThreadSafe<MyFoo> { |
| 382 | // ... |
| 383 | // }; |
| 384 | // |
| 385 | // If you're using the default trait, then you should add compile time |
| 386 | // asserts that no one else is deleting your object. i.e. |
| 387 | // private: |
| 388 | // friend class base::RefCountedThreadSafe<MyFoo>; |
| 389 | // ~MyFoo(); |
| 390 | // |
| 391 | // We can use REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE() with RefCountedThreadSafe |
| 392 | // too. See the comment above the RefCounted definition for details. |
| 393 | template <class T, typename Traits = DefaultRefCountedThreadSafeTraits<T> > |
| 394 | class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase { |
| 395 | public: |
| 396 | static constexpr subtle::StartRefCountFromZeroTag kRefCountPreference = |
| 397 | subtle::kStartRefCountFromZeroTag; |
| 398 |
| 399 | explicit RefCountedThreadSafe() |
| 400 | : subtle::RefCountedThreadSafeBase(T::kRefCountPreference) {} |
| 401 |
| 402 | void AddRef() const { AddRefImpl(T::kRefCountPreference); } |
| 403 |
| 404 | void Release() const { |
| 405 | if (subtle::RefCountedThreadSafeBase::Release()) { |
| 406 | ANALYZER_SKIP_THIS_PATH(); |
| 407 | Traits::Destruct(static_cast<const T*>(this)); |
| 408 | } |
| 409 | } |
| 410 |
| 411 | protected: |
| 412 | ~RefCountedThreadSafe() = default; |
| 413 |
| 414 | private: |
| 415 | friend struct DefaultRefCountedThreadSafeTraits<T>; |
| 416 | template <typename U> |
| 417 | static void DeleteInternal(const U* x) { |
| 418 | delete x; |
| 419 | } |
| 420 |
| 421 | void AddRefImpl(subtle::StartRefCountFromZeroTag) const { |
| 422 | subtle::RefCountedThreadSafeBase::AddRef(); |
| 423 | } |
| 424 |
| 425 | void AddRefImpl(subtle::StartRefCountFromOneTag) const { |
| 426 | subtle::RefCountedThreadSafeBase::AddRefWithCheck(); |
| 427 | } |
| 428 |
| 429 | DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe); |
| 430 | }; |
| 431 |
| 432 | // |
| 433 | // A thread-safe wrapper for some piece of data so we can place other |
| 434 | // things in scoped_refptrs<>. |
| 435 | // |
| 436 | template<typename T> |
| 437 | class RefCountedData |
| 438 | : public base::RefCountedThreadSafe< base::RefCountedData<T> > { |
| 439 | public: |
| 440 | RefCountedData() : data() {} |
| 441 | RefCountedData(const T& in_value) : data(in_value) {} |
| 442 | RefCountedData(T&& in_value) : data(std::move(in_value)) {} |
| 443 |
| 444 | T data; |
| 445 |
| 446 | private: |
| 447 | friend class base::RefCountedThreadSafe<base::RefCountedData<T> >; |
| 448 | ~RefCountedData() = default; |
| 449 | }; |
| 450 |
| 451 | template <typename T> |
| 452 | bool operator==(const RefCountedData<T>& lhs, const RefCountedData<T>& rhs) { |
| 453 | return lhs.data == rhs.data; |
| 454 | } |
| 455 |
| 456 | template <typename T> |
| 457 | bool operator!=(const RefCountedData<T>& lhs, const RefCountedData<T>& rhs) { |
| 458 | return !(lhs == rhs); |
| 459 | } |
| 460 |
| 461 | } // namespace base |
| 462 |
| 463 | #endif // BASE_MEMORY_REF_COUNTED_H_ |
| 464 |