| 6 | // PLEASE READ: Do you really need a singleton? If possible, use a |
| 7 | // function-local static of type base::NoDestructor<T> instead: |
| 8 | // |
| 9 | // Factory& Factory::GetInstance() { |
| 10 | // static base::NoDestructor<Factory> instance; |
| 11 | // return *instance; |
| 12 | // } |
| 13 | // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |
| 14 | // |
| 15 | // Singletons make it hard to determine the lifetime of an object, which can |
| 16 | // lead to buggy code and spurious crashes. |
| 17 | // |
| 18 | // Instead of adding another singleton into the mix, try to identify either: |
| 19 | // a) An existing singleton that can manage your object's lifetime |
| 20 | // b) Locations where you can deterministically create the object and pass |
| 21 | // into other objects |
| 22 | // |
| 23 | // If you absolutely need a singleton, please keep them as trivial as possible |
| 24 | // and ideally a leaf dependency. Singletons get problematic when they attempt |
| 25 | // to do too much in their destructor or have circular dependencies. |
| 26 |
| 27 | #ifndef BASE_MEMORY_SINGLETON_H_ |
| 28 | #define BASE_MEMORY_SINGLETON_H_ |
| 29 |
| 30 | #include "base/at_exit.h" |
| 31 | #include "base/atomicops.h" |
| 32 | #include "base/base_export.h" |
| 33 | #include "base/lazy_instance_helpers.h" |
| 34 | #include "base/logging.h" |
| 35 | #include "base/macros.h" |
| 36 | #include "base/threading/thread_restrictions.h" |
| 37 |
| 38 | namespace base { |
| 39 |
| 40 | // Default traits for Singleton<Type>. Calls operator new and operator delete on |
| 41 | // the object. Registers automatic deletion at process exit. |
| 42 | // Overload if you need arguments or another memory allocation function. |
| 43 | template<typename Type> |
| 44 | struct DefaultSingletonTraits { |
| 45 | // Allocates the object. |
| 46 | static Type* New() { |
| 47 | // The parenthesis is very important here; it forces POD type |
| 48 | // initialization. |
| 49 | return new Type(); |
| 50 | } |
| 51 |
| 52 | // Destroys the object. |
| 53 | static void Delete(Type* x) { |
| 54 | delete x; |
| 55 | } |
| 56 |
| 57 | // Set to true to automatically register deletion of the object on process |
| 58 | // exit. See below for the required call that makes this happen. |
| 59 | static const bool kRegisterAtExit = true; |
| 60 |
| 61 | #if DCHECK_IS_ON() |
| 62 | // Set to false to disallow access on a non-joinable thread. This is |
| 63 | // different from kRegisterAtExit because StaticMemorySingletonTraits allows |
| 64 | // access on non-joinable threads, and gracefully handles this. |
| 65 | static const bool kAllowedToAccessOnNonjoinableThread = false; |
| 66 | #endif |
| 67 | }; |
| 68 |
| 69 |
| 70 | // Alternate traits for use with the Singleton<Type>. Identical to |
| 71 | // DefaultSingletonTraits except that the Singleton will not be cleaned up |
| 72 | // at exit. |
| 73 | template<typename Type> |
| 74 | struct LeakySingletonTraits : public DefaultSingletonTraits<Type> { |
| 75 | static const bool kRegisterAtExit = false; |
| 76 | #if DCHECK_IS_ON() |
| 77 | static const bool kAllowedToAccessOnNonjoinableThread = true; |
| 78 | #endif |
| 79 | }; |
| 80 |
| 81 | // Alternate traits for use with the Singleton<Type>. Allocates memory |
| 82 | // for the singleton instance from a static buffer. The singleton will |
| 83 | // be cleaned up at exit, but can't be revived after destruction unless |
| 84 | // the ResurrectForTesting() method is called. |
| 85 | // |
| 86 | // This is useful for a certain category of things, notably logging and |
| 87 | // tracing, where the singleton instance is of a type carefully constructed to |
| 88 | // be safe to access post-destruction. |
| 89 | // In logging and tracing you'll typically get stray calls at odd times, like |
| 90 | // during static destruction, thread teardown and the like, and there's a |
| 91 | // termination race on the heap-based singleton - e.g. if one thread calls |
| 92 | // get(), but then another thread initiates AtExit processing, the first thread |
| 93 | // may call into an object residing in unallocated memory. If the instance is |
| 94 | // allocated from the data segment, then this is survivable. |
| 95 | // |
| 96 | // The destructor is to deallocate system resources, in this case to unregister |
| 97 | // a callback the system will invoke when logging levels change. Note that |
| 98 | // this is also used in e.g. Chrome Frame, where you have to allow for the |
| 99 | // possibility of loading briefly into someone else's process space, and |
| 100 | // so leaking is not an option, as that would sabotage the state of your host |
| 101 | // process once you've unloaded. |
| 102 | template <typename Type> |
| 103 | struct StaticMemorySingletonTraits { |
| 104 | // WARNING: User has to support a New() which returns null. |
| 105 | static Type* New() { |
| 106 | // Only constructs once and returns pointer; otherwise returns null. |
| 107 | if (subtle::NoBarrier_AtomicExchange(&dead_, 1)) |
| 108 | return nullptr; |
| 109 |
| 110 | return new (buffer_) Type(); |
| 111 | } |
| 112 |
| 113 | static void Delete(Type* p) { |
| 114 | if (p) |
| 115 | p->Type::~Type(); |
| 116 | } |
| 117 |
| 118 | static const bool kRegisterAtExit = true; |
| 119 |
| 120 | #if DCHECK_IS_ON() |
| 121 | static const bool kAllowedToAccessOnNonjoinableThread = true; |
| 122 | #endif |
| 123 |
| 124 | static void ResurrectForTesting() { subtle::NoBarrier_Store(&dead_, 0); } |
| 125 |
| 126 | private: |
| 127 | alignas(Type) static char buffer_[sizeof(Type)]; |
| 128 | // Signal the object was already deleted, so it is not revived. |
| 129 | static subtle::Atomic32 dead_; |
| 130 | }; |
| 131 |
| 132 | template <typename Type> |
| 133 | alignas(Type) char StaticMemorySingletonTraits<Type>::buffer_[sizeof(Type)]; |
| 134 | template <typename Type> |
| 135 | subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0; |
| 136 |
| 137 | // The Singleton<Type, Traits, DifferentiatingType> class manages a single |
| 138 | // instance of Type which will be created on first use and will be destroyed at |
| 139 | // normal process exit). The Trait::Delete function will not be called on |
| 140 | // abnormal process exit. |
| 141 | // |
| 142 | // DifferentiatingType is used as a key to differentiate two different |
| 143 | // singletons having the same memory allocation functions but serving a |
| 144 | // different purpose. This is mainly used for Locks serving different purposes. |
| 145 | // |
| 146 | // Example usage: |
| 147 | // |
| 148 | // In your header: |
| 149 | // namespace base { |
| 150 | // template <typename T> |
| 151 | // struct DefaultSingletonTraits; |
| 152 | // } |
| 153 | // class FooClass { |
| 154 | // public: |
| 155 | // static FooClass* GetInstance(); <-- See comment below on this. |
| 156 | // void Bar() { ... } |
| 157 | // private: |
| 158 | // FooClass() { ... } |
| 159 | // friend struct base::DefaultSingletonTraits<FooClass>; |
| 160 | // |
| 161 | // DISALLOW_COPY_AND_ASSIGN(FooClass); |
| 162 | // }; |
| 163 | // |
| 164 | // In your source file: |
| 165 | // #include "base/memory/singleton.h" |
| 166 | // FooClass* FooClass::GetInstance() { |
| 167 | // return base::Singleton<FooClass>::get(); |
| 168 | // } |
| 169 | // |
| 170 | // Or for leaky singletons: |
| 171 | // #include "base/memory/singleton.h" |
| 172 | // FooClass* FooClass::GetInstance() { |
| 173 | // return base::Singleton< |
| 174 | // FooClass, base::LeakySingletonTraits<FooClass>>::get(); |
| 175 | // } |
| 176 | // |
| 177 | // And to call methods on FooClass: |
| 178 | // FooClass::GetInstance()->Bar(); |
| 179 | // |
| 180 | // NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance |
| 181 | // and it is important that FooClass::GetInstance() is not inlined in the |
| 182 | // header. This makes sure that when source files from multiple targets include |
| 183 | // this header they don't end up with different copies of the inlined code |
| 184 | // creating multiple copies of the singleton. |
| 185 | // |
| 186 | // Singleton<> has no non-static members and doesn't need to actually be |
| 187 | // instantiated. |
| 188 | // |
| 189 | // This class is itself thread-safe. The underlying Type must of course be |
| 190 | // thread-safe if you want to use it concurrently. Two parameters may be tuned |
| 191 | // depending on the user's requirements. |
| 192 | // |
| 193 | // Glossary: |
| 194 | // RAE = kRegisterAtExit |
| 195 | // |
| 196 | // On every platform, if Traits::RAE is true, the singleton will be destroyed at |
| 197 | // process exit. More precisely it uses AtExitManager which requires an |
| 198 | // object of this type to be instantiated. AtExitManager mimics the semantics |
| 199 | // of atexit() such as LIFO order but under Windows is safer to call. For more |
| 200 | // information see at_exit.h. |
| 201 | // |
| 202 | // If Traits::RAE is false, the singleton will not be freed at process exit, |
| 203 | // thus the singleton will be leaked if it is ever accessed. Traits::RAE |
| 204 | // shouldn't be false unless absolutely necessary. Remember that the heap where |
| 205 | // the object is allocated may be destroyed by the CRT anyway. |
| 206 | // |
| 207 | // Caveats: |
| 208 | // (a) Every call to get(), operator->() and operator*() incurs some overhead |
| 209 | // (16ns on my P4/2.8GHz) to check whether the object has already been |
| 210 | // initialized. You may wish to cache the result of get(); it will not |
| 211 | // change. |
| 212 | // |
| 213 | // (b) Your factory function must never throw an exception. This class is not |
| 214 | // exception-safe. |
| 215 | // |
| 216 |
| 217 | template <typename Type, |
| 218 | typename Traits = DefaultSingletonTraits<Type>, |
| 219 | typename DifferentiatingType = Type> |
| 220 | class Singleton { |
| 221 | private: |
| 222 | // A class T using the Singleton<T> pattern should declare a GetInstance() |
| 223 | // method and call Singleton::get() from within that. T may also declare a |
| 224 | // GetInstanceIfExists() method to invoke Singleton::GetIfExists(). |
| 225 | friend Type; |
| 226 |
| 227 | // This class is safe to be constructed and copy-constructed since it has no |
| 228 | // member. |
| 229 |
| 230 | // Returns a pointer to the one true instance of the class. |
| 231 | static Type* get() { |
| 232 | #if DCHECK_IS_ON() |
| 233 | if (!Traits::kAllowedToAccessOnNonjoinableThread) |
| 234 | ThreadRestrictions::AssertSingletonAllowed(); |
| 235 | #endif |
| 236 |
| 237 | return subtle::GetOrCreateLazyPointer( |
| 238 | &instance_, &CreatorFunc, nullptr, |
| 239 | Traits::kRegisterAtExit ? OnExit : nullptr, nullptr); |
| 240 | } |
| 241 |
| 242 | // Returns the same result as get() if the instance exists but doesn't |
| 243 | // construct it (and returns null) if it doesn't. |
| 244 | static Type* GetIfExists() { |
| 245 | #if DCHECK_IS_ON() |
| 246 | if (!Traits::kAllowedToAccessOnNonjoinableThread) |
| 247 | ThreadRestrictions::AssertSingletonAllowed(); |
| 248 | #endif |
| 249 |
| 250 | if (!subtle::NoBarrier_Load(&instance_)) |
| 251 | return nullptr; |
| 252 |
| 253 | // Need to invoke get() nonetheless as some Traits return null after |
| 254 | // destruction (even though |instance_| still holds garbage). |
| 255 | return get(); |
| 256 | } |
| 257 |
| 258 | // Internal method used as an adaptor for GetOrCreateLazyPointer(). Do not use |
| 259 | // outside of that use case. |
| 260 | static Type* CreatorFunc(void* /* creator_arg*/) { return Traits::New(); } |
| 261 |
| 262 | // Adapter function for use with AtExit(). This should be called single |
| 263 | // threaded, so don't use atomic operations. |
| 264 | // Calling OnExit while singleton is in use by other threads is a mistake. |
| 265 | static void OnExit(void* /*unused*/) { |
| 266 | // AtExit should only ever be register after the singleton instance was |
| 267 | // created. We should only ever get here with a valid instance_ pointer. |
| 268 | Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_))); |
| 269 | instance_ = 0; |
| 270 | } |
| 271 | static subtle::AtomicWord instance_; |
| 272 | }; |
| 273 |
| 274 | template <typename Type, typename Traits, typename DifferentiatingType> |
| 275 | subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0; |
| 276 |
| 277 | } // namespace base |
| 278 |
| 279 | #endif // BASE_MEMORY_SINGLETON_H_ |
| 280 |