Fix copyright lines
[folly.git] / folly / Singleton.h
index 01a9d5d12448a4c097664e3d4c7243f47eda87b6..6926ca7dc6b458132e85e2b73c984e5b39666c84 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017 Facebook, Inc.
+ * Copyright 2014-present Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 // SingletonVault - a library to manage the creation and destruction
 // of interdependent singletons.
 //
 // should call reenableInstances.
 
 #pragma once
-#include <folly/Baton.h>
-#include <folly/Demangle.h>
+
 #include <folly/Exception.h>
 #include <folly/Executor.h>
 #include <folly/Memory.h>
-#include <folly/RWSpinLock.h>
 #include <folly/Synchronized.h>
 #include <folly/detail/StaticSingletonManager.h>
 #include <folly/experimental/ReadMostlySharedPtr.h>
 #include <folly/hash/Hash.h>
+#include <folly/synchronization/Baton.h>
+#include <folly/synchronization/RWSpinLock.h>
 
 #include <algorithm>
 #include <atomic>
@@ -206,14 +205,7 @@ class TypeDescriptor {
     return *this;
   }
 
-  std::string name() const {
-    auto ret = demangle(ti_.name());
-    if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
-      ret += "/";
-      ret += demangle(tag_ti_.name());
-    }
-    return ret.toStdString();
-  }
+  std::string name() const;
 
   friend class TypeDescriptorHasher;
 
@@ -233,6 +225,59 @@ class TypeDescriptorHasher {
   }
 };
 
+[[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
+    const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
+    const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
+    const TypeDescriptor& type);
+
+void singletonWarnDestroyInstanceLeak(
+    const TypeDescriptor& type,
+    const void* ptr);
+
+[[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
+    const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
+    const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
+    const TypeDescriptor& type);
+
+void singletonPrintDestructionStackTrace(const TypeDescriptor& type);
+
+[[noreturn]] void singletonThrowNullCreator(const std::type_info& type);
+
+[[noreturn]] void singletonThrowGetInvokedAfterDestruction(
+    const TypeDescriptor& type);
+
+struct SingletonVaultState {
+  // The two stages of life for a vault, as mentioned in the class comment.
+  enum class Type {
+    Running,
+    Quiescing,
+  };
+
+  Type state{Type::Running};
+  bool registrationComplete{false};
+
+  // Each singleton in the vault can be in two states: dead
+  // (registered but never created), living (CreateFunc returned an instance).
+
+  void check(
+      Type expected,
+      const char* msg = "Unexpected singleton state change") const {
+    if (expected != state) {
+      throwUnexpectedState(msg);
+    }
+  }
+
+  [[noreturn]] static void throwUnexpectedState(const char* msg);
+};
+
 // This interface is used by SingletonVault to interact with SingletonHolders.
 // Having a non-template interface allows SingletonVault to keep a list of all
 // SingletonHolders.
@@ -408,7 +453,7 @@ class SingletonVault {
    *   folly::IOThreadPoolExecutor executor(max_concurrency_level);
    *   folly::Baton<> done;
    *   doEagerInitVia(executor, &done);
-   *   done.wait();  // or 'timed_wait', or spin with 'try_wait'
+   *   done.wait();  // or 'try_wait_for', etc.
    *
    */
   void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
@@ -475,29 +520,6 @@ class SingletonVault {
   template <typename T>
   friend struct detail::SingletonHolder;
 
-  // The two stages of life for a vault, as mentioned in the class comment.
-  enum class SingletonVaultState {
-    Running,
-    Quiescing,
-  };
-
-  struct State {
-    SingletonVaultState state{SingletonVaultState::Running};
-    bool registrationComplete{false};
-  };
-
-  // Each singleton in the vault can be in two states: dead
-  // (registered but never created), living (CreateFunc returned an instance).
-
-  static void stateCheck(
-      SingletonVaultState expected,
-      const State& state,
-      const char* msg = "Unexpected singleton state change") {
-    if (expected != state.state) {
-      throw std::logic_error(msg);
-    }
-  }
-
   // This method only matters if registrationComplete() is never called.
   // Otherwise destroyInstances is scheduled to be executed atexit.
   //
@@ -514,15 +536,15 @@ class SingletonVault {
   typedef std::unordered_map<detail::TypeDescriptor,
                              detail::SingletonHolderBase*,
                              detail::TypeDescriptorHasher> SingletonMap;
-  folly::Synchronized<SingletonMap> singletons_;
-  folly::Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
+  Synchronized<SingletonMap> singletons_;
+  Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
       eagerInitSingletons_;
-  folly::Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
+  Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
 
   // Using SharedMutexReadPriority is important here, because we want to make
   // sure we don't block nested singleton creation happening concurrently with
   // destroyInstances().
-  folly::Synchronized<State, folly::SharedMutexReadPriority> state_;
+  Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_;
 
   Type type_;
 };
@@ -576,8 +598,7 @@ class Singleton {
   explicit Singleton(typename Singleton::CreateFunc c,
                      typename Singleton::TeardownFunc t = nullptr) {
     if (c == nullptr) {
-      throw std::logic_error(
-        "nullptr_t should be passed if you want T to be default constructed");
+      detail::singletonThrowNullCreator(typeid(T));
     }
 
     auto vault = SingletonVault::singleton<VaultTag>();
@@ -625,8 +646,7 @@ class Singleton {
   static void make_mock(CreateFunc c,
                         typename Singleton<T>::TeardownFunc t = nullptr) {
     if (c == nullptr) {
-      throw std::logic_error(
-        "nullptr_t should be passed if you want T to be default constructed");
+      detail::singletonThrowNullCreator(typeid(T));
     }
 
     auto& entry = getEntry();
@@ -660,9 +680,7 @@ class LeakySingleton {
   explicit LeakySingleton(CreateFunc createFunc) {
     auto& entry = entryInstance();
     if (entry.state != State::NotRegistered) {
-      LOG(FATAL) << "Double registration of singletons of the same "
-                 << "underlying type; check for multiple definitions "
-                 << "of type folly::LeakySingleton<" + entry.type_.name() + ">";
+      detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_);
     }
     entry.createFunc = createFunc;
     entry.state = State::Dead;
@@ -675,12 +693,11 @@ class LeakySingleton {
   }
 
   static void make_mock(CreateFunc createFunc) {
-    auto& entry = entryInstance();
     if (createFunc == nullptr) {
-      throw std::logic_error(
-          "nullptr_t should be passed if you want T to be default constructed");
+      detail::singletonThrowNullCreator(typeid(T));
     }
 
+    auto& entry = entryInstance();
     entry.createFunc = createFunc;
     entry.state = State::Dead;
   }
@@ -723,11 +740,7 @@ class LeakySingleton {
     }
 
     if (entry.state == State::NotRegistered) {
-      auto ptr = SingletonVault::stackTraceGetter().load();
-      LOG(FATAL) << "Creating instance for unregistered singleton: "
-                 << entry.type_.name() << "\n"
-                 << "Stacktrace:"
-                 << "\n" << (ptr ? (*ptr)() : "(not available)");
+      detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_);
     }
 
     entry.ptr = entry.createFunc();