1 /*
2  * Copyright 2015-present 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>
singleton()23 SingletonHolder<T>& SingletonHolder<T>::singleton() {
24   /* library-local */ static auto entry =
25       createGlobal<SingletonHolder<T>, std::pair<Tag, VaultTag>>([]() {
26         return new SingletonHolder<T>(
27             {typeid(T), typeid(Tag)}, *SingletonVault::singleton<VaultTag>());
28       });
29   return *entry;
30 }
31 
32 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
33     const TypeDescriptor& type);
34 
35 template <typename T>
registerSingleton(CreateFunc c,TeardownFunc t)36 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
37   std::lock_guard<std::mutex> entry_lock(mutex_);
38 
39   if (state_ != SingletonHolderState::NotRegistered) {
40     /* Possible causes:
41      *
42      * You have two instances of the same
43      * folly::Singleton<Class>. Probably because you define the
44      * singleton in a header included in multiple places? In general,
45      * folly::Singleton shouldn't be in the header, only off in some
46      * anonymous namespace in a cpp file. Code needing the singleton
47      * will find it when that code references folly::Singleton<Class>.
48      *
49      * Alternatively, you could have 2 singletons with the same type
50      * defined with a different name in a .cpp (source) file. For
51      * example:
52      *
53      * Singleton<int> a([] { return new int(3); });
54      * Singleton<int> b([] { return new int(4); });
55      *
56      */
57     singletonWarnDoubleRegistrationAndAbort(type());
58   }
59 
60   create_ = std::move(c);
61   teardown_ = std::move(t);
62 
63   state_ = SingletonHolderState::Dead;
64 }
65 
66 template <typename T>
registerSingletonMock(CreateFunc c,TeardownFunc t)67 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
68   if (state_ == SingletonHolderState::NotRegistered) {
69     detail::singletonWarnRegisterMockEarlyAndAbort(type());
70   }
71   if (state_ == SingletonHolderState::Living) {
72     destroyInstance();
73   }
74 
75   {
76     auto creationOrder = vault_.creationOrder_.wlock();
77 
78     auto it = std::find(creationOrder->begin(), creationOrder->end(), type());
79     if (it != creationOrder->end()) {
80       creationOrder->erase(it);
81     }
82   }
83 
84   std::lock_guard<std::mutex> entry_lock(mutex_);
85 
86   create_ = std::move(c);
87   teardown_ = std::move(t);
88 }
89 
90 template <typename T>
get()91 T* SingletonHolder<T>::get() {
92   if (LIKELY(
93           state_.load(std::memory_order_acquire) ==
94           SingletonHolderState::Living)) {
95     return instance_ptr_;
96   }
97   createInstance();
98 
99   if (instance_weak_.expired()) {
100     detail::singletonThrowGetInvokedAfterDestruction(type());
101   }
102 
103   return instance_ptr_;
104 }
105 
106 template <typename T>
get_weak()107 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
108   if (UNLIKELY(
109           state_.load(std::memory_order_acquire) !=
110           SingletonHolderState::Living)) {
111     createInstance();
112   }
113 
114   return instance_weak_;
115 }
116 
117 template <typename T>
try_get()118 std::shared_ptr<T> SingletonHolder<T>::try_get() {
119   if (UNLIKELY(
120           state_.load(std::memory_order_acquire) !=
121           SingletonHolderState::Living)) {
122     createInstance();
123   }
124 
125   return instance_weak_.lock();
126 }
127 
128 template <typename T>
try_get_fast()129 folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
130   if (UNLIKELY(
131           state_.load(std::memory_order_acquire) !=
132           SingletonHolderState::Living)) {
133     createInstance();
134   }
135 
136   return instance_weak_fast_.lock();
137 }
138 
139 template <typename T>
vivify()140 void SingletonHolder<T>::vivify() {
141   if (UNLIKELY(
142           state_.load(std::memory_order_relaxed) !=
143           SingletonHolderState::Living)) {
144     createInstance();
145   }
146 }
147 
148 template <typename T>
hasLiveInstance()149 bool SingletonHolder<T>::hasLiveInstance() {
150   return !instance_weak_.expired();
151 }
152 
153 template <typename T>
preDestroyInstance(ReadMostlyMainPtrDeleter<> & deleter)154 void SingletonHolder<T>::preDestroyInstance(
155     ReadMostlyMainPtrDeleter<>& deleter) {
156   instance_copy_ = instance_;
157   deleter.add(std::move(instance_));
158 }
159 
160 template <typename T>
destroyInstance()161 void SingletonHolder<T>::destroyInstance() {
162   state_ = SingletonHolderState::Dead;
163   instance_.reset();
164   instance_copy_.reset();
165   if (destroy_baton_) {
166     constexpr std::chrono::seconds kDestroyWaitTime{5};
167     auto last_reference_released =
168         destroy_baton_->try_wait_for(kDestroyWaitTime);
169     if (last_reference_released) {
170       teardown_(instance_ptr_);
171     } else {
172       print_destructor_stack_trace_->store(true);
173       detail::singletonWarnDestroyInstanceLeak(type(), instance_ptr_);
174     }
175   }
176 }
177 
178 template <typename T>
SingletonHolder(TypeDescriptor typeDesc,SingletonVault & vault)179 SingletonHolder<T>::SingletonHolder(
180     TypeDescriptor typeDesc,
181     SingletonVault& vault)
182     : SingletonHolderBase(typeDesc), vault_(vault) {}
183 
184 template <typename T>
creationStarted()185 bool SingletonHolder<T>::creationStarted() {
186   // If alive, then creation was of course started.
187   // This is flipped after creating_thread_ was set, and before it was reset.
188   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
189     return true;
190   }
191 
192   // Not yet built.  Is it currently in progress?
193   if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
194     return true;
195   }
196 
197   return false;
198 }
199 
200 template <typename T>
createInstance()201 void SingletonHolder<T>::createInstance() {
202   if (creating_thread_.load(std::memory_order_acquire) ==
203       std::this_thread::get_id()) {
204     detail::singletonWarnCreateCircularDependencyAndAbort(type());
205   }
206 
207   std::lock_guard<std::mutex> entry_lock(mutex_);
208   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
209     return;
210   }
211   if (state_.load(std::memory_order_acquire) ==
212       SingletonHolderState::NotRegistered) {
213     detail::singletonWarnCreateUnregisteredAndAbort(type());
214   }
215 
216   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
217     return;
218   }
219 
220   SCOPE_EXIT {
221     // Clean up creator thread when complete, and also, in case of errors here,
222     // so that subsequent attempts don't think this is still in the process of
223     // being built.
224     creating_thread_.store(std::thread::id(), std::memory_order_release);
225   };
226 
227   creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
228 
229   auto state = vault_.state_.rlock();
230   if (vault_.type_ != SingletonVault::Type::Relaxed &&
231       !state->registrationComplete) {
232     detail::singletonWarnCreateBeforeRegistrationCompleteAndAbort(type());
233   }
234   if (state->state == detail::SingletonVaultState::Type::Quiescing) {
235     return;
236   }
237 
238   auto destroy_baton = std::make_shared<folly::Baton<>>();
239   auto print_destructor_stack_trace =
240       std::make_shared<std::atomic<bool>>(false);
241 
242   // Can't use make_shared -- no support for a custom deleter, sadly.
243   std::shared_ptr<T> instance(
244       create_(),
245       [destroy_baton, print_destructor_stack_trace, type = type()](T*) mutable {
246         destroy_baton->post();
247         if (print_destructor_stack_trace->load()) {
248           detail::singletonPrintDestructionStackTrace(type);
249         }
250       });
251 
252   // We should schedule destroyInstances() only after the singleton was
253   // created. This will ensure it will be destroyed before singletons,
254   // not managed by folly::Singleton, which were initialized in its
255   // constructor
256   SingletonVault::scheduleDestroyInstances();
257 
258   instance_weak_ = instance;
259   instance_ptr_ = instance.get();
260   instance_.reset(std::move(instance));
261   instance_weak_fast_ = instance_;
262 
263   destroy_baton_ = std::move(destroy_baton);
264   print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
265 
266   // This has to be the last step, because once state is Living other threads
267   // may access instance and instance_weak w/o synchronization.
268   state_.store(SingletonHolderState::Living, std::memory_order_release);
269 
270   vault_.creationOrder_.wlock()->push_back(type());
271 }
272 
273 } // namespace detail
274 
275 } // namespace folly
276