• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
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.
NewDefaultSingletonTraits46   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.
DeleteDefaultSingletonTraits53   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.
NewStaticMemorySingletonTraits105   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 
DeleteStaticMemorySingletonTraits113   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 
ResurrectForTestingStaticMemorySingletonTraits124   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   // Classes using the Singleton<T> pattern should declare a GetInstance()
223   // method and call Singleton::get() from within that.
224   friend Type* Type::GetInstance();
225 
226   // This class is safe to be constructed and copy-constructed since it has no
227   // member.
228 
229   // Return a pointer to the one true instance of the class.
get()230   static Type* get() {
231 #if DCHECK_IS_ON()
232     if (!Traits::kAllowedToAccessOnNonjoinableThread)
233       ThreadRestrictions::AssertSingletonAllowed();
234 #endif
235 
236     return subtle::GetOrCreateLazyPointer(
237         &instance_, &CreatorFunc, nullptr,
238         Traits::kRegisterAtExit ? OnExit : nullptr, nullptr);
239   }
240 
241   // Internal method used as an adaptor for GetOrCreateLazyPointer(). Do not use
242   // outside of that use case.
CreatorFunc(void *)243   static Type* CreatorFunc(void* /* creator_arg*/) { return Traits::New(); }
244 
245   // Adapter function for use with AtExit().  This should be called single
246   // threaded, so don't use atomic operations.
247   // Calling OnExit while singleton is in use by other threads is a mistake.
OnExit(void *)248   static void OnExit(void* /*unused*/) {
249     // AtExit should only ever be register after the singleton instance was
250     // created.  We should only ever get here with a valid instance_ pointer.
251     Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
252     instance_ = 0;
253   }
254   static subtle::AtomicWord instance_;
255 };
256 
257 template <typename Type, typename Traits, typename DifferentiatingType>
258 subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0;
259 
260 }  // namespace base
261 
262 #endif  // BASE_MEMORY_SINGLETON_H_
263