1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/sandbox/chromium/base/memory/singleton.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,285 @@ 1.4 +// Copyright (c) 2011 The Chromium Authors. All rights reserved. 1.5 +// Use of this source code is governed by a BSD-style license that can be 1.6 +// found in the LICENSE file. 1.7 + 1.8 +// PLEASE READ: Do you really need a singleton? 1.9 +// 1.10 +// Singletons make it hard to determine the lifetime of an object, which can 1.11 +// lead to buggy code and spurious crashes. 1.12 +// 1.13 +// Instead of adding another singleton into the mix, try to identify either: 1.14 +// a) An existing singleton that can manage your object's lifetime 1.15 +// b) Locations where you can deterministically create the object and pass 1.16 +// into other objects 1.17 +// 1.18 +// If you absolutely need a singleton, please keep them as trivial as possible 1.19 +// and ideally a leaf dependency. Singletons get problematic when they attempt 1.20 +// to do too much in their destructor or have circular dependencies. 1.21 + 1.22 +#ifndef BASE_MEMORY_SINGLETON_H_ 1.23 +#define BASE_MEMORY_SINGLETON_H_ 1.24 + 1.25 +#include "base/at_exit.h" 1.26 +#include "base/atomicops.h" 1.27 +#include "base/base_export.h" 1.28 +#include "base/memory/aligned_memory.h" 1.29 +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" 1.30 +#include "base/threading/thread_restrictions.h" 1.31 + 1.32 +namespace base { 1.33 +namespace internal { 1.34 + 1.35 +// Our AtomicWord doubles as a spinlock, where a value of 1.36 +// kBeingCreatedMarker means the spinlock is being held for creation. 1.37 +static const subtle::AtomicWord kBeingCreatedMarker = 1; 1.38 + 1.39 +// We pull out some of the functionality into a non-templated function, so that 1.40 +// we can implement the more complicated pieces out of line in the .cc file. 1.41 +BASE_EXPORT subtle::AtomicWord WaitForInstance(subtle::AtomicWord* instance); 1.42 + 1.43 +} // namespace internal 1.44 +} // namespace base 1.45 + 1.46 +// TODO(joth): Move more of this file into namespace base 1.47 + 1.48 +// Default traits for Singleton<Type>. Calls operator new and operator delete on 1.49 +// the object. Registers automatic deletion at process exit. 1.50 +// Overload if you need arguments or another memory allocation function. 1.51 +template<typename Type> 1.52 +struct DefaultSingletonTraits { 1.53 + // Allocates the object. 1.54 + static Type* New() { 1.55 + // The parenthesis is very important here; it forces POD type 1.56 + // initialization. 1.57 + return new Type(); 1.58 + } 1.59 + 1.60 + // Destroys the object. 1.61 + static void Delete(Type* x) { 1.62 + delete x; 1.63 + } 1.64 + 1.65 + // Set to true to automatically register deletion of the object on process 1.66 + // exit. See below for the required call that makes this happen. 1.67 + static const bool kRegisterAtExit = true; 1.68 + 1.69 + // Set to false to disallow access on a non-joinable thread. This is 1.70 + // different from kRegisterAtExit because StaticMemorySingletonTraits allows 1.71 + // access on non-joinable threads, and gracefully handles this. 1.72 + static const bool kAllowedToAccessOnNonjoinableThread = false; 1.73 +}; 1.74 + 1.75 + 1.76 +// Alternate traits for use with the Singleton<Type>. Identical to 1.77 +// DefaultSingletonTraits except that the Singleton will not be cleaned up 1.78 +// at exit. 1.79 +template<typename Type> 1.80 +struct LeakySingletonTraits : public DefaultSingletonTraits<Type> { 1.81 + static const bool kRegisterAtExit = false; 1.82 + static const bool kAllowedToAccessOnNonjoinableThread = true; 1.83 +}; 1.84 + 1.85 + 1.86 +// Alternate traits for use with the Singleton<Type>. Allocates memory 1.87 +// for the singleton instance from a static buffer. The singleton will 1.88 +// be cleaned up at exit, but can't be revived after destruction unless 1.89 +// the Resurrect() method is called. 1.90 +// 1.91 +// This is useful for a certain category of things, notably logging and 1.92 +// tracing, where the singleton instance is of a type carefully constructed to 1.93 +// be safe to access post-destruction. 1.94 +// In logging and tracing you'll typically get stray calls at odd times, like 1.95 +// during static destruction, thread teardown and the like, and there's a 1.96 +// termination race on the heap-based singleton - e.g. if one thread calls 1.97 +// get(), but then another thread initiates AtExit processing, the first thread 1.98 +// may call into an object residing in unallocated memory. If the instance is 1.99 +// allocated from the data segment, then this is survivable. 1.100 +// 1.101 +// The destructor is to deallocate system resources, in this case to unregister 1.102 +// a callback the system will invoke when logging levels change. Note that 1.103 +// this is also used in e.g. Chrome Frame, where you have to allow for the 1.104 +// possibility of loading briefly into someone else's process space, and 1.105 +// so leaking is not an option, as that would sabotage the state of your host 1.106 +// process once you've unloaded. 1.107 +template <typename Type> 1.108 +struct StaticMemorySingletonTraits { 1.109 + // WARNING: User has to deal with get() in the singleton class 1.110 + // this is traits for returning NULL. 1.111 + static Type* New() { 1.112 + // Only constructs once and returns pointer; otherwise returns NULL. 1.113 + if (base::subtle::NoBarrier_AtomicExchange(&dead_, 1)) 1.114 + return NULL; 1.115 + 1.116 + return new(buffer_.void_data()) Type(); 1.117 + } 1.118 + 1.119 + static void Delete(Type* p) { 1.120 + if (p != NULL) 1.121 + p->Type::~Type(); 1.122 + } 1.123 + 1.124 + static const bool kRegisterAtExit = true; 1.125 + static const bool kAllowedToAccessOnNonjoinableThread = true; 1.126 + 1.127 + // Exposed for unittesting. 1.128 + static void Resurrect() { 1.129 + base::subtle::NoBarrier_Store(&dead_, 0); 1.130 + } 1.131 + 1.132 + private: 1.133 + static base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_; 1.134 + // Signal the object was already deleted, so it is not revived. 1.135 + static base::subtle::Atomic32 dead_; 1.136 +}; 1.137 + 1.138 +template <typename Type> base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> 1.139 + StaticMemorySingletonTraits<Type>::buffer_; 1.140 +template <typename Type> base::subtle::Atomic32 1.141 + StaticMemorySingletonTraits<Type>::dead_ = 0; 1.142 + 1.143 +// The Singleton<Type, Traits, DifferentiatingType> class manages a single 1.144 +// instance of Type which will be created on first use and will be destroyed at 1.145 +// normal process exit). The Trait::Delete function will not be called on 1.146 +// abnormal process exit. 1.147 +// 1.148 +// DifferentiatingType is used as a key to differentiate two different 1.149 +// singletons having the same memory allocation functions but serving a 1.150 +// different purpose. This is mainly used for Locks serving different purposes. 1.151 +// 1.152 +// Example usage: 1.153 +// 1.154 +// In your header: 1.155 +// template <typename T> struct DefaultSingletonTraits; 1.156 +// class FooClass { 1.157 +// public: 1.158 +// static FooClass* GetInstance(); <-- See comment below on this. 1.159 +// void Bar() { ... } 1.160 +// private: 1.161 +// FooClass() { ... } 1.162 +// friend struct DefaultSingletonTraits<FooClass>; 1.163 +// 1.164 +// DISALLOW_COPY_AND_ASSIGN(FooClass); 1.165 +// }; 1.166 +// 1.167 +// In your source file: 1.168 +// #include "base/memory/singleton.h" 1.169 +// FooClass* FooClass::GetInstance() { 1.170 +// return Singleton<FooClass>::get(); 1.171 +// } 1.172 +// 1.173 +// And to call methods on FooClass: 1.174 +// FooClass::GetInstance()->Bar(); 1.175 +// 1.176 +// NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance 1.177 +// and it is important that FooClass::GetInstance() is not inlined in the 1.178 +// header. This makes sure that when source files from multiple targets include 1.179 +// this header they don't end up with different copies of the inlined code 1.180 +// creating multiple copies of the singleton. 1.181 +// 1.182 +// Singleton<> has no non-static members and doesn't need to actually be 1.183 +// instantiated. 1.184 +// 1.185 +// This class is itself thread-safe. The underlying Type must of course be 1.186 +// thread-safe if you want to use it concurrently. Two parameters may be tuned 1.187 +// depending on the user's requirements. 1.188 +// 1.189 +// Glossary: 1.190 +// RAE = kRegisterAtExit 1.191 +// 1.192 +// On every platform, if Traits::RAE is true, the singleton will be destroyed at 1.193 +// process exit. More precisely it uses base::AtExitManager which requires an 1.194 +// object of this type to be instantiated. AtExitManager mimics the semantics 1.195 +// of atexit() such as LIFO order but under Windows is safer to call. For more 1.196 +// information see at_exit.h. 1.197 +// 1.198 +// If Traits::RAE is false, the singleton will not be freed at process exit, 1.199 +// thus the singleton will be leaked if it is ever accessed. Traits::RAE 1.200 +// shouldn't be false unless absolutely necessary. Remember that the heap where 1.201 +// the object is allocated may be destroyed by the CRT anyway. 1.202 +// 1.203 +// Caveats: 1.204 +// (a) Every call to get(), operator->() and operator*() incurs some overhead 1.205 +// (16ns on my P4/2.8GHz) to check whether the object has already been 1.206 +// initialized. You may wish to cache the result of get(); it will not 1.207 +// change. 1.208 +// 1.209 +// (b) Your factory function must never throw an exception. This class is not 1.210 +// exception-safe. 1.211 +// 1.212 +template <typename Type, 1.213 + typename Traits = DefaultSingletonTraits<Type>, 1.214 + typename DifferentiatingType = Type> 1.215 +class Singleton { 1.216 + private: 1.217 + // Classes using the Singleton<T> pattern should declare a GetInstance() 1.218 + // method and call Singleton::get() from within that. 1.219 + friend Type* Type::GetInstance(); 1.220 + 1.221 + // Allow TraceLog tests to test tracing after OnExit. 1.222 + friend class DeleteTraceLogForTesting; 1.223 + 1.224 + // This class is safe to be constructed and copy-constructed since it has no 1.225 + // member. 1.226 + 1.227 + // Return a pointer to the one true instance of the class. 1.228 + static Type* get() { 1.229 +#ifndef NDEBUG 1.230 + // Avoid making TLS lookup on release builds. 1.231 + if (!Traits::kAllowedToAccessOnNonjoinableThread) 1.232 + base::ThreadRestrictions::AssertSingletonAllowed(); 1.233 +#endif 1.234 + 1.235 + base::subtle::AtomicWord value = base::subtle::NoBarrier_Load(&instance_); 1.236 + if (value != 0 && value != base::internal::kBeingCreatedMarker) { 1.237 + // See the corresponding HAPPENS_BEFORE below. 1.238 + ANNOTATE_HAPPENS_AFTER(&instance_); 1.239 + return reinterpret_cast<Type*>(value); 1.240 + } 1.241 + 1.242 + // Object isn't created yet, maybe we will get to create it, let's try... 1.243 + if (base::subtle::Acquire_CompareAndSwap( 1.244 + &instance_, 0, base::internal::kBeingCreatedMarker) == 0) { 1.245 + // instance_ was NULL and is now kBeingCreatedMarker. Only one thread 1.246 + // will ever get here. Threads might be spinning on us, and they will 1.247 + // stop right after we do this store. 1.248 + Type* newval = Traits::New(); 1.249 + 1.250 + // This annotation helps race detectors recognize correct lock-less 1.251 + // synchronization between different threads calling get(). 1.252 + // See the corresponding HAPPENS_AFTER below and above. 1.253 + ANNOTATE_HAPPENS_BEFORE(&instance_); 1.254 + base::subtle::Release_Store( 1.255 + &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval)); 1.256 + 1.257 + if (newval != NULL && Traits::kRegisterAtExit) 1.258 + base::AtExitManager::RegisterCallback(OnExit, NULL); 1.259 + 1.260 + return newval; 1.261 + } 1.262 + 1.263 + // We hit a race. Wait for the other thread to complete it. 1.264 + value = base::internal::WaitForInstance(&instance_); 1.265 + 1.266 + // See the corresponding HAPPENS_BEFORE above. 1.267 + ANNOTATE_HAPPENS_AFTER(&instance_); 1.268 + return reinterpret_cast<Type*>(value); 1.269 + } 1.270 + 1.271 + // Adapter function for use with AtExit(). This should be called single 1.272 + // threaded, so don't use atomic operations. 1.273 + // Calling OnExit while singleton is in use by other threads is a mistake. 1.274 + static void OnExit(void* /*unused*/) { 1.275 + // AtExit should only ever be register after the singleton instance was 1.276 + // created. We should only ever get here with a valid instance_ pointer. 1.277 + Traits::Delete( 1.278 + reinterpret_cast<Type*>(base::subtle::NoBarrier_Load(&instance_))); 1.279 + instance_ = 0; 1.280 + } 1.281 + static base::subtle::AtomicWord instance_; 1.282 +}; 1.283 + 1.284 +template <typename Type, typename Traits, typename DifferentiatingType> 1.285 +base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>:: 1.286 + instance_ = 0; 1.287 + 1.288 +#endif // BASE_MEMORY_SINGLETON_H_