• 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 #ifndef BASE_MEMORY_SINGLETON_H_
6 #define BASE_MEMORY_SINGLETON_H_
7 #pragma once
8 
9 #include "base/at_exit.h"
10 #include "base/atomicops.h"
11 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
12 #include "base/threading/platform_thread.h"
13 #include "base/threading/thread_restrictions.h"
14 
15 // Default traits for Singleton<Type>. Calls operator new and operator delete on
16 // the object. Registers automatic deletion at process exit.
17 // Overload if you need arguments or another memory allocation function.
18 template<typename Type>
19 struct DefaultSingletonTraits {
20   // Allocates the object.
NewDefaultSingletonTraits21   static Type* New() {
22     // The parenthesis is very important here; it forces POD type
23     // initialization.
24     return new Type();
25   }
26 
27   // Destroys the object.
DeleteDefaultSingletonTraits28   static void Delete(Type* x) {
29     delete x;
30   }
31 
32   // Set to true to automatically register deletion of the object on process
33   // exit. See below for the required call that makes this happen.
34   static const bool kRegisterAtExit = true;
35 
36   // Set to false to disallow access on a non-joinable thread.  This is
37   // different from kRegisterAtExit because StaticMemorySingletonTraits allows
38   // access on non-joinable threads, and gracefully handles this.
39   static const bool kAllowedToAccessOnNonjoinableThread = false;
40 };
41 
42 
43 // Alternate traits for use with the Singleton<Type>.  Identical to
44 // DefaultSingletonTraits except that the Singleton will not be cleaned up
45 // at exit.
46 template<typename Type>
47 struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
48   static const bool kRegisterAtExit = false;
49   static const bool kAllowedToAccessOnNonjoinableThread = true;
50 };
51 
52 
53 // Alternate traits for use with the Singleton<Type>.  Allocates memory
54 // for the singleton instance from a static buffer.  The singleton will
55 // be cleaned up at exit, but can't be revived after destruction unless
56 // the Resurrect() method is called.
57 //
58 // This is useful for a certain category of things, notably logging and
59 // tracing, where the singleton instance is of a type carefully constructed to
60 // be safe to access post-destruction.
61 // In logging and tracing you'll typically get stray calls at odd times, like
62 // during static destruction, thread teardown and the like, and there's a
63 // termination race on the heap-based singleton - e.g. if one thread calls
64 // get(), but then another thread initiates AtExit processing, the first thread
65 // may call into an object residing in unallocated memory. If the instance is
66 // allocated from the data segment, then this is survivable.
67 //
68 // The destructor is to deallocate system resources, in this case to unregister
69 // a callback the system will invoke when logging levels change. Note that
70 // this is also used in e.g. Chrome Frame, where you have to allow for the
71 // possibility of loading briefly into someone else's process space, and
72 // so leaking is not an option, as that would sabotage the state of your host
73 // process once you've unloaded.
74 template <typename Type>
75 struct StaticMemorySingletonTraits {
76   // WARNING: User has to deal with get() in the singleton class
77   // this is traits for returning NULL.
NewStaticMemorySingletonTraits78   static Type* New() {
79     if (base::subtle::NoBarrier_AtomicExchange(&dead_, 1))
80       return NULL;
81     Type* ptr = reinterpret_cast<Type*>(buffer_);
82 
83     // We are protected by a memory barrier.
84     new(ptr) Type();
85     return ptr;
86   }
87 
DeleteStaticMemorySingletonTraits88   static void Delete(Type* p) {
89     base::subtle::NoBarrier_Store(&dead_, 1);
90     base::subtle::MemoryBarrier();
91     if (p != NULL)
92       p->Type::~Type();
93   }
94 
95   static const bool kRegisterAtExit = true;
96   static const bool kAllowedToAccessOnNonjoinableThread = true;
97 
98   // Exposed for unittesting.
ResurrectStaticMemorySingletonTraits99   static void Resurrect() {
100     base::subtle::NoBarrier_Store(&dead_, 0);
101   }
102 
103  private:
104   static const size_t kBufferSize = (sizeof(Type) +
105                                      sizeof(intptr_t) - 1) / sizeof(intptr_t);
106   static intptr_t buffer_[kBufferSize];
107 
108   // Signal the object was already deleted, so it is not revived.
109   static base::subtle::Atomic32 dead_;
110 };
111 
112 template <typename Type> intptr_t
113     StaticMemorySingletonTraits<Type>::buffer_[kBufferSize];
114 template <typename Type> base::subtle::Atomic32
115     StaticMemorySingletonTraits<Type>::dead_ = 0;
116 
117 // The Singleton<Type, Traits, DifferentiatingType> class manages a single
118 // instance of Type which will be created on first use and will be destroyed at
119 // normal process exit). The Trait::Delete function will not be called on
120 // abnormal process exit.
121 //
122 // DifferentiatingType is used as a key to differentiate two different
123 // singletons having the same memory allocation functions but serving a
124 // different purpose. This is mainly used for Locks serving different purposes.
125 //
126 // Example usage:
127 //
128 // In your header:
129 //   #include "base/memory/singleton.h"
130 //   class FooClass {
131 //    public:
132 //     static FooClass* GetInstance();  <-- See comment below on this.
133 //     void Bar() { ... }
134 //    private:
135 //     FooClass() { ... }
136 //     friend struct DefaultSingletonTraits<FooClass>;
137 //
138 //     DISALLOW_COPY_AND_ASSIGN(FooClass);
139 //   };
140 //
141 // In your source file:
142 //  FooClass* FooClass::GetInstance() {
143 //    return Singleton<FooClass>::get();
144 //  }
145 //
146 // And to call methods on FooClass:
147 //   FooClass::GetInstance()->Bar();
148 //
149 // NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance
150 // and it is important that FooClass::GetInstance() is not inlined in the
151 // header. This makes sure that when source files from multiple targets include
152 // this header they don't end up with different copies of the inlined code
153 // creating multiple copies of the singleton.
154 //
155 // Singleton<> has no non-static members and doesn't need to actually be
156 // instantiated.
157 //
158 // This class is itself thread-safe. The underlying Type must of course be
159 // thread-safe if you want to use it concurrently. Two parameters may be tuned
160 // depending on the user's requirements.
161 //
162 // Glossary:
163 //   RAE = kRegisterAtExit
164 //
165 // On every platform, if Traits::RAE is true, the singleton will be destroyed at
166 // process exit. More precisely it uses base::AtExitManager which requires an
167 // object of this type to be instantiated. AtExitManager mimics the semantics
168 // of atexit() such as LIFO order but under Windows is safer to call. For more
169 // information see at_exit.h.
170 //
171 // If Traits::RAE is false, the singleton will not be freed at process exit,
172 // thus the singleton will be leaked if it is ever accessed. Traits::RAE
173 // shouldn't be false unless absolutely necessary. Remember that the heap where
174 // the object is allocated may be destroyed by the CRT anyway.
175 //
176 // Caveats:
177 // (a) Every call to get(), operator->() and operator*() incurs some overhead
178 //     (16ns on my P4/2.8GHz) to check whether the object has already been
179 //     initialized.  You may wish to cache the result of get(); it will not
180 //     change.
181 //
182 // (b) Your factory function must never throw an exception. This class is not
183 //     exception-safe.
184 //
185 template <typename Type,
186           typename Traits = DefaultSingletonTraits<Type>,
187           typename DifferentiatingType = Type>
188 class Singleton {
189  private:
190   // Classes using the Singleton<T> pattern should declare a GetInstance()
191   // method and call Singleton::get() from within that.
192   friend Type* Type::GetInstance();
193 
194   // This class is safe to be constructed and copy-constructed since it has no
195   // member.
196 
197   // Return a pointer to the one true instance of the class.
get()198   static Type* get() {
199     if (!Traits::kAllowedToAccessOnNonjoinableThread)
200       base::ThreadRestrictions::AssertSingletonAllowed();
201 
202     // Our AtomicWord doubles as a spinlock, where a value of
203     // kBeingCreatedMarker means the spinlock is being held for creation.
204     static const base::subtle::AtomicWord kBeingCreatedMarker = 1;
205 
206     base::subtle::AtomicWord value = base::subtle::NoBarrier_Load(&instance_);
207     if (value != 0 && value != kBeingCreatedMarker) {
208       // See the corresponding HAPPENS_BEFORE below.
209       ANNOTATE_HAPPENS_AFTER(&instance_);
210       return reinterpret_cast<Type*>(value);
211     }
212 
213     // Object isn't created yet, maybe we will get to create it, let's try...
214     if (base::subtle::Acquire_CompareAndSwap(&instance_,
215                                              0,
216                                              kBeingCreatedMarker) == 0) {
217       // instance_ was NULL and is now kBeingCreatedMarker.  Only one thread
218       // will ever get here.  Threads might be spinning on us, and they will
219       // stop right after we do this store.
220       Type* newval = Traits::New();
221 
222       // This annotation helps race detectors recognize correct lock-less
223       // synchronization between different threads calling get().
224       // See the corresponding HAPPENS_AFTER below and above.
225       ANNOTATE_HAPPENS_BEFORE(&instance_);
226       base::subtle::Release_Store(
227           &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval));
228 
229       if (newval != NULL && Traits::kRegisterAtExit)
230         base::AtExitManager::RegisterCallback(OnExit, NULL);
231 
232       return newval;
233     }
234 
235     // We hit a race.  Another thread beat us and either:
236     // - Has the object in BeingCreated state
237     // - Already has the object created...
238     // We know value != NULL.  It could be kBeingCreatedMarker, or a valid ptr.
239     // Unless your constructor can be very time consuming, it is very unlikely
240     // to hit this race.  When it does, we just spin and yield the thread until
241     // the object has been created.
242     while (true) {
243       value = base::subtle::NoBarrier_Load(&instance_);
244       if (value != kBeingCreatedMarker)
245         break;
246       base::PlatformThread::YieldCurrentThread();
247     }
248 
249     // See the corresponding HAPPENS_BEFORE above.
250     ANNOTATE_HAPPENS_AFTER(&instance_);
251     return reinterpret_cast<Type*>(value);
252   }
253 
254   // Adapter function for use with AtExit().  This should be called single
255   // threaded, so don't use atomic operations.
256   // Calling OnExit while singleton is in use by other threads is a mistake.
OnExit(void *)257   static void OnExit(void* /*unused*/) {
258     // AtExit should only ever be register after the singleton instance was
259     // created.  We should only ever get here with a valid instance_ pointer.
260     Traits::Delete(
261         reinterpret_cast<Type*>(base::subtle::NoBarrier_Load(&instance_)));
262     instance_ = 0;
263   }
264   static base::subtle::AtomicWord instance_;
265 };
266 
267 template <typename Type, typename Traits, typename DifferentiatingType>
268 base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::
269     instance_ = 0;
270 
271 #endif  // BASE_MEMORY_SINGLETON_H_
272