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