Fix folly::Singleton to work in dynamically linked binaries
[folly.git] / folly / Singleton-inl.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 namespace folly {
18
19 namespace detail {
20
21 template <typename T>
22 template <typename Tag, typename VaultTag>
23 SingletonHolder<T>& SingletonHolder<T>::singleton() {
24   static auto entry =
25       createGlobal<SingletonHolder<T>, std::pair<Tag, VaultTag>>([]() {
26         return new SingletonHolder<T>({typeid(T), typeid(Tag)},
27                                       *SingletonVault::singleton<VaultTag>());
28       });
29   return *entry;
30 }
31
32 template <typename T>
33 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
34   std::lock_guard<std::mutex> entry_lock(mutex_);
35
36   if (state_ != SingletonHolderState::NotRegistered) {
37     /* Possible causes:
38      *
39      * You have two instances of the same
40      * folly::Singleton<Class>. Probably because you define the
41      * singleton in a header included in multiple places? In general,
42      * folly::Singleton shouldn't be in the header, only off in some
43      * anonymous namespace in a cpp file. Code needing the singleton
44      * will find it when that code references folly::Singleton<Class>.
45      *
46      * Alternatively, you could have 2 singletons with the same type
47      * defined with a different name in a .cpp (source) file. For
48      * example:
49      *
50      * Singleton<int> a([] { return new int(3); });
51      * Singleton<int> b([] { return new int(4); });
52      *
53      */
54     LOG(FATAL) << "Double registration of singletons of the same "
55                << "underlying type; check for multiple definitions "
56                << "of type folly::Singleton<" + type_.name() + ">";
57   }
58
59   create_ = std::move(c);
60   teardown_ = std::move(t);
61
62   state_ = SingletonHolderState::Dead;
63 }
64
65 template <typename T>
66 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
67   if (state_ == SingletonHolderState::NotRegistered) {
68     LOG(FATAL)
69         << "Registering mock before singleton was registered: " << type_.name();
70   }
71   destroyInstance();
72
73   std::lock_guard<std::mutex> entry_lock(mutex_);
74
75   create_ = std::move(c);
76   teardown_ = std::move(t);
77 }
78
79 template <typename T>
80 T* SingletonHolder<T>::get() {
81   if (LIKELY(state_.load(std::memory_order_acquire) ==
82              SingletonHolderState::Living)) {
83     return instance_ptr_;
84   }
85   createInstance();
86
87   if (instance_weak_.expired()) {
88     throw std::runtime_error(
89         "Raw pointer to a singleton requested after its destruction."
90         " Singleton type is: " +
91         type_.name());
92   }
93
94   return instance_ptr_;
95 }
96
97 template <typename T>
98 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
99   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
100                SingletonHolderState::Living)) {
101     createInstance();
102   }
103
104   return instance_weak_;
105 }
106
107 template <typename T>
108 std::shared_ptr<T> SingletonHolder<T>::try_get() {
109   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
110                SingletonHolderState::Living)) {
111     createInstance();
112   }
113
114   return instance_weak_.lock();
115 }
116
117 template <typename T>
118 folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
119   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
120                SingletonHolderState::Living)) {
121     createInstance();
122   }
123
124   return instance_weak_fast_.lock();
125 }
126
127 template <typename T>
128 TypeDescriptor SingletonHolder<T>::type() {
129   return type_;
130 }
131
132 template <typename T>
133 bool SingletonHolder<T>::hasLiveInstance() {
134   return !instance_weak_.expired();
135 }
136
137 template <typename T>
138 void SingletonHolder<T>::destroyInstance() {
139   state_ = SingletonHolderState::Dead;
140   instance_.reset();
141   if (destroy_baton_) {
142     auto wait_result = destroy_baton_->timed_wait(
143       std::chrono::steady_clock::now() + kDestroyWaitTime);
144     if (!wait_result) {
145       print_destructor_stack_trace_->store(true);
146       LOG(ERROR) << "Singleton of type " << type_.name() << " has a "
147                  << "living reference at destroyInstances time; beware! Raw "
148                  << "pointer is " << instance_ptr_ << ". It is very likely "
149                  << "that some other singleton is holding a shared_ptr to it. "
150                  << "Make sure dependencies between these singletons are "
151                  << "properly defined.";
152     }
153   }
154 }
155
156 template <typename T>
157 SingletonHolder<T>::SingletonHolder(TypeDescriptor type__,
158                                     SingletonVault& vault) :
159     type_(type__), vault_(vault) {
160 }
161
162 template <typename T>
163 bool SingletonHolder<T>::creationStarted() {
164   // If alive, then creation was of course started.
165   // This is flipped after creating_thread_ was set, and before it was reset.
166   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
167     return true;
168   }
169
170   // Not yet built.  Is it currently in progress?
171   if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
172     return true;
173   }
174
175   return false;
176 }
177
178 template <typename T>
179 void SingletonHolder<T>::createInstance() {
180   if (creating_thread_.load(std::memory_order_acquire) ==
181         std::this_thread::get_id()) {
182     LOG(FATAL) << "circular singleton dependency: " << type_.name();
183   }
184
185   std::lock_guard<std::mutex> entry_lock(mutex_);
186   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
187     return;
188   }
189   if (state_.load(std::memory_order_acquire) ==
190         SingletonHolderState::NotRegistered) {
191     auto ptr = SingletonVault::stackTraceGetter().load();
192     LOG(FATAL) << "Creating instance for unregistered singleton: "
193                << type_.name() << "\n"
194                << "Stacktrace:"
195                << "\n" << (ptr ? (*ptr)() : "(not available)");
196   }
197
198   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
199     return;
200   }
201
202   SCOPE_EXIT {
203     // Clean up creator thread when complete, and also, in case of errors here,
204     // so that subsequent attempts don't think this is still in the process of
205     // being built.
206     creating_thread_.store(std::thread::id(), std::memory_order_release);
207   };
208
209   creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
210
211   RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
212   if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
213     return;
214   }
215
216   auto destroy_baton = std::make_shared<folly::Baton<>>();
217   auto print_destructor_stack_trace =
218     std::make_shared<std::atomic<bool>>(false);
219   auto teardown = teardown_;
220   auto type_name = type_.name();
221
222   // Can't use make_shared -- no support for a custom deleter, sadly.
223   std::shared_ptr<T> instance(
224     create_(),
225     [destroy_baton, print_destructor_stack_trace, teardown, type_name]
226     (T* instance_ptr) mutable {
227       teardown(instance_ptr);
228       destroy_baton->post();
229       if (print_destructor_stack_trace->load()) {
230         std::string output = "Singleton " + type_name + " was destroyed.\n";
231
232         auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
233         auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
234         if (stack_trace.empty()) {
235           output += "Failed to get destructor stack trace.";
236         } else {
237           output += "Destructor stack trace:\n";
238           output += stack_trace;
239         }
240
241         LOG(ERROR) << output;
242       }
243     });
244
245   // We should schedule destroyInstances() only after the singleton was
246   // created. This will ensure it will be destroyed before singletons,
247   // not managed by folly::Singleton, which were initialized in its
248   // constructor
249   SingletonVault::scheduleDestroyInstances();
250
251   instance_weak_ = instance;
252   instance_ptr_ = instance.get();
253   instance_.reset(std::move(instance));
254   instance_weak_fast_ = instance_;
255
256   destroy_baton_ = std::move(destroy_baton);
257   print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
258
259   // This has to be the last step, because once state is Living other threads
260   // may access instance and instance_weak w/o synchronization.
261   state_.store(SingletonHolderState::Living, std::memory_order_release);
262
263   {
264     RWSpinLock::WriteHolder wh(&vault_.mutex_);
265     vault_.creation_order_.push_back(type_);
266   }
267 }
268
269 }
270
271 }