diff options
56 files changed, 493 insertions, 335 deletions
diff --git a/base/i18n/number_formatting.cc b/base/i18n/number_formatting.cc index 7a69294..df6af14 100644 --- a/base/i18n/number_formatting.cc +++ b/base/i18n/number_formatting.cc @@ -6,7 +6,8 @@ #include "base/format_macros.h" #include "base/logging.h" -#include "base/singleton.h" +#include "base/lazy_instance.h" +#include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "unicode/numfmt.h" @@ -16,25 +17,26 @@ namespace base { namespace { -struct NumberFormatSingletonTraits - : public DefaultSingletonTraits<icu::NumberFormat> { - static icu::NumberFormat* New() { +struct NumberFormatWrapper { + NumberFormatWrapper() { + // There's no ICU call to destroy a NumberFormat object other than + // operator delete, so use the default Delete, which calls operator delete. + // This can cause problems if a different allocator is used by this file + // than by ICU. UErrorCode status = U_ZERO_ERROR; - icu::NumberFormat* formatter = icu::NumberFormat::createInstance(status); + number_format.reset(icu::NumberFormat::createInstance(status)); DCHECK(U_SUCCESS(status)); - return formatter; } - // There's no ICU call to destroy a NumberFormat object other than - // operator delete, so use the default Delete, which calls operator delete. - // This can cause problems if a different allocator is used by this file than - // by ICU. + + scoped_ptr<icu::NumberFormat> number_format; }; } // namespace +static LazyInstance<NumberFormatWrapper> g_number_format(LINKER_INITIALIZED); + string16 FormatNumber(int64 number) { - icu::NumberFormat* number_format = - Singleton<icu::NumberFormat, NumberFormatSingletonTraits>::get(); + icu::NumberFormat* number_format = g_number_format.Get().number_format.get(); if (!number_format) { // As a fallback, just return the raw number in a string. diff --git a/base/path_service.cc b/base/path_service.cc index 4381998..56ce5fa 100644 --- a/base/path_service.cc +++ b/base/path_service.cc @@ -13,9 +13,9 @@ #include "base/file_path.h" #include "base/file_util.h" #include "base/hash_tables.h" +#include "base/lazy_instance.h" #include "base/lock.h" #include "base/logging.h" -#include "base/singleton.h" namespace base { bool PathProvider(int key, FilePath* result); @@ -118,8 +118,10 @@ struct PathData { } }; +static base::LazyInstance<PathData> g_path_data(base::LINKER_INITIALIZED); + static PathData* GetPathData() { - return Singleton<PathData>::get(); + return g_path_data.Pointer(); } } // namespace diff --git a/base/singleton.h b/base/singleton.h index 8435c43..914f46c 100644 --- a/base/singleton.h +++ b/base/singleton.h @@ -114,6 +114,13 @@ template <typename Type> intptr_t template <typename Type> base::subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0; +// This is a hack to work around a limitation where a template argument cannot +// be declared as a friend directly. This is used in the below Singleton +// template. +template <typename T> +struct FriendMaker { + typedef T FriendType; +}; // The Singleton<Type, Traits, DifferentiatingType> class manages a single // instance of Type which will be created on first use and will be destroyed at @@ -124,15 +131,36 @@ template <typename Type> base::subtle::Atomic32 // singletons having the same memory allocation functions but serving a // different purpose. This is mainly used for Locks serving different purposes. // -// Example usages: (none are preferred, they all result in the same code) -// 1. FooClass* ptr = Singleton<FooClass>::get(); -// ptr->Bar(); -// 2. Singleton<FooClass>()->Bar(); -// 3. Singleton<FooClass>::get()->Bar(); +// Example usage: +// +// In your header: +// #include "base/singleton.h" +// class FooClass { +// public: +// static FooClass* GetInstance(); <-- See comment below on this. +// void Bar() { ... } +// private: +// FooClass() { ... } +// friend struct DefaultSingletonTraits<FooClass>; +// +// DISALLOW_COPY_AND_ASSIGN(FooClass); +// }; +// +// In your source file: +// FooClass* FooClass::GetInstance() { +// return Singleton<FooClass>::get(); +// } +// +// And to call methods on FooClass: +// FooClass::GetInstance()->Bar(); +// +// NOTE: It is important that FooClass::GetInstance() is not inlined in the +// header, so that when source files from multiple targets include this header +// they don't end up with different copies of the inlined code creating multiple +// copies of the singleton. // // Singleton<> has no non-static members and doesn't need to actually be -// instantiated. It does no harm to instantiate it and use it as a class member -// or at global level since it is acting as a POD type. +// instantiated. // // This class is itself thread-safe. The underlying Type must of course be // thread-safe if you want to use it concurrently. Two parameters may be tuned @@ -152,20 +180,6 @@ template <typename Type> base::subtle::Atomic32 // shouldn't be false unless absolutely necessary. Remember that the heap where // the object is allocated may be destroyed by the CRT anyway. // -// If you want to ensure that your class can only exist as a singleton, make -// its constructors private, and make DefaultSingletonTraits<> a friend: -// -// #include "base/singleton.h" -// class FooClass { -// public: -// void Bar() { ... } -// private: -// FooClass() { ... } -// friend struct DefaultSingletonTraits<FooClass>; -// -// DISALLOW_COPY_AND_ASSIGN(FooClass); -// }; -// // Caveats: // (a) Every call to get(), operator->() and operator*() incurs some overhead // (16ns on my P4/2.8GHz) to check whether the object has already been @@ -179,7 +193,13 @@ template <typename Type, typename Traits = DefaultSingletonTraits<Type>, typename DifferentiatingType = Type> class Singleton { - public: + private: +#if defined(OS_WIN) + friend typename FriendMaker<Type>::FriendType; +#else + friend class FriendMaker<Type>::FriendType; +#endif + // This class is safe to be constructed and copy-constructed since it has no // member. @@ -240,16 +260,6 @@ class Singleton { return reinterpret_cast<Type*>(value); } - // Shortcuts. - Type& operator*() { - return *get(); - } - - Type* operator->() { - return get(); - } - - private: // Adapter function for use with AtExit(). This should be called single // threaded, so don't use atomic operations. // Calling OnExit while singleton is in use by other threads is a mistake. diff --git a/base/singleton_unittest.cc b/base/singleton_unittest.cc index acb1247..288b89a 100644 --- a/base/singleton_unittest.cc +++ b/base/singleton_unittest.cc @@ -16,83 +16,127 @@ template<typename Type> struct LockTrait : public DefaultSingletonTraits<Type> { }; -struct Init5Trait : public DefaultSingletonTraits<int> { - static int* New() { - return new int(5); - } -}; - typedef void (*CallbackFunc)(); -struct CallbackTrait : public DefaultSingletonTraits<CallbackFunc> { - static void Delete(CallbackFunc* p) { - if (*p) - (*p)(); - DefaultSingletonTraits<CallbackFunc>::Delete(p); - } -}; +class IntSingleton { + public: + class DummyDifferentiatingClass { + }; + + struct Init5Trait : public DefaultSingletonTraits<IntSingleton> { + static IntSingleton* New() { + IntSingleton* instance = new IntSingleton(); + instance->value_ = 5; + return instance; + } + }; -struct StaticCallbackTrait : public StaticMemorySingletonTraits<CallbackFunc> { - static void Delete(CallbackFunc* p) { - if (*p) - (*p)(); - StaticMemorySingletonTraits<CallbackFunc>::Delete(p); + static IntSingleton* GetInstance() { + return Singleton<IntSingleton>::get(); + } + static IntSingleton* GetInstanceWithDefaultTraits() { + return Singleton<IntSingleton, + DefaultSingletonTraits<IntSingleton> >::get(); + } + static IntSingleton* GetInstanceWithDifferentiatingClass() { + return Singleton<IntSingleton, + DefaultSingletonTraits<IntSingleton>, + DummyDifferentiatingClass>::get(); + } + static IntSingleton* GetInstanceWithLockTrait() { + return Singleton<IntSingleton, LockTrait<IntSingleton> >::get(); + } + static IntSingleton* GetInstanceWithInit5Trait() { + return Singleton<IntSingleton, Init5Trait>::get(); } -}; - - -struct NoLeakTrait : public CallbackTrait { -}; -struct LeakTrait : public CallbackTrait { - static const bool kRegisterAtExit = false; + int value_; }; int* SingletonInt1() { - return Singleton<int>::get(); + return &IntSingleton::GetInstance()->value_; } int* SingletonInt2() { // Force to use a different singleton than SingletonInt1. - return Singleton<int, DefaultSingletonTraits<int> >::get(); + return &IntSingleton::GetInstanceWithDefaultTraits()->value_; } -class DummyDifferentiatingClass { -}; - int* SingletonInt3() { // Force to use a different singleton than SingletonInt1 and SingletonInt2. - // Note that any type can be used; int, float, std::wstring... - return Singleton<int, DefaultSingletonTraits<int>, - DummyDifferentiatingClass>::get(); + return &IntSingleton::GetInstanceWithDifferentiatingClass()->value_; } int* SingletonInt4() { - return Singleton<int, LockTrait<int> >::get(); + return &IntSingleton::GetInstanceWithLockTrait()->value_; } int* SingletonInt5() { - return Singleton<int, Init5Trait>::get(); + return &IntSingleton::GetInstanceWithInit5Trait()->value_; +} + +class CallbackSingleton { + public: + struct CallbackTrait : public DefaultSingletonTraits<CallbackSingleton> { + static void Delete(CallbackSingleton* instance) { + if (instance->callback_) + (instance->callback_)(); + DefaultSingletonTraits<CallbackSingleton>::Delete(instance); + } + }; + + struct NoLeakTrait : public CallbackTrait { + }; + + struct LeakTrait : public CallbackTrait { + static const bool kRegisterAtExit = false; + }; + + CallbackSingleton() : callback_(NULL) { + } + + static CallbackSingleton* GetInstanceWithNoLeakTrait() { + return Singleton<CallbackSingleton, NoLeakTrait>::get(); + } + static CallbackSingleton* GetInstanceWithLeakTrait() { + return Singleton<CallbackSingleton, LeakTrait>::get(); + } + static CallbackSingleton* GetInstanceWithStaticTrait(); + + CallbackFunc callback_; +}; + +struct StaticCallbackTrait + : public StaticMemorySingletonTraits<CallbackSingleton> { + static void Delete(CallbackSingleton* instance) { + if (instance->callback_) + (instance->callback_)(); + StaticMemorySingletonTraits<CallbackSingleton>::Delete(instance); + } +}; + +CallbackSingleton* CallbackSingleton::GetInstanceWithStaticTrait() { + return Singleton<CallbackSingleton, StaticCallbackTrait>::get(); } void SingletonNoLeak(CallbackFunc CallOnQuit) { - *Singleton<CallbackFunc, NoLeakTrait>::get() = CallOnQuit; + CallbackSingleton::GetInstanceWithNoLeakTrait()->callback_ = CallOnQuit; } void SingletonLeak(CallbackFunc CallOnQuit) { - *Singleton<CallbackFunc, LeakTrait>::get() = CallOnQuit; + CallbackSingleton::GetInstanceWithLeakTrait()->callback_ = CallOnQuit; } CallbackFunc* GetLeakySingleton() { - return Singleton<CallbackFunc, LeakTrait>::get(); + return &CallbackSingleton::GetInstanceWithLeakTrait()->callback_; } void SingletonStatic(CallbackFunc CallOnQuit) { - *Singleton<CallbackFunc, StaticCallbackTrait>::get() = CallOnQuit; + CallbackSingleton::GetInstanceWithStaticTrait()->callback_ = CallOnQuit; } CallbackFunc* GetStaticSingleton() { - return Singleton<CallbackFunc, StaticCallbackTrait>::get(); + return &CallbackSingleton::GetInstanceWithStaticTrait()->callback_; } } // namespace @@ -235,7 +279,7 @@ TEST_F(SingletonTest, Basic) { { // Resurrect the static singleton, and assert that it // still points to the same (static) memory. - StaticMemorySingletonTraits<CallbackFunc>::Resurrect(); + StaticMemorySingletonTraits<CallbackSingleton>::Resurrect(); EXPECT_EQ(GetStaticSingleton(), static_singleton); } } diff --git a/base/worker_pool_mac.mm b/base/worker_pool_mac.mm index bbc7892..956cfb4 100644 --- a/base/worker_pool_mac.mm +++ b/base/worker_pool_mac.mm @@ -4,11 +4,12 @@ #include "base/worker_pool_mac.h" +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/metrics/histogram.h" +#include "base/scoped_nsobject.h" #include "base/scoped_ptr.h" -#import "base/singleton_objc.h" #include "base/task.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/worker_pool_linux.h" @@ -34,6 +35,18 @@ std::vector<id> outstanding_ops_; // Outstanding operations at last check. size_t running_ = 0; // Operations in |Run()|. size_t outstanding_ = 0; // Operations posted but not completed. +// We use a wrapper struct here for the NSOperationQueue so that the object +// can be released when LazyInstance calls our destructor. +struct NSOperationQueueWrapper { + NSOperationQueueWrapper() { + operation_queue.reset([[NSOperationQueue alloc] init]); + } + scoped_nsobject<NSOperationQueue> operation_queue; +}; + +static base::LazyInstance<NSOperationQueueWrapper> g_nsoperation_queue( + base::LINKER_INITIALIZED); + } // namespace namespace worker_pool_mac { @@ -47,7 +60,7 @@ void SetUseLinuxWorkerPool(bool flag) { @implementation WorkerPoolObjC + (NSOperationQueue*)sharedOperationQueue { - return SingletonObjC<NSOperationQueue>::get(); + return g_nsoperation_queue.Get().operation_queue.get(); } @end // @implementation WorkerPoolObjC diff --git a/chrome/browser/chromeos/browser_main_chromeos.cc b/chrome/browser/chromeos/browser_main_chromeos.cc index df4653a..776a82b 100644 --- a/chrome/browser/chromeos/browser_main_chromeos.cc +++ b/chrome/browser/chromeos/browser_main_chromeos.cc @@ -4,8 +4,8 @@ #include "chrome/browser/chromeos/browser_main_chromeos.h" +#include "base/lazy_instance.h" #include "base/message_loop.h" -#include "base/singleton.h" #include <gtk/gtk.h> @@ -38,12 +38,13 @@ class MessageLoopObserver : public MessageLoopForUI::Observer { } }; -void BrowserMainPartsChromeos::PostMainMessageLoopStart() { - static Singleton<MessageLoopObserver> observer; +static base::LazyInstance<MessageLoopObserver> g_message_loop_observer( + base::LINKER_INITIALIZED); +void BrowserMainPartsChromeos::PostMainMessageLoopStart() { BrowserMainPartsPosix::PostMainMessageLoopStart(); MessageLoopForUI* message_loop = MessageLoopForUI::current(); - message_loop->AddObserver(observer.get()); + message_loop->AddObserver(g_message_loop_observer.Pointer()); } // static diff --git a/chrome/browser/chromeos/login/screen_locker.cc b/chrome/browser/chromeos/login/screen_locker.cc index f59307b..2167650 100644 --- a/chrome/browser/chromeos/login/screen_locker.cc +++ b/chrome/browser/chromeos/login/screen_locker.cc @@ -16,9 +16,9 @@ #include "app/resource_bundle.h" #include "app/x11_util.h" #include "base/command_line.h" +#include "base/lazy_instance.h" #include "base/metrics/histogram.h" #include "base/message_loop.h" -#include "base/singleton.h" #include "base/string_util.h" #include "base/timer.h" #include "base/utf_string_conversions.h" @@ -194,6 +194,9 @@ class ScreenLockObserver : public chromeos::ScreenLockLibrary::Observer, DISALLOW_COPY_AND_ASSIGN(ScreenLockObserver); }; +static base::LazyInstance<ScreenLockObserver> g_screen_lock_observer( + base::LINKER_INITIALIZED); + // A ScreenLock window that covers entire screen to keep the keyboard // focus/events inside the grab widget. class LockWindow : public views::WidgetGtk { @@ -901,7 +904,7 @@ void ScreenLocker::UnlockScreenFailed() { // static void ScreenLocker::InitClass() { - Singleton<ScreenLockObserver>::get(); + g_screen_lock_observer.Get(); } //////////////////////////////////////////////////////////////////////////////// diff --git a/chrome/browser/chromeos/login/signed_settings_helper.cc b/chrome/browser/chromeos/login/signed_settings_helper.cc index ad86e83..6a1a735 100644 --- a/chrome/browser/chromeos/login/signed_settings_helper.cc +++ b/chrome/browser/chromeos/login/signed_settings_helper.cc @@ -7,9 +7,9 @@ #include <string> #include <vector> +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/ref_counted.h" -#include "base/singleton.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/chromeos/login/signed_settings.h" @@ -262,10 +262,13 @@ class SignedSettingsHelperImpl : public SignedSettingsHelper, std::vector<OpContext*> pending_contexts_; - friend struct DefaultSingletonTraits<SignedSettingsHelperImpl>; + friend struct base::DefaultLazyInstanceTraits<SignedSettingsHelperImpl>; DISALLOW_COPY_AND_ASSIGN(SignedSettingsHelperImpl); }; +static base::LazyInstance<SignedSettingsHelperImpl> + g_signed_settings_helper_impl(base::LINKER_INITIALIZED); + SignedSettingsHelperImpl::SignedSettingsHelperImpl() { } @@ -371,7 +374,7 @@ void SignedSettingsHelperImpl::OnOpCompleted(OpContext* context) { } SignedSettingsHelper* SignedSettingsHelper::Get() { - return Singleton<SignedSettingsHelperImpl>::get(); + return g_signed_settings_helper_impl.Pointer(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/offline/offline_load_service.cc b/chrome/browser/chromeos/offline/offline_load_service.cc index 08f2362..ace85d8 100644 --- a/chrome/browser/chromeos/offline/offline_load_service.cc +++ b/chrome/browser/chromeos/offline/offline_load_service.cc @@ -4,8 +4,8 @@ #include "chrome/browser/chromeos/offline/offline_load_service.h" +#include "base/lazy_instance.h" #include "base/ref_counted.h" -#include "base/singleton.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/tab_contents.h" @@ -24,7 +24,7 @@ class OfflineLoadServiceSingleton { } private: - friend struct DefaultSingletonTraits<OfflineLoadServiceSingleton>; + friend struct base::DefaultLazyInstanceTraits<OfflineLoadServiceSingleton>; OfflineLoadServiceSingleton() : offline_load_service_(new chromeos::OfflineLoadService()) {} virtual ~OfflineLoadServiceSingleton() {} @@ -34,9 +34,12 @@ class OfflineLoadServiceSingleton { DISALLOW_COPY_AND_ASSIGN(OfflineLoadServiceSingleton); }; +static base::LazyInstance<OfflineLoadServiceSingleton> + g_offline_load_service_singleton(base::LINKER_INITIALIZED); + // static OfflineLoadService* OfflineLoadService::Get() { - return Singleton<OfflineLoadServiceSingleton>::get()->offline_load_service(); + return g_offline_load_service_singleton.Get().offline_load_service(); } void OfflineLoadService::Observe(NotificationType type, diff --git a/chrome/browser/enumerate_modules_model_win.cc b/chrome/browser/enumerate_modules_model_win.cc index b521b6c..cff39c6 100644 --- a/chrome/browser/enumerate_modules_model_win.cc +++ b/chrome/browser/enumerate_modules_model_win.cc @@ -672,6 +672,11 @@ string16 ModuleEnumerator::GetSubjectNameFromDigitalSignature( // ---------------------------------------------------------------------------- +// static +EnumerateModulesModel* EnumerateModulesModel::GetSingleton() { + return Singleton<EnumerateModulesModel>::get(); +} + void EnumerateModulesModel::ScanNow() { if (scanning_) return; // A scan is already in progress. diff --git a/chrome/browser/enumerate_modules_model_win.h b/chrome/browser/enumerate_modules_model_win.h index 9000a6c..15492a5 100644 --- a/chrome/browser/enumerate_modules_model_win.h +++ b/chrome/browser/enumerate_modules_model_win.h @@ -218,9 +218,7 @@ class ModuleEnumerator : public base::RefCountedThreadSafe<ModuleEnumerator> { // notification. class EnumerateModulesModel { public: - static EnumerateModulesModel* GetSingleton() { - return Singleton<EnumerateModulesModel>::get(); - } + static EnumerateModulesModel* GetSingleton(); // Returns the number of suspected bad modules found in the last scan. // Returns 0 if no scan has taken place yet. diff --git a/chrome/browser/gtk/browser_toolbar_gtk.cc b/chrome/browser/gtk/browser_toolbar_gtk.cc index ad10e51..d3dffff 100644 --- a/chrome/browser/gtk/browser_toolbar_gtk.cc +++ b/chrome/browser/gtk/browser_toolbar_gtk.cc @@ -626,7 +626,7 @@ bool BrowserToolbarGtk::ShouldOnlyShowLocation() const { gboolean BrowserToolbarGtk::OnWrenchMenuButtonExpose(GtkWidget* sender, GdkEventExpose* expose) { - if (!Singleton<UpgradeDetector>::get()->notify_upgrade()) + if (!UpgradeDetector::GetInstance()->notify_upgrade()) return FALSE; const SkBitmap& badge = diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc index 7ec0303..2bc0a49 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page.cc @@ -76,6 +76,9 @@ static const char* const kTakeMeBackCommand = "takeMeBack"; // static SafeBrowsingBlockingPageFactory* SafeBrowsingBlockingPage::factory_ = NULL; +static base::LazyInstance<SafeBrowsingBlockingPage::UnsafeResourceMap> + g_unsafe_resource_map(base::LINKER_INITIALIZED); + // The default SafeBrowsingBlockingPageFactory. Global, made a singleton so we // don't leak it. class SafeBrowsingBlockingPageFactoryImpl @@ -559,7 +562,7 @@ void SafeBrowsingBlockingPage::NotifySafeBrowsingService( // static SafeBrowsingBlockingPage::UnsafeResourceMap* SafeBrowsingBlockingPage::GetUnsafeResourcesMap() { - return Singleton<UnsafeResourceMap>::get(); + return g_unsafe_resource_map.Pointer(); } // static diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page.h b/chrome/browser/safe_browsing/safe_browsing_blocking_page.h index 53b21a0..cfe2358 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page.h +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page.h @@ -44,6 +44,9 @@ class TabContents; class SafeBrowsingBlockingPage : public InterstitialPage { public: + typedef std::vector<SafeBrowsingService::UnsafeResource> UnsafeResourceList; + typedef std::map<TabContents*, UnsafeResourceList> UnsafeResourceMap; + virtual ~SafeBrowsingBlockingPage(); // Shows a blocking page warning the user about phishing/malware for a @@ -66,8 +69,6 @@ class SafeBrowsingBlockingPage : public InterstitialPage { virtual void Proceed(); virtual void DontProceed(); - typedef std::vector<SafeBrowsingService::UnsafeResource> UnsafeResourceList; - protected: friend class SafeBrowsingBlockingPageTest; @@ -118,7 +119,6 @@ class SafeBrowsingBlockingPage : public InterstitialPage { // A list of SafeBrowsingService::UnsafeResource for a tab that the user // should be warned about. They are queued when displaying more than one // interstitial at a time. - typedef std::map<TabContents*, UnsafeResourceList> UnsafeResourceMap; static UnsafeResourceMap* GetUnsafeResourcesMap(); // Notifies the SafeBrowsingService on the IO thread whether to proceed or not diff --git a/chrome/common/sqlite_utils.cc b/chrome/common/sqlite_utils.cc index d11b925..9d16c7f 100644 --- a/chrome/common/sqlite_utils.cc +++ b/chrome/common/sqlite_utils.cc @@ -8,8 +8,8 @@ #include "base/file_path.h" #include "base/lock.h" +#include "base/lazy_instance.h" #include "base/logging.h" -#include "base/singleton.h" #include "base/stl_util-inl.h" #include "base/string16.h" @@ -76,10 +76,13 @@ class DefaultSQLErrorHandlerFactory : public SQLErrorHandlerFactory { Lock lock_; }; +static base::LazyInstance<DefaultSQLErrorHandlerFactory> + g_default_sql_error_handler_factory(base::LINKER_INITIALIZED); + SQLErrorHandlerFactory* GetErrorHandlerFactory() { // TODO(cpu): Testing needs to override the error handler. // Destruction of DefaultSQLErrorHandlerFactory handled by at_exit manager. - return Singleton<DefaultSQLErrorHandlerFactory>::get(); + return g_default_sql_error_handler_factory.Pointer(); } namespace sqlite_utils { diff --git a/chrome/common/time_format.cc b/chrome/common/time_format.cc index c62f4f5..9de3a402 100644 --- a/chrome/common/time_format.cc +++ b/chrome/common/time_format.cc @@ -7,9 +7,9 @@ #include <vector> #include "app/l10n_util.h" +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/scoped_ptr.h" -#include "base/singleton.h" #include "base/stl_util-inl.h" #include "base/string16.h" #include "base/time.h" @@ -168,8 +168,7 @@ class TimeFormatter { STLDeleteContainerPointers(time_elapsed_formatter_.begin(), time_elapsed_formatter_.end()); } - friend class Singleton<TimeFormatter>; - friend struct DefaultSingletonTraits<TimeFormatter>; + friend struct base::DefaultLazyInstanceTraits<TimeFormatter>; std::vector<icu::PluralFormat*> short_formatter_; std::vector<icu::PluralFormat*> time_left_formatter_; @@ -182,6 +181,9 @@ class TimeFormatter { DISALLOW_COPY_AND_ASSIGN(TimeFormatter); }; +static base::LazyInstance<TimeFormatter> g_time_formatter( + base::LINKER_INITIALIZED); + void TimeFormatter::BuildFormats( FormatType format_type, std::vector<icu::PluralFormat*>* time_formats) { static const icu::UnicodeString kKeywords[] = { @@ -253,8 +255,6 @@ icu::PluralFormat* TimeFormatter::createFallbackFormat( return format; } -Singleton<TimeFormatter> time_formatter; - static string16 FormatTimeImpl(const TimeDelta& delta, FormatType format_type) { if (delta.ToInternalValue() < 0) { NOTREACHED() << "Negative duration"; @@ -264,7 +264,7 @@ static string16 FormatTimeImpl(const TimeDelta& delta, FormatType format_type) { int number; const std::vector<icu::PluralFormat*>& formatters = - time_formatter->formatter(format_type); + g_time_formatter.Get().formatter(format_type); UErrorCode error = U_ZERO_ERROR; icu::UnicodeString time_string; diff --git a/chrome/plugin/webplugin_proxy.cc b/chrome/plugin/webplugin_proxy.cc index 87a4772..bb77108 100644 --- a/chrome/plugin/webplugin_proxy.cc +++ b/chrome/plugin/webplugin_proxy.cc @@ -9,13 +9,13 @@ #if defined(OS_WIN) #include "app/win_util.h" #endif +#include "base/lazy_instance.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #include "base/mac/scoped_cftyperef.h" #endif #include "base/scoped_handle.h" #include "base/shared_memory.h" -#include "base/singleton.h" #include "build/build_config.h" #include "chrome/common/child_process_logging.h" #include "chrome/common/plugin_messages.h" @@ -47,9 +47,7 @@ using webkit_glue::WebPluginAcceleratedSurface; #endif typedef std::map<CPBrowsingContext, WebPluginProxy*> ContextMap; -static ContextMap& GetContextMap() { - return *Singleton<ContextMap>::get(); -} +static base::LazyInstance<ContextMap> g_context_map(base::LINKER_INITIALIZED); WebPluginProxy::WebPluginProxy( PluginChannel* channel, @@ -93,7 +91,7 @@ WebPluginProxy::WebPluginProxy( WebPluginProxy::~WebPluginProxy() { if (cp_browsing_context_) - GetContextMap().erase(cp_browsing_context_); + g_context_map.Get().erase(cp_browsing_context_); #if defined(USE_X11) if (windowless_shm_pixmap_ != None) @@ -271,14 +269,14 @@ CPBrowsingContext WebPluginProxy::GetCPBrowsingContext() { if (cp_browsing_context_ == 0) { Send(new PluginHostMsg_GetCPBrowsingContext(route_id_, &cp_browsing_context_)); - GetContextMap()[cp_browsing_context_] = this; + g_context_map.Get()[cp_browsing_context_] = this; } return cp_browsing_context_; } WebPluginProxy* WebPluginProxy::FromCPBrowsingContext( CPBrowsingContext context) { - return GetContextMap()[context]; + return g_context_map.Get()[context]; } WebPluginResourceClient* WebPluginProxy::GetResourceClient(int id) { diff --git a/chrome/renderer/extensions/bindings_utils.cc b/chrome/renderer/extensions/bindings_utils.cc index 5b213c4..4776966 100644 --- a/chrome/renderer/extensions/bindings_utils.cc +++ b/chrome/renderer/extensions/bindings_utils.cc @@ -4,6 +4,7 @@ #include "chrome/renderer/extensions/bindings_utils.h" +#include "base/lazy_instance.h" #include "base/string_split.h" #include "base/string_util.h" #include "chrome/renderer/render_view.h" @@ -21,11 +22,14 @@ struct SingletonData { ContextList contexts; PendingRequestMap pending_requests; }; +static base::LazyInstance<SingletonData> g_singleton_data( + base::LINKER_INITIALIZED); typedef std::map<int, std::string> StringMap; +static base::LazyInstance<StringMap> g_string_map(base::LINKER_INITIALIZED); const char* GetStringResource(int resource_id) { - StringMap* strings = Singleton<StringMap>::get(); + StringMap* strings = g_string_map.Pointer(); StringMap::iterator it = strings->find(resource_id); if (it == strings->end()) { it = strings->insert(std::make_pair( @@ -84,7 +88,7 @@ ContextInfo::ContextInfo(v8::Persistent<v8::Context> context, ContextInfo::~ContextInfo() {} ContextList& GetContexts() { - return Singleton<SingletonData>::get()->contexts; + return g_singleton_data.Get().contexts; } ContextList GetContextsForExtension(const std::string& extension_id) { @@ -134,7 +138,7 @@ ContextList::iterator FindContext(v8::Handle<v8::Context> context) { } PendingRequestMap& GetPendingRequestMap() { - return Singleton<SingletonData>::get()->pending_requests; + return g_singleton_data.Get().pending_requests; } RenderView* GetRenderViewForCurrentContext() { diff --git a/chrome/renderer/extensions/renderer_extension_bindings.cc b/chrome/renderer/extensions/renderer_extension_bindings.cc index 9555672..ab7a8eb 100644 --- a/chrome/renderer/extensions/renderer_extension_bindings.cc +++ b/chrome/renderer/extensions/renderer_extension_bindings.cc @@ -8,7 +8,7 @@ #include <string> #include "base/basictypes.h" -#include "base/singleton.h" +#include "base/lazy_instance.h" #include "base/values.h" #include "chrome/common/extensions/extension_message_bundle.h" #include "chrome/common/render_messages.h" @@ -43,17 +43,20 @@ struct ExtensionData { std::map<int, PortData> ports; // port ID -> data }; +static base::LazyInstance<ExtensionData> g_extension_data( + base::LINKER_INITIALIZED); + static bool HasPortData(int port_id) { - return Singleton<ExtensionData>::get()->ports.find(port_id) != - Singleton<ExtensionData>::get()->ports.end(); + return g_extension_data.Get().ports.find(port_id) != + g_extension_data.Get().ports.end(); } static ExtensionData::PortData& GetPortData(int port_id) { - return Singleton<ExtensionData>::get()->ports[port_id]; + return g_extension_data.Get().ports[port_id]; } static void ClearPortData(int port_id) { - Singleton<ExtensionData>::get()->ports.erase(port_id); + g_extension_data.Get().ports.erase(port_id); } const char kPortClosedError[] = "Attempting to use a disconnected port object"; diff --git a/chrome/renderer/ggl/ggl.cc b/chrome/renderer/ggl/ggl.cc index 577e853..c95bbb5 100644 --- a/chrome/renderer/ggl/ggl.cc +++ b/chrome/renderer/ggl/ggl.cc @@ -4,8 +4,8 @@ #include "build/build_config.h" +#include "base/lazy_instance.h" #include "base/ref_counted.h" -#include "base/singleton.h" #include "base/weak_ptr.h" #include "chrome/renderer/command_buffer_proxy.h" #include "chrome/renderer/ggl/ggl.h" @@ -48,6 +48,10 @@ class GLES2Initializer { private: DISALLOW_COPY_AND_ASSIGN(GLES2Initializer); }; + +static base::LazyInstance<GLES2Initializer> g_gles2_initializer( + base::LINKER_INITIALIZED); + } // namespace anonymous // Manages a GL context. @@ -163,7 +167,7 @@ bool Context::Initialize(gfx::NativeViewId view, return false; // Ensure the gles2 library is initialized first in a thread safe way. - Singleton<GLES2Initializer>::get(); + g_gles2_initializer.Get(); // Allocate a frame buffer ID with respect to the parent. if (parent_.get()) { diff --git a/chrome/renderer/render_view.cc b/chrome/renderer/render_view.cc index e29e30a..ca29c0a 100644 --- a/chrome/renderer/render_view.cc +++ b/chrome/renderer/render_view.cc @@ -15,10 +15,10 @@ #include "base/callback.h" #include "base/command_line.h" #include "base/compiler_specific.h" +#include "base/lazy_instance.h" #include "base/metrics/histogram.h" #include "base/path_service.h" #include "base/process_util.h" -#include "base/singleton.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" @@ -277,6 +277,7 @@ using webkit_glue::WebAccessibility; //----------------------------------------------------------------------------- typedef std::map<WebKit::WebView*, RenderView*> ViewMap; +static base::LazyInstance<ViewMap> g_view_map(base::LINKER_INITIALIZED); // define to write the time necessary for thumbnail/DOM text retrieval, // respectively, into the system debug log @@ -615,7 +616,7 @@ RenderView::~RenderView() { #ifndef NDEBUG // Make sure we are no longer referenced by the ViewMap. - ViewMap* views = Singleton<ViewMap>::get(); + ViewMap* views = g_view_map.Pointer(); for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) DCHECK_NE(this, it->second) << "Failed to call Close?"; #endif @@ -623,7 +624,7 @@ RenderView::~RenderView() { /*static*/ void RenderView::ForEach(RenderViewVisitor* visitor) { - ViewMap* views = Singleton<ViewMap>::get(); + ViewMap* views = g_view_map.Pointer(); for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) { if (!visitor->Visit(it->second)) return; @@ -632,7 +633,7 @@ void RenderView::ForEach(RenderViewVisitor* visitor) { /*static*/ RenderView* RenderView::FromWebView(WebView* webview) { - ViewMap* views = Singleton<ViewMap>::get(); + ViewMap* views = g_view_map.Pointer(); ViewMap::iterator it = views->find(webview); return it == views->end() ? NULL : it->second; } @@ -895,7 +896,7 @@ void RenderView::Init(gfx::NativeViewId parent_hwnd, devtools_agent_.reset(new DevToolsAgent(routing_id, this)); webwidget_ = WebView::create(this, devtools_agent_.get()); - Singleton<ViewMap>::get()->insert(std::make_pair(webview(), this)); + g_view_map.Get().insert(std::make_pair(webview(), this)); webkit_preferences_.Apply(webview()); webview()->initializeMainFrame(this); if (!frame_name.empty()) @@ -5447,7 +5448,7 @@ void RenderView::Close() { // We need to grab a pointer to the doomed WebView before we destroy it. WebView* doomed = webview(); RenderWidget::Close(); - Singleton<ViewMap>::get()->erase(doomed); + g_view_map.Get().erase(doomed); } void RenderView::DidHandleKeyEvent() { diff --git a/chrome_frame/chrome_frame_automation.cc b/chrome_frame/chrome_frame_automation.cc index b670548..ab13151 100644 --- a/chrome_frame/chrome_frame_automation.cc +++ b/chrome_frame/chrome_frame_automation.cc @@ -11,11 +11,11 @@ #include "base/debug/trace_event.h" #include "base/file_util.h" #include "base/file_version_info.h" +#include "base/lazy_instance.h" #include "base/lock.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process_util.h" -#include "base/singleton.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/utf_string_conversions.h" @@ -569,7 +569,9 @@ bool ProxyFactory::ReleaseAutomationServer(void* server_id, return true; } -Singleton<ProxyFactory, LeakySingletonTraits<ProxyFactory> > g_proxy_factory; +static base::LazyInstance<ProxyFactory, + base::LeakyLazyInstanceTraits<ProxyFactory> > + g_proxy_factory(base::LINKER_INITIALIZED); template <> struct RunnableMethodTraits<ChromeFrameAutomationClient> { static void RetainCallee(ChromeFrameAutomationClient* obj) {} @@ -586,7 +588,7 @@ ChromeFrameAutomationClient::ChromeFrameAutomationClient() ui_thread_id_(NULL), init_state_(UNINITIALIZED), use_chrome_network_(false), - proxy_factory_(g_proxy_factory.get()), + proxy_factory_(g_proxy_factory.Pointer()), handle_top_level_requests_(false), tab_handle_(-1), session_id_(-1), diff --git a/chrome_frame/external_tab.cc b/chrome_frame/external_tab.cc index ca402d9..0d2609f 100644 --- a/chrome_frame/external_tab.cc +++ b/chrome_frame/external_tab.cc @@ -3,7 +3,7 @@ // found in the LICENSE file. #include "chrome_frame/external_tab.h" -#include "base/singleton.h" +#include "base/lazy_instance.h" #include "base/tracked.h" #include "base/task.h" #include "base/waitable_event.h" @@ -14,7 +14,8 @@ DISABLE_RUNNABLE_METHOD_REFCOUNT(ExternalTabProxy); DISABLE_RUNNABLE_METHOD_REFCOUNT(UIDelegate); namespace { - Singleton<ChromeProxyFactory> g_proxy_factory; + static base::LazyInstance<ChromeProxyFactory> g_proxy_factory( + base::LINKER_INITIALIZED); struct UserDataHolder : public SyncMessageContext { explicit UserDataHolder(void* p) : data(p) {} @@ -24,7 +25,7 @@ namespace { ExternalTabProxy::ExternalTabProxy() : state_(NONE), tab_(0), tab_wnd_(NULL), - chrome_wnd_(NULL), proxy_factory_(g_proxy_factory.get()), proxy_(NULL), + chrome_wnd_(NULL), proxy_factory_(g_proxy_factory.Pointer()), proxy_(NULL), ui_delegate_(NULL) { } diff --git a/gfx/window_impl.cc b/gfx/window_impl.cc index 95561ff..b85f2f2 100644 --- a/gfx/window_impl.cc +++ b/gfx/window_impl.cc @@ -222,7 +222,7 @@ std::wstring WindowImpl::GetWindowClassName() { ATOM atom = RegisterClassEx(&class_ex); DCHECK(atom); - Singleton<ClassRegistrar>()->RegisterClass(class_info, name, atom); + ClassRegistrar::GetInstance()->RegisterClass(class_info, name, atom); return name; } diff --git a/media/tools/player_wtl/mainfrm.h b/media/tools/player_wtl/mainfrm.h index f92a97d..6c73957 100644 --- a/media/tools/player_wtl/mainfrm.h +++ b/media/tools/player_wtl/mainfrm.h @@ -61,10 +61,10 @@ class CMainFrame : public CFrameWindowImpl<CMainFrame>, virtual BOOL OnIdle() { BOOL bEnable = !m_view.bmp_.IsNull(); - BOOL bMovieOpen = media::Movie::get()->IsOpen() ? true : false; + BOOL bMovieOpen = media::Movie::GetInstance()->IsOpen() ? true : false; - float current_position = media::Movie::get()->GetPosition(); - float duration = media::Movie::get()->GetDuration(); + float current_position = media::Movie::GetInstance()->GetPosition(); + float duration = media::Movie::GetInstance()->GetDuration(); if (enable_exit && bEnable && duration > 0.0f && current_position >= duration) { OnFileExit(0, 0, 0); @@ -304,8 +304,8 @@ class CMainFrame : public CFrameWindowImpl<CMainFrame>, } void UpdateSpeedUICheck() { - if (media::Movie::get()) { - float play_rate = media::Movie::get()->GetPlayRate(); + if (media::Movie::GetInstance()) { + float play_rate = media::Movie::GetInstance()->GetPlayRate(); UISetCheck(ID_PLAY_HALFSPEED, (play_rate == 0.5f)); UISetCheck(ID_PLAY_NORMALSPEED, (play_rate == 1.0f)); UISetCheck(ID_PLAY_DOUBLESPEED, (play_rate == 2.0f)); @@ -422,10 +422,10 @@ class CMainFrame : public CFrameWindowImpl<CMainFrame>, TogglePrintPreview(); // If a movie is open, close it. - media::Movie::get()->Close(); + media::Movie::GetInstance()->Close(); if (IsMovie(file_name)) { - success = media::Movie::get()->Open(file_name, m_view.renderer_); + success = media::Movie::GetInstance()->Open(file_name, m_view.renderer_); } else { HBITMAP hbmp = NULL; hbmp = (HBITMAP)::LoadImage(NULL, file_name, IMAGE_BITMAP, 0, 0, @@ -590,7 +590,7 @@ class CMainFrame : public CFrameWindowImpl<CMainFrame>, if (m_bPrintPreview) TogglePrintPreview(); - media::Movie::get()->Close(); + media::Movie::GetInstance()->Close(); m_view.Reset(); UpdateTitleBar(NULL); m_szFilePath[0] = 0; @@ -643,44 +643,44 @@ class CMainFrame : public CFrameWindowImpl<CMainFrame>, } void OnPlayPlayPause(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - bool paused = !media::Movie::get()->GetPause(); - media::Movie::get()->SetPause(paused); + bool paused = !media::Movie::GetInstance()->GetPause(); + media::Movie::GetInstance()->SetPause(paused); } void OnPlayStepForward(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - float current_position = media::Movie::get()->GetPosition(); - media::Movie::get()->SetPosition(current_position + 10.0f); + float current_position = media::Movie::GetInstance()->GetPosition(); + media::Movie::GetInstance()->SetPosition(current_position + 10.0f); } void OnPlayStepBackward(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - float current_position = media::Movie::get()->GetPosition(); - media::Movie::get()->SetPosition(current_position - 10.0f); + float current_position = media::Movie::GetInstance()->GetPosition(); + media::Movie::GetInstance()->SetPosition(current_position - 10.0f); } void OnPlayGotoStart(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - media::Movie::get()->SetPosition(0.0); + media::Movie::GetInstance()->SetPosition(0.0); } void OnPlayGotoEnd(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - float current_position = media::Movie::get()->GetDuration(); - media::Movie::get()->SetPosition(current_position - 30.0f); + float current_position = media::Movie::GetInstance()->GetDuration(); + media::Movie::GetInstance()->SetPosition(current_position - 30.0f); } void SetPlayRate(int play_speed) { if (play_speed == 0) { - media::Movie::get()->Play(0.5f); + media::Movie::GetInstance()->Play(0.5f); } else if (play_speed == 2) { - media::Movie::get()->Play(2.0f); + media::Movie::GetInstance()->Play(2.0f); } else if (play_speed == 3) { - media::Movie::get()->Play(3.0f); + media::Movie::GetInstance()->Play(3.0f); } else if (play_speed == 4) { - media::Movie::get()->Play(4.0f); + media::Movie::GetInstance()->Play(4.0f); } else if (play_speed == 5) { - media::Movie::get()->Play(8.0f); + media::Movie::GetInstance()->Play(8.0f); } else if (play_speed == 6) { - media::Movie::get()->Play(16.0f); + media::Movie::GetInstance()->Play(16.0f); } else { - media::Movie::get()->Play(1.0f); + media::Movie::GetInstance()->Play(1.0f); } } @@ -699,22 +699,23 @@ class CMainFrame : public CFrameWindowImpl<CMainFrame>, } void OnOptionsDraw(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - bool enable_draw = !media::Movie::get()->GetDrawEnable(); - media::Movie::get()->SetDrawEnable(enable_draw); + bool enable_draw = !media::Movie::GetInstance()->GetDrawEnable(); + media::Movie::GetInstance()->SetDrawEnable(enable_draw); UISetCheck(ID_OPTIONS_DRAW, enable_draw); UpdateLayout(); } void OnOptionsAudio(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wnd*/) { - bool enable_audio = !media::Movie::get()->GetAudioEnable(); - media::Movie::get()->SetAudioEnable(enable_audio); + bool enable_audio = !media::Movie::GetInstance()->GetAudioEnable(); + media::Movie::GetInstance()->SetAudioEnable(enable_audio); UISetCheck(ID_OPTIONS_AUDIO, enable_audio); UpdateLayout(); } void OnOptionsDumpYUVFile(UINT /*uNotify*/, int /*nID*/, CWindow /*wnd*/) { - bool enable_dump_yuv_file = !media::Movie::get()->GetDumpYuvFileEnable(); - media::Movie::get()->SetDumpYuvFileEnable(enable_dump_yuv_file); + bool enable_dump_yuv_file = + !media::Movie::GetInstance()->GetDumpYuvFileEnable(); + media::Movie::GetInstance()->SetDumpYuvFileEnable(enable_dump_yuv_file); UISetCheck(ID_OPTIONS_DUMPYUVFILE, enable_dump_yuv_file); UpdateLayout(); } diff --git a/media/tools/player_wtl/movie.cc b/media/tools/player_wtl/movie.cc index 70ede51..7a06cb9 100644 --- a/media/tools/player_wtl/movie.cc +++ b/media/tools/player_wtl/movie.cc @@ -4,6 +4,7 @@ #include "media/tools/player_wtl/movie.h" +#include "base/singleton.h" #include "base/utf_string_conversions.h" #include "media/base/filter_collection.h" #include "media/base/pipeline_impl.h" @@ -39,6 +40,10 @@ Movie::Movie() Movie::~Movie() { } +Movie* Movie::GetInstance() { + return Singleton<Movie>::get(); +} + bool Movie::IsOpen() { return pipeline_ != NULL; } diff --git a/media/tools/player_wtl/movie.h b/media/tools/player_wtl/movie.h index e505165..581a0db 100644 --- a/media/tools/player_wtl/movie.h +++ b/media/tools/player_wtl/movie.h @@ -11,17 +11,20 @@ #include "base/ref_counted.h" #include "base/scoped_ptr.h" -#include "base/singleton.h" #include "base/thread.h" +template <typename T> struct DefaultSingletonTraits; class WtlVideoRenderer; namespace media { class PipelineImpl; -class Movie : public Singleton<Movie> { +class Movie { public: + // Returns the singleton instance. + static Movie* GetInstance(); + // Open a movie. bool Open(const wchar_t* url, WtlVideoRenderer* video_renderer); diff --git a/media/tools/player_wtl/player_wtl.cc b/media/tools/player_wtl/player_wtl.cc index 8fe9f1b..b1dbabc 100644 --- a/media/tools/player_wtl/player_wtl.cc +++ b/media/tools/player_wtl/player_wtl.cc @@ -55,7 +55,7 @@ int Run(wchar_t* win_cmd_line, int cmd_show) { int result = the_loop.Run(); - media::Movie::get()->Close(); + media::Movie::GetInstance()->Close(); g_module.RemoveMessageLoop(); return result; diff --git a/media/tools/player_wtl/props.h b/media/tools/player_wtl/props.h index 65224e5..d2b7dbb 100644 --- a/media/tools/player_wtl/props.h +++ b/media/tools/player_wtl/props.h @@ -124,7 +124,7 @@ class CPageOne : public CPropertyPageImpl<CPageOne> { SetDlgItemText(IDC_FILESIZE, szBuff); // TODO(fbarchard): We need a pipeline property for frame rate. - float duration = media::Movie::get()->GetDuration(); + float duration = media::Movie::GetInstance()->GetDuration(); float fps = 29.97f; wsprintf(szBuff, L"%i.%2i Seconds, %i Frames", static_cast<int>(duration), diff --git a/media/tools/player_wtl/seek.h b/media/tools/player_wtl/seek.h index 84f3c95..d5cf464 100644 --- a/media/tools/player_wtl/seek.h +++ b/media/tools/player_wtl/seek.h @@ -34,12 +34,12 @@ class CSeek : public CSimpleDialog<IDD_SEEK>, BOOL& bHandled) { static float previous_position = -1.0f; - float position = media::Movie::get()->GetPosition(); + float position = media::Movie::GetInstance()->GetPosition(); if (static_cast<int>(position * 10) != static_cast<int>(previous_position * 10)) { previous_position = position; wchar_t szBuff[200]; - float duration = media::Movie::get()->GetDuration(); + float duration = media::Movie::GetInstance()->GetDuration(); float fps = 29.97f; wsprintf(szBuff, L"%i.%i / %i.%i, %i / %i", static_cast<int>(position), @@ -58,8 +58,8 @@ class CSeek : public CSimpleDialog<IDD_SEEK>, virtual BOOL OnIdle() { wchar_t szBuff[200]; - float position = media::Movie::get()->GetPosition(); - float duration = media::Movie::get()->GetDuration(); + float position = media::Movie::GetInstance()->GetPosition(); + float duration = media::Movie::GetInstance()->GetDuration(); // TODO(fbarchard): Use frame rate property when it exists. float fps = 29.97f; wsprintf(szBuff, L"%i.%i / %i.%i, %i / %i", diff --git a/media/tools/player_wtl/view.h b/media/tools/player_wtl/view.h index dd1aaaf..cbb0a48 100644 --- a/media/tools/player_wtl/view.h +++ b/media/tools/player_wtl/view.h @@ -182,7 +182,8 @@ class WtlVideoWindow : public CScrollWindowImpl<WtlVideoWindow> { } // Append each frame to end of file. - bool enable_dump_yuv_file = media::Movie::get()->GetDumpYuvFileEnable(); + bool enable_dump_yuv_file = + media::Movie::GetInstance()->GetDumpYuvFileEnable(); if (enable_dump_yuv_file) { DumpYUV(video_frame); } @@ -191,7 +192,7 @@ class WtlVideoWindow : public CScrollWindowImpl<WtlVideoWindow> { double yuv_time_start = GetTime(); // Start timer. #endif - bool enable_draw = media::Movie::get()->GetDrawEnable(); + bool enable_draw = media::Movie::GetInstance()->GetDrawEnable(); if (enable_draw) { DCHECK(bm.bmBitsPixel == 32); DrawYUV(video_frame, diff --git a/net/base/bandwidth_metrics.cc b/net/base/bandwidth_metrics.cc index eaaa3c0..fa23a77 100644 --- a/net/base/bandwidth_metrics.cc +++ b/net/base/bandwidth_metrics.cc @@ -2,14 +2,35 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/singleton.h" +#include "base/lazy_instance.h" #include "net/base/bandwidth_metrics.h" +static base::LazyInstance<net::BandwidthMetrics> g_bandwidth_metrics( + base::LINKER_INITIALIZED); + namespace net { ScopedBandwidthMetrics::ScopedBandwidthMetrics() - : metrics_(Singleton<BandwidthMetrics>::get()), - started_(false) { + : started_(false) { +} + +ScopedBandwidthMetrics::~ScopedBandwidthMetrics() { + if (started_) + g_bandwidth_metrics.Get().StopStream(); +} + +void ScopedBandwidthMetrics::StartStream() { + started_ = true; + g_bandwidth_metrics.Get().StartStream(); +} + +void ScopedBandwidthMetrics::StopStream() { + started_ = false; + g_bandwidth_metrics.Get().StopStream(); +} + +void ScopedBandwidthMetrics::RecordBytes(int bytes) { + g_bandwidth_metrics.Get().RecordBytes(bytes); } } // namespace net diff --git a/net/base/bandwidth_metrics.h b/net/base/bandwidth_metrics.h index aef366d..ce1a498 100644 --- a/net/base/bandwidth_metrics.h +++ b/net/base/bandwidth_metrics.h @@ -122,30 +122,16 @@ class BandwidthMetrics { class ScopedBandwidthMetrics { public: ScopedBandwidthMetrics(); + ~ScopedBandwidthMetrics(); - ~ScopedBandwidthMetrics() { - if (started_) - metrics_->StopStream(); - } - - void StartStream() { - started_ = true; - metrics_->StartStream(); - } - - void StopStream() { - started_ = false; - metrics_->StopStream(); - } - - void RecordBytes(int bytes) { metrics_->RecordBytes(bytes); } + void StartStream(); + void StopStream(); + void RecordBytes(int bytes); private: - BandwidthMetrics* metrics_; bool started_; }; } // namespace net #endif // NET_BASE_BANDWIDTH_METRICS_H_ - diff --git a/net/base/cert_database_nss_unittest.cc b/net/base/cert_database_nss_unittest.cc index 5056e5d..8e69104 100644 --- a/net/base/cert_database_nss_unittest.cc +++ b/net/base/cert_database_nss_unittest.cc @@ -104,16 +104,9 @@ bool ReadCertIntoList(const std::string& name, CertificateList* certs) { class CertDatabaseNSSTest : public testing::Test { public: virtual void SetUp() { - if (!temp_db_initialized_) { - ScopedTempDir* temp_db_dir = Singleton< - ScopedTempDir, - DefaultSingletonTraits<ScopedTempDir>, - CertDatabaseNSSTest>::get(); - ASSERT_TRUE(temp_db_dir->CreateUniqueTempDir()); - ASSERT_TRUE( - base::OpenTestNSSDB(temp_db_dir->path(), "CertDatabaseNSSTest db")); - temp_db_initialized_ = true; - } + ASSERT_TRUE(temp_db_dir_.CreateUniqueTempDir()); + ASSERT_TRUE( + base::OpenTestNSSDB(temp_db_dir_.path(), "CertDatabaseNSSTest db")); slot_.reset(base::GetDefaultNSSKeySlot()); // Test db should be empty at start of test. @@ -121,7 +114,6 @@ class CertDatabaseNSSTest : public testing::Test { } virtual void TearDown() { // Don't try to cleanup if the setup failed. - ASSERT_TRUE(temp_db_initialized_); ASSERT_TRUE(slot_.get()); EXPECT_TRUE(CleanupSlotContents(slot_.get())); @@ -133,12 +125,9 @@ class CertDatabaseNSSTest : public testing::Test { CertDatabase cert_db_; private: - static bool temp_db_initialized_; + ScopedTempDir temp_db_dir_; }; -// static -bool CertDatabaseNSSTest::temp_db_initialized_ = false; - TEST_F(CertDatabaseNSSTest, ListCerts) { // This test isn't terribly useful, though it will at least let valgrind test // for leaks. diff --git a/net/base/mime_util.cc b/net/base/mime_util.cc index ddcfc4b..d95c029 100644 --- a/net/base/mime_util.cc +++ b/net/base/mime_util.cc @@ -9,8 +9,8 @@ #include "net/base/platform_mime_util.h" #include "base/hash_tables.h" +#include "base/lazy_instance.h" #include "base/logging.h" -#include "base/singleton.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" @@ -51,7 +51,7 @@ class MimeUtil : public PlatformMimeUtil { const std::vector<std::string>& codecs) const; private: - friend struct DefaultSingletonTraits<MimeUtil>; + friend struct base::DefaultLazyInstanceTraits<MimeUtil>; MimeUtil() { InitializeMimeTypeMaps(); } @@ -71,6 +71,8 @@ class MimeUtil : public PlatformMimeUtil { StrictMappings strict_format_map_; }; // class MimeUtil +static base::LazyInstance<MimeUtil> g_mime_util(base::LINKER_INITIALIZED); + struct MimeInfo { const char* mime_type; const char* extensions; // comma separated list @@ -473,70 +475,67 @@ bool MimeUtil::IsSupportedStrictMediaMimeType(const std::string& mime_type, // Wrappers for the singleton //---------------------------------------------------------------------------- -static MimeUtil* GetMimeUtil() { - return Singleton<MimeUtil>::get(); -} - bool GetMimeTypeFromExtension(const FilePath::StringType& ext, std::string* mime_type) { - return GetMimeUtil()->GetMimeTypeFromExtension(ext, mime_type); + return g_mime_util.Get().GetMimeTypeFromExtension(ext, mime_type); } bool GetMimeTypeFromFile(const FilePath& file_path, std::string* mime_type) { - return GetMimeUtil()->GetMimeTypeFromFile(file_path, mime_type); + return g_mime_util.Get().GetMimeTypeFromFile(file_path, mime_type); } bool GetPreferredExtensionForMimeType(const std::string& mime_type, FilePath::StringType* extension) { - return GetMimeUtil()->GetPreferredExtensionForMimeType(mime_type, extension); + return g_mime_util.Get().GetPreferredExtensionForMimeType(mime_type, + extension); } bool IsSupportedImageMimeType(const char* mime_type) { - return GetMimeUtil()->IsSupportedImageMimeType(mime_type); + return g_mime_util.Get().IsSupportedImageMimeType(mime_type); } bool IsSupportedMediaMimeType(const char* mime_type) { - return GetMimeUtil()->IsSupportedMediaMimeType(mime_type); + return g_mime_util.Get().IsSupportedMediaMimeType(mime_type); } bool IsSupportedNonImageMimeType(const char* mime_type) { - return GetMimeUtil()->IsSupportedNonImageMimeType(mime_type); + return g_mime_util.Get().IsSupportedNonImageMimeType(mime_type); } bool IsSupportedJavascriptMimeType(const char* mime_type) { - return GetMimeUtil()->IsSupportedJavascriptMimeType(mime_type); + return g_mime_util.Get().IsSupportedJavascriptMimeType(mime_type); } bool IsViewSourceMimeType(const char* mime_type) { - return GetMimeUtil()->IsViewSourceMimeType(mime_type); + return g_mime_util.Get().IsViewSourceMimeType(mime_type); } bool IsSupportedMimeType(const std::string& mime_type) { - return GetMimeUtil()->IsSupportedMimeType(mime_type); + return g_mime_util.Get().IsSupportedMimeType(mime_type); } bool MatchesMimeType(const std::string &mime_type_pattern, const std::string &mime_type) { - return GetMimeUtil()->MatchesMimeType(mime_type_pattern, mime_type); + return g_mime_util.Get().MatchesMimeType(mime_type_pattern, mime_type); } bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) { - return GetMimeUtil()->AreSupportedMediaCodecs(codecs); + return g_mime_util.Get().AreSupportedMediaCodecs(codecs); } bool IsStrictMediaMimeType(const std::string& mime_type) { - return GetMimeUtil()->IsStrictMediaMimeType(mime_type); + return g_mime_util.Get().IsStrictMediaMimeType(mime_type); } bool IsSupportedStrictMediaMimeType(const std::string& mime_type, const std::vector<std::string>& codecs) { - return GetMimeUtil()->IsSupportedStrictMediaMimeType(mime_type, codecs); + return g_mime_util.Get().IsSupportedStrictMediaMimeType(mime_type, codecs); } void ParseCodecString(const std::string& codecs, std::vector<std::string>* codecs_out, const bool strip) { - GetMimeUtil()->ParseCodecString(codecs, codecs_out, strip); + g_mime_util.Get().ParseCodecString(codecs, codecs_out, strip); } namespace { diff --git a/net/base/winsock_init.cc b/net/base/winsock_init.cc index ccaf01c..41810ef 100644 --- a/net/base/winsock_init.cc +++ b/net/base/winsock_init.cc @@ -6,8 +6,8 @@ #include "net/base/winsock_init.h" +#include "base/lazy_instance.h" #include "base/logging.h" -#include "base/singleton.h" namespace { @@ -37,12 +37,15 @@ class WinsockInitSingleton { } }; +static base::LazyInstance<WinsockInitSingleton> g_winsock_init_singleton( + base::LINKER_INITIALIZED); + } // namespace namespace net { void EnsureWinsockInit() { - Singleton<WinsockInitSingleton>::get(); + g_winsock_init_singleton.Get(); } } // namespace net diff --git a/net/base/x509_certificate_win.cc b/net/base/x509_certificate_win.cc index 75cdf40..71aa545 100644 --- a/net/base/x509_certificate_win.cc +++ b/net/base/x509_certificate_win.cc @@ -4,9 +4,9 @@ #include "net/base/x509_certificate.h" +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/pickle.h" -#include "base/singleton.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" @@ -529,7 +529,7 @@ class GlobalCertStore { } private: - friend struct DefaultSingletonTraits<GlobalCertStore>; + friend struct base::DefaultLazyInstanceTraits<GlobalCertStore>; GlobalCertStore() : cert_store_(CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, 0, NULL)) { @@ -544,9 +544,12 @@ class GlobalCertStore { DISALLOW_COPY_AND_ASSIGN(GlobalCertStore); }; +static base::LazyInstance<GlobalCertStore> g_cert_store( + base::LINKER_INITIALIZED); + // static HCERTSTORE X509Certificate::cert_store() { - return Singleton<GlobalCertStore>::get()->cert_store(); + return g_cert_store.Get().cert_store(); } int X509Certificate::Verify(const std::string& hostname, diff --git a/net/disk_cache/file_win.cc b/net/disk_cache/file_win.cc index 5b01224..737b8e8 100644 --- a/net/disk_cache/file_win.cc +++ b/net/disk_cache/file_win.cc @@ -5,8 +5,8 @@ #include "net/disk_cache/file.h" #include "base/file_path.h" +#include "base/lazy_instance.h" #include "base/message_loop.h" -#include "base/singleton.h" #include "net/disk_cache/disk_cache.h" namespace { @@ -33,6 +33,9 @@ class CompletionHandler : public MessageLoopForIO::IOHandler { DWORD actual_bytes, DWORD error); }; +static base::LazyInstance<CompletionHandler> g_completion_handler( + base::LINKER_INITIALIZED); + void CompletionHandler::OnIOCompleted(MessageLoopForIO::IOContext* context, DWORD actual_bytes, DWORD error) { MyOverlapped* data = reinterpret_cast<MyOverlapped*>(context); @@ -52,7 +55,7 @@ void CompletionHandler::OnIOCompleted(MessageLoopForIO::IOContext* context, MyOverlapped::MyOverlapped(disk_cache::File* file, size_t offset, disk_cache::FileIOCallback* callback) { memset(this, 0, sizeof(*this)); - context_.handler = Singleton<CompletionHandler>::get(); + context_.handler = g_completion_handler.Pointer(); context_.overlapped.Offset = static_cast<DWORD>(offset); file_ = file; callback_ = callback; @@ -81,7 +84,7 @@ bool File::Init(const FilePath& name) { return false; MessageLoopForIO::current()->RegisterIOHandler( - platform_file_, Singleton<CompletionHandler>::get()); + platform_file_, g_completion_handler.Pointer()); init_ = true; sync_platform_file_ = CreateFile(name.value().c_str(), access, sharing, NULL, @@ -255,7 +258,7 @@ void File::WaitForPendingIO(int* num_pending_io) { while (*num_pending_io) { // Asynchronous IO operations may be in flight and the completion may end // up calling us back so let's wait for them. - MessageLoopForIO::IOHandler* handler = Singleton<CompletionHandler>::get(); + MessageLoopForIO::IOHandler* handler = g_completion_handler.Pointer(); MessageLoopForIO::current()->WaitForIOCompletion(100, handler); } } diff --git a/net/socket/client_socket_factory.cc b/net/socket/client_socket_factory.cc index 8965630..1c998c6 100644 --- a/net/socket/client_socket_factory.cc +++ b/net/socket/client_socket_factory.cc @@ -4,7 +4,7 @@ #include "net/socket/client_socket_factory.h" -#include "base/singleton.h" +#include "base/lazy_instance.h" #include "build/build_config.h" #include "net/socket/client_socket_handle.h" #if defined(OS_WIN) @@ -71,11 +71,14 @@ class DefaultClientSocketFactory : public ClientSocketFactory { } }; +static base::LazyInstance<DefaultClientSocketFactory> + g_default_client_socket_factory(base::LINKER_INITIALIZED); + } // namespace // static ClientSocketFactory* ClientSocketFactory::GetDefaultFactory() { - return Singleton<DefaultClientSocketFactory>::get(); + return g_default_client_socket_factory.Pointer(); } // static diff --git a/net/socket/dns_cert_provenance_checker.cc b/net/socket/dns_cert_provenance_checker.cc index 27c4982..2243755 100644 --- a/net/socket/dns_cert_provenance_checker.cc +++ b/net/socket/dns_cert_provenance_checker.cc @@ -19,10 +19,10 @@ #include "base/basictypes.h" #include "base/crypto/encryptor.h" #include "base/crypto/symmetric_key.h" +#include "base/lazy_instance.h" #include "base/non_thread_safe.h" #include "base/pickle.h" #include "base/scoped_ptr.h" -#include "base/singleton.h" #include "net/base/completion_callback.h" #include "net/base/dns_util.h" #include "net/base/dnsrr_resolver.h" @@ -72,13 +72,16 @@ class DnsCertLimits { } private: - friend struct DefaultSingletonTraits<DnsCertLimits>; + friend struct base::DefaultLazyInstanceTraits<DnsCertLimits>; std::set<std::string> uploaded_hostnames_; DISALLOW_COPY_AND_ASSIGN(DnsCertLimits); }; +static base::LazyInstance<DnsCertLimits> g_dns_cert_limits( + base::LINKER_INITIALIZED); + // DnsCertProvenanceCheck performs the DNS lookup of the certificate. This // class is self-deleting. class DnsCertProvenanceCheck : public NonThreadSafe { @@ -105,7 +108,7 @@ class DnsCertProvenanceCheck : public NonThreadSafe { if (der_certs_.empty()) return; - DnsCertLimits* const limits = Singleton<DnsCertLimits>::get(); + DnsCertLimits* const limits = g_dns_cert_limits.Pointer(); if (limits->HaveReachedMaxUploads() || limits->HaveUploadedForHostname(hostname_)) { return; @@ -146,7 +149,7 @@ class DnsCertProvenanceCheck : public NonThreadSafe { LOG(ERROR) << "FAILED" << " hostname:" << hostname_ << " domain:" << domain_; - Singleton<DnsCertLimits>::get()->DidUpload(hostname_); + g_dns_cert_limits.Get().DidUpload(hostname_); delegate_->OnDnsCertLookupFailed(hostname_, der_certs_); } else if (status == OK) { LOG(ERROR) << "GOOD" diff --git a/net/socket/ssl_client_socket_mac.cc b/net/socket/ssl_client_socket_mac.cc index fb0c26e..488beeb 100644 --- a/net/socket/ssl_client_socket_mac.cc +++ b/net/socket/ssl_client_socket_mac.cc @@ -11,8 +11,8 @@ #include <algorithm> +#include "base/lazy_instance.h" #include "base/mac/scoped_cftyperef.h" -#include "base/singleton.h" #include "base/string_util.h" #include "net/base/address_list.h" #include "net/base/cert_verifier.h" @@ -475,7 +475,7 @@ class EnabledCipherSuites { const std::vector<SSLCipherSuite>& ciphers() const { return ciphers_; } private: - friend struct DefaultSingletonTraits<EnabledCipherSuites>; + friend struct base::DefaultLazyInstanceTraits<EnabledCipherSuites>; EnabledCipherSuites(); ~EnabledCipherSuites() {} @@ -484,6 +484,9 @@ class EnabledCipherSuites { DISALLOW_COPY_AND_ASSIGN(EnabledCipherSuites); }; +static base::LazyInstance<EnabledCipherSuites> g_enabled_cipher_suites( + base::LINKER_INITIALIZED); + EnabledCipherSuites::EnabledCipherSuites() { SSLContextRef ssl_context; OSStatus status = SSLNewContext(false, &ssl_context); @@ -786,7 +789,7 @@ int SSLClientSocketMac::InitializeSSLContext() { return NetErrorFromOSStatus(status); std::vector<SSLCipherSuite> enabled_ciphers = - Singleton<EnabledCipherSuites>::get()->ciphers(); + g_enabled_cipher_suites.Get().ciphers(); CipherSuiteIsDisabledFunctor is_disabled_cipher( ssl_config_.disabled_cipher_suites); diff --git a/net/socket/ssl_client_socket_nss.cc b/net/socket/ssl_client_socket_nss.cc index fff4352..f946819 100644 --- a/net/socket/ssl_client_socket_nss.cc +++ b/net/socket/ssl_client_socket_nss.cc @@ -63,9 +63,9 @@ #include "base/compiler_specific.h" #include "base/metrics/histogram.h" +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/nss_util.h" -#include "base/singleton.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/stringprintf.h" @@ -185,6 +185,9 @@ class NSSSSLInitSingleton { } }; +static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton( + base::LINKER_INITIALIZED); + // Initialize the NSS SSL library if it isn't already initialized. This must // be called before any other NSS SSL functions. This function is // thread-safe, and the NSS SSL library will only ever be initialized once. @@ -195,7 +198,7 @@ void EnsureNSSSSLInit() { // http://code.google.com/p/chromium/issues/detail?id=59847 base::ThreadRestrictions::ScopedAllowIO allow_io; - Singleton<NSSSSLInitSingleton>::get(); + g_nss_ssl_init_singleton.Get(); } // The default error mapping function. diff --git a/net/socket/ssl_client_socket_win.cc b/net/socket/ssl_client_socket_win.cc index fbe4913..19c3814 100644 --- a/net/socket/ssl_client_socket_win.cc +++ b/net/socket/ssl_client_socket_win.cc @@ -8,8 +8,8 @@ #include <map> #include "base/compiler_specific.h" +#include "base/lazy_instance.h" #include "base/lock.h" -#include "base/singleton.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" @@ -194,6 +194,9 @@ class CredHandleTable { CredHandleMap client_cert_creds_; }; +static base::LazyInstance<CredHandleTable> g_cred_handle_table( + base::LINKER_INITIALIZED); + // static int CredHandleTable::InitializeHandle(CredHandle* handle, PCCERT_CONTEXT client_cert, @@ -285,9 +288,9 @@ static int GetCredHandle(PCCERT_CONTEXT client_cert, NOTREACHED(); return ERR_UNEXPECTED; } - return Singleton<CredHandleTable>::get()->GetHandle(client_cert, - ssl_version_mask, - handle_ptr); + return g_cred_handle_table.Get().GetHandle(client_cert, + ssl_version_mask, + handle_ptr); } //----------------------------------------------------------------------------- @@ -356,6 +359,9 @@ class ClientCertStore { HCERTSTORE store_; }; +static base::LazyInstance<ClientCertStore> g_client_cert_store( + base::LINKER_INITIALIZED); + //----------------------------------------------------------------------------- // Size of recv_buffer_ @@ -507,7 +513,7 @@ void SSLClientSocketWin::GetSSLCertRequestInfo( // Copy it to our own certificate store, so that we can close the "MY" // certificate store before returning from this function. PCCERT_CONTEXT cert_context2 = - Singleton<ClientCertStore>::get()->CopyCertContext(cert_context); + g_client_cert_store.Get().CopyCertContext(cert_context); if (!cert_context2) { NOTREACHED(); continue; diff --git a/net/third_party/mozilla_security_manager/nsPKCS12Blob.cpp b/net/third_party/mozilla_security_manager/nsPKCS12Blob.cpp index aae8d90..cf2b0cf 100644 --- a/net/third_party/mozilla_security_manager/nsPKCS12Blob.cpp +++ b/net/third_party/mozilla_security_manager/nsPKCS12Blob.cpp @@ -43,9 +43,9 @@ #include <secerr.h> #include "base/crypto/scoped_nss_types.h" +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/nss_util_internal.h" -#include "base/singleton.h" #include "base/string_util.h" #include "net/base/net_errors.h" #include "net/base/x509_certificate.h" @@ -252,10 +252,13 @@ class PKCS12InitSingleton { } }; +static base::LazyInstance<PKCS12InitSingleton> g_pkcs12_init_singleton( + base::LINKER_INITIALIZED); + } // namespace void EnsurePKCS12Init() { - Singleton<PKCS12InitSingleton>::get(); + g_pkcs12_init_singleton.Get(); } // Based on nsPKCS12Blob::ImportFromFile. diff --git a/net/tools/fetch/fetch_client.cc b/net/tools/fetch/fetch_client.cc index 138bed3..800f3070 100644 --- a/net/tools/fetch/fetch_client.cc +++ b/net/tools/fetch/fetch_client.cc @@ -6,9 +6,9 @@ #include "base/at_exit.h" #include "base/command_line.h" +#include "base/lazy_instance.h" #include "base/message_loop.h" #include "base/metrics/stats_counters.h" -#include "base/singleton.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "net/base/completion_callback.h" @@ -47,6 +47,8 @@ class Driver { int clients_; }; +static base::LazyInstance<Driver> g_driver(base::LINKER_INITIALIZED); + // A network client class Client { public: @@ -60,7 +62,7 @@ class Client { int rv = factory->CreateTransaction(&transaction_); DCHECK_EQ(net::OK, rv); buffer_->AddRef(); - driver_->ClientStarted(); + g_driver.Get().ClientStarted(); request_info_.url = url_; request_info_.method = "GET"; int state = transaction_->Start( @@ -101,7 +103,7 @@ class Client { void OnRequestComplete(int result) { static base::StatsCounter requests("FetchClient.requests"); requests.Increment(); - driver_->ClientStopped(); + g_driver.Get().ClientStopped(); printf("."); } @@ -112,7 +114,6 @@ class Client { scoped_refptr<net::IOBuffer> buffer_; net::CompletionCallbackImpl<Client> connect_callback_; net::CompletionCallbackImpl<Client> read_callback_; - Singleton<Driver> driver_; }; int main(int argc, char**argv) { diff --git a/net/websockets/websocket_job.cc b/net/websockets/websocket_job.cc index 9adbaa3..44c944d 100644 --- a/net/websockets/websocket_job.cc +++ b/net/websockets/websocket_job.cc @@ -6,7 +6,7 @@ #include <algorithm> -#include "base/singleton.h" +#include "base/lazy_instance.h" #include "base/string_tokenizer.h" #include "googleurl/src/gurl.h" #include "net/base/net_errors.h" @@ -40,20 +40,23 @@ net::SocketStreamJob* WebSocketJobFactory( class WebSocketJobInitSingleton { private: - friend struct DefaultSingletonTraits<WebSocketJobInitSingleton>; + friend struct base::DefaultLazyInstanceTraits<WebSocketJobInitSingleton>; WebSocketJobInitSingleton() { net::SocketStreamJob::RegisterProtocolFactory("ws", WebSocketJobFactory); net::SocketStreamJob::RegisterProtocolFactory("wss", WebSocketJobFactory); } }; +static base::LazyInstance<WebSocketJobInitSingleton> g_websocket_job_init( + base::LINKER_INITIALIZED); + } // anonymous namespace namespace net { // static void WebSocketJob::EnsureInit() { - Singleton<WebSocketJobInitSingleton>::get(); + g_websocket_job_init.Get(); } WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate) diff --git a/printing/backend/print_backend_cups.cc b/printing/backend/print_backend_cups.cc index 9fbf2ab..e75a800 100644 --- a/printing/backend/print_backend_cups.cc +++ b/printing/backend/print_backend_cups.cc @@ -12,9 +12,9 @@ #include <pthread.h> #include "base/file_util.h" +#include "base/lazy_instance.h" #include "base/lock.h" #include "base/logging.h" -#include "base/singleton.h" #include "base/string_number_conversions.h" #include "base/values.h" #include "googleurl/src/gurl.h" @@ -66,6 +66,9 @@ class GcryptInitializer { } }; +static base::LazyInstance<GcryptInitializer> g_gcrypt_initializer( + base::LINKER_INITIALIZED); + } // namespace #endif @@ -188,7 +191,7 @@ scoped_refptr<PrintBackend> PrintBackend::CreateInstance( const DictionaryValue* print_backend_settings) { #if !defined(OS_MACOSX) // Initialize gcrypt library. - Singleton<GcryptInitializer>::get(); + g_gcrypt_initializer.Get(); #endif std::string print_server_url_str; diff --git a/printing/printed_document.cc b/printing/printed_document.cc index 75d4b95..0880da5 100644 --- a/printing/printed_document.cc +++ b/printing/printed_document.cc @@ -13,8 +13,8 @@ #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/file_util_icu.h" +#include "base/lazy_instance.h" #include "base/message_loop.h" -#include "base/singleton.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/i18n/time_formatting.h" @@ -37,7 +37,8 @@ struct PrintDebugDumpPath { FilePath debug_dump_path; }; -Singleton<PrintDebugDumpPath> g_debug_dump_info; +static base::LazyInstance<PrintDebugDumpPath> g_debug_dump_info( + base::LINKER_INITIALIZED); } // namespace @@ -244,7 +245,7 @@ void PrintedDocument::PrintHeaderFooter(gfx::NativeDrawingContext context, } void PrintedDocument::DebugDump(const PrintedPage& page) { - if (!g_debug_dump_info->enabled) + if (!g_debug_dump_info.Get().enabled) return; string16 filename; @@ -258,19 +259,19 @@ void PrintedDocument::DebugDump(const PrintedPage& page) { filename += ASCIIToUTF16("_.emf"); #if defined(OS_WIN) page.native_metafile()->SaveTo( - g_debug_dump_info->debug_dump_path.Append(filename).ToWStringHack()); + g_debug_dump_info.Get().debug_dump_path.Append(filename).ToWStringHack()); #else // OS_WIN NOTIMPLEMENTED(); #endif // OS_WIN } void PrintedDocument::set_debug_dump_path(const FilePath& debug_dump_path) { - g_debug_dump_info->enabled = !debug_dump_path.empty(); - g_debug_dump_info->debug_dump_path = debug_dump_path; + g_debug_dump_info.Get().enabled = !debug_dump_path.empty(); + g_debug_dump_info.Get().debug_dump_path = debug_dump_path; } const FilePath& PrintedDocument::debug_dump_path() { - return g_debug_dump_info->debug_dump_path; + return g_debug_dump_info.Get().debug_dump_path; } PrintedDocument::Mutable::Mutable(PrintedPagesSource* source) diff --git a/remoting/base/tracer.cc b/remoting/base/tracer.cc index 3245887..3cef3a0 100644 --- a/remoting/base/tracer.cc +++ b/remoting/base/tracer.cc @@ -8,6 +8,7 @@ #include "base/basictypes.h" #include "base/condition_variable.h" +#include "base/lazy_instance.h" #include "base/message_loop.h" #include "base/rand_util.h" #include "base/ref_counted.h" @@ -88,7 +89,7 @@ class OutputLogger { } private: - friend struct DefaultSingletonTraits<OutputLogger>; + friend struct base::DefaultLazyInstanceTraits<OutputLogger>; ~OutputLogger() { { @@ -108,6 +109,11 @@ class OutputLogger { std::list<TraceBuffer*> buffers_; }; +static base::LazyInstance<OutputLogger> g_output_logger( + base::LINKER_INITIALIZED); +static base::LazyInstance<base::ThreadLocalPointer<TraceContext> > + g_thread_local_trace_context(base::LINKER_INITIALIZED); + } // namespace Tracer::Tracer(const std::string& name, double sample_percent) { @@ -136,7 +142,7 @@ Tracer::~Tracer() { AutoLock l(lock_); if (buffer_.get()) { - Singleton<OutputLogger>::get()->OutputTrace(buffer_.release()); + g_output_logger.Get().OutputTrace(buffer_.release()); } } @@ -158,11 +164,11 @@ void TraceContext::PopTracer() { // static TraceContext* TraceContext::Get() { TraceContext* context = - Singleton<base::ThreadLocalPointer<TraceContext> >::get()->Get(); + g_thread_local_trace_context.Get().Get(); if (context == NULL) { context = new TraceContext(); context->PushTracerInternal(new Tracer("default", 0.0)); - Singleton<base::ThreadLocalPointer<TraceContext> >::get()->Set(context); + g_thread_local_trace_context.Get().Set(context); } return context; } diff --git a/skia/ext/vector_platform_device_linux.cc b/skia/ext/vector_platform_device_linux.cc index 3d45596..4bf5fd1 100644 --- a/skia/ext/vector_platform_device_linux.cc +++ b/skia/ext/vector_platform_device_linux.cc @@ -12,8 +12,8 @@ #include <map> +#include "base/lazy_instance.h" #include "base/logging.h" -#include "base/singleton.h" #include "skia/ext/bitmap_platform_device.h" #include "third_party/skia/include/core/SkFontHost.h" #include "third_party/skia/include/core/SkStream.h" @@ -29,6 +29,8 @@ struct FontInfo { }; typedef std::map<uint32_t, FontInfo> MapFontId2FontInfo; +static base::LazyInstance<MapFontId2FontInfo> g_map_font_id_to_font_info( + base::LINKER_INITIALIZED); // Wrapper for FT_Library that handles initialization and cleanup, and allows // us to use a singleton. @@ -55,6 +57,7 @@ class FtLibrary { private: FT_Library library_; }; +static base::LazyInstance<FtLibrary> g_ft_library(base::LINKER_INITIALIZED); // Verify cairo surface after creation/modification. bool IsContextValid(cairo_t* context) { @@ -592,12 +595,12 @@ bool VectorPlatformDevice::SelectFontById(uint32_t font_id) { DCHECK(IsContextValid(context_)); DCHECK(SkFontHost::ValidFontID(font_id)); - FtLibrary* ft_library = Singleton<FtLibrary>::get(); + FtLibrary* ft_library = g_ft_library.Pointer(); if (!ft_library->library()) return false; // Checks if we have a cache hit. - MapFontId2FontInfo* g_font_cache = Singleton<MapFontId2FontInfo>::get(); + MapFontId2FontInfo* g_font_cache = g_map_font_id_to_font_info.Pointer(); DCHECK(g_font_cache); MapFontId2FontInfo::iterator it = g_font_cache->find(font_id); @@ -667,7 +670,7 @@ bool VectorPlatformDevice::SelectFontById(uint32_t font_id) { // static void VectorPlatformDevice::ClearFontCache() { - MapFontId2FontInfo* g_font_cache = Singleton<MapFontId2FontInfo>::get(); + MapFontId2FontInfo* g_font_cache = g_map_font_id_to_font_info.Pointer(); DCHECK(g_font_cache); for (MapFontId2FontInfo::iterator it = g_font_cache->begin(); diff --git a/views/focus/focus_manager.cc b/views/focus/focus_manager.cc index 4848e4b..e8a3e7e 100644 --- a/views/focus/focus_manager.cc +++ b/views/focus/focus_manager.cc @@ -63,6 +63,12 @@ void FocusManager::WidgetFocusManager::OnWidgetFocusEvent( } } +// static +FocusManager::WidgetFocusManager* +FocusManager::WidgetFocusManager::GetInstance() { + return Singleton<WidgetFocusManager>::get(); +} + // FocusManager ----------------------------------------------------- FocusManager::FocusManager(Widget* widget) @@ -82,7 +88,7 @@ FocusManager::~FocusManager() { // static FocusManager::WidgetFocusManager* FocusManager::GetWidgetFocusManager() { - return Singleton<WidgetFocusManager>::get(); + return WidgetFocusManager::GetInstance(); } bool FocusManager::OnKeyEvent(const KeyEvent& event) { diff --git a/views/focus/focus_manager.h b/views/focus/focus_manager.h index 28f97b4..6eee79d 100644 --- a/views/focus/focus_manager.h +++ b/views/focus/focus_manager.h @@ -126,6 +126,9 @@ class FocusManager { public: class WidgetFocusManager { public: + // Returns the singleton instance. + static WidgetFocusManager* GetInstance(); + // Adds/removes a WidgetFocusChangeListener |listener| to the set of // active listeners. void AddFocusChangeListener(WidgetFocusChangeListener* listener); diff --git a/webkit/appcache/web_application_cache_host_impl.cc b/webkit/appcache/web_application_cache_host_impl.cc index f65bed6..76c75c19 100644 --- a/webkit/appcache/web_application_cache_host_impl.cc +++ b/webkit/appcache/web_application_cache_host_impl.cc @@ -6,9 +6,9 @@ #include "base/compiler_specific.h" #include "base/id_map.h" +#include "base/lazy_instance.h" #include "base/string_util.h" #include "base/stringprintf.h" -#include "base/singleton.h" #include "third_party/WebKit/WebKit/chromium/public/WebDataSource.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" @@ -29,6 +29,7 @@ namespace appcache { namespace { typedef IDMap<WebApplicationCacheHostImpl> HostsMap; +static base::LazyInstance<HostsMap> g_hosts_map(base::LINKER_INITIALIZED); // Note: the order of the elements in this array must match those // of the EventID enum in appcache_interfaces.h. @@ -45,14 +46,10 @@ GURL ClearUrlRef(const GURL& url) { return url.ReplaceComponents(replacements); } -HostsMap* all_hosts() { - return Singleton<HostsMap>::get(); -} - } // anon namespace WebApplicationCacheHostImpl* WebApplicationCacheHostImpl::FromId(int id) { - return all_hosts()->Lookup(id); + return g_hosts_map.Get().Lookup(id); } WebApplicationCacheHostImpl* WebApplicationCacheHostImpl::FromFrame( @@ -71,7 +68,7 @@ WebApplicationCacheHostImpl::WebApplicationCacheHostImpl( AppCacheBackend* backend) : client_(client), backend_(backend), - ALLOW_THIS_IN_INITIALIZER_LIST(host_id_(all_hosts()->Add(this))), + ALLOW_THIS_IN_INITIALIZER_LIST(host_id_(g_hosts_map.Get().Add(this))), has_status_(false), status_(UNCACHED), has_cached_status_(false), @@ -86,7 +83,7 @@ WebApplicationCacheHostImpl::WebApplicationCacheHostImpl( WebApplicationCacheHostImpl::~WebApplicationCacheHostImpl() { backend_->UnregisterHost(host_id_); - all_hosts()->Remove(host_id_); + g_hosts_map.Get().Remove(host_id_); } void WebApplicationCacheHostImpl::OnCacheSelected( diff --git a/webkit/blob/deletable_file_reference.cc b/webkit/blob/deletable_file_reference.cc index 87ef4cc..7a5cfac 100644 --- a/webkit/blob/deletable_file_reference.cc +++ b/webkit/blob/deletable_file_reference.cc @@ -7,27 +7,25 @@ #include <map> #include "base/file_util.h" #include "base/file_util_proxy.h" +#include "base/lazy_instance.h" #include "base/message_loop_proxy.h" -#include "base/singleton.h" namespace webkit_blob { namespace { typedef std::map<FilePath, DeletableFileReference*> DeleteableFileMap; - -DeleteableFileMap* map() { - return Singleton<DeleteableFileMap>::get(); -} +static base::LazyInstance<DeleteableFileMap> g_deletable_file_map( + base::LINKER_INITIALIZED); } // namespace // static scoped_refptr<DeletableFileReference> DeletableFileReference::Get( const FilePath& path) { - DeleteableFileMap::iterator found = map()->find(path); + DeleteableFileMap::iterator found = g_deletable_file_map.Get().find(path); DeletableFileReference* reference = - (found == map()->end()) ? NULL : found->second; + (found == g_deletable_file_map.Get().end()) ? NULL : found->second; return scoped_refptr<DeletableFileReference>(reference); } @@ -36,7 +34,7 @@ scoped_refptr<DeletableFileReference> DeletableFileReference::GetOrCreate( const FilePath& path, base::MessageLoopProxy* file_thread) { DCHECK(file_thread); typedef std::pair<DeleteableFileMap::iterator, bool> InsertResult; - InsertResult result = map()->insert( + InsertResult result = g_deletable_file_map.Get().insert( DeleteableFileMap::value_type(path, NULL)); if (result.second == false) return scoped_refptr<DeletableFileReference>(result.first->second); @@ -51,12 +49,12 @@ scoped_refptr<DeletableFileReference> DeletableFileReference::GetOrCreate( DeletableFileReference::DeletableFileReference( const FilePath& path, base::MessageLoopProxy* file_thread) : path_(path), file_thread_(file_thread) { - DCHECK(map()->find(path_)->second == NULL); + DCHECK(g_deletable_file_map.Get().find(path_)->second == NULL); } DeletableFileReference::~DeletableFileReference() { - DCHECK(map()->find(path_)->second == this); - map()->erase(path_); + DCHECK(g_deletable_file_map.Get().find(path_)->second == this); + g_deletable_file_map.Get().erase(path_); base::FileUtilProxy::Delete(file_thread_, path_, false /* recursive */, NULL); } diff --git a/webkit/glue/plugins/pepper_graphics_3d.cc b/webkit/glue/plugins/pepper_graphics_3d.cc index 2dc4def..3e72c29 100644 --- a/webkit/glue/plugins/pepper_graphics_3d.cc +++ b/webkit/glue/plugins/pepper_graphics_3d.cc @@ -5,7 +5,7 @@ #include "webkit/glue/plugins/pepper_graphics_3d.h" #include "gpu/command_buffer/common/command_buffer.h" -#include "base/singleton.h" +#include "base/lazy_instance.h" #include "base/thread_local.h" #include "ppapi/c/dev/ppb_graphics_3d_dev.h" #include "webkit/glue/plugins/pepper_common.h" @@ -15,10 +15,8 @@ namespace pepper { namespace { -struct CurrentContextTag {}; -typedef Singleton<base::ThreadLocalPointer<Graphics3D>, - DefaultSingletonTraits<base::ThreadLocalPointer<Graphics3D> >, - CurrentContextTag> CurrentContextKey; +static base::LazyInstance<base::ThreadLocalPointer<Graphics3D> > + g_current_context_key(base::LINKER_INITIALIZED); // Size of the transfer buffer. enum { kTransferBufferSize = 512 * 1024 }; @@ -138,11 +136,11 @@ const PPB_Graphics3D_Dev* Graphics3D::GetInterface() { } Graphics3D* Graphics3D::GetCurrent() { - return CurrentContextKey::get()->Get(); + return g_current_context_key.Get().Get(); } void Graphics3D::ResetCurrent() { - CurrentContextKey::get()->Set(NULL); + g_current_context_key.Get().Set(NULL); } Graphics3D::~Graphics3D() { @@ -201,7 +199,7 @@ bool Graphics3D::MakeCurrent() { if (!platform_context_.get()) return false; - CurrentContextKey::get()->Set(this); + g_current_context_key.Get().Set(this); // TODO(apatrick): Return false on context lost. return true; diff --git a/webkit/glue/webkit_glue.cc b/webkit/glue/webkit_glue.cc index 350ba29..45944fc 100644 --- a/webkit/glue/webkit_glue.cc +++ b/webkit/glue/webkit_glue.cc @@ -11,9 +11,9 @@ #include <sys/utsname.h> #endif +#include "base/lazy_instance.h" #include "base/logging.h" #include "base/scoped_ptr.h" -#include "base/singleton.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/stringprintf.h" @@ -356,10 +356,11 @@ struct UserAgentState { bool user_agent_is_overridden; }; -Singleton<UserAgentState> g_user_agent; +static base::LazyInstance<UserAgentState> g_user_agent( + base::LINKER_INITIALIZED); void SetUserAgentToDefault() { - BuildUserAgent(false, &g_user_agent->user_agent); + BuildUserAgent(false, &g_user_agent.Get().user_agent); } } // namespace @@ -367,31 +368,31 @@ void SetUserAgentToDefault() { void SetUserAgent(const std::string& new_user_agent) { // If you combine this with the previous line, the function only works the // first time. - DCHECK(!g_user_agent->user_agent_requested) << + DCHECK(!g_user_agent.Get().user_agent_requested) << "Setting the user agent after someone has " "already requested it can result in unexpected behavior."; - g_user_agent->user_agent_is_overridden = true; - g_user_agent->user_agent = new_user_agent; + g_user_agent.Get().user_agent_is_overridden = true; + g_user_agent.Get().user_agent = new_user_agent; } const std::string& GetUserAgent(const GURL& url) { - if (g_user_agent->user_agent.empty()) + if (g_user_agent.Get().user_agent.empty()) SetUserAgentToDefault(); - g_user_agent->user_agent_requested = true; - if (!g_user_agent->user_agent_is_overridden) { + g_user_agent.Get().user_agent_requested = true; + if (!g_user_agent.Get().user_agent_is_overridden) { // Workarounds for sites that use misguided UA sniffing. #if defined(OS_POSIX) && !defined(OS_MACOSX) if (MatchPattern(url.host(), "*.mail.yahoo.com")) { // mail.yahoo.com is ok with Windows Chrome but not Linux Chrome. // http://bugs.chromium.org/11136 // TODO(evanm): remove this if Yahoo fixes their sniffing. - if (g_user_agent->mimic_windows_user_agent.empty()) - BuildUserAgent(true, &g_user_agent->mimic_windows_user_agent); - return g_user_agent->mimic_windows_user_agent; + if (g_user_agent.Get().mimic_windows_user_agent.empty()) + BuildUserAgent(true, &g_user_agent.Get().mimic_windows_user_agent); + return g_user_agent.Get().mimic_windows_user_agent; } #endif } - return g_user_agent->user_agent; + return g_user_agent.Get().user_agent; } void SetForcefullyTerminatePluginProcess(bool value) { |