2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/Singleton.h>
29 #include <folly/ScopeGuard.h>
31 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
32 static void hs_init_weak(int* argc, char** argv[])
33 __attribute__((__weakref__("hs_init")));
38 SingletonVault::Type SingletonVault::defaultVaultType() {
39 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
40 bool isPython = dlsym(RTLD_DEFAULT, "Py_Main");
41 bool isHaskel = &::hs_init_weak || dlsym(RTLD_DEFAULT, "hs_init");
42 bool isJVM = dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs");
43 bool isD = dlsym(RTLD_DEFAULT, "_d_run_main");
45 return isPython || isHaskel || isJVM || isD ? Type::Relaxed : Type::Strict;
53 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
54 const TypeDescriptor& type) {
55 // Ensure the availability of std::cerr
56 std::ios_base::Init ioInit;
57 std::cerr << "Double registration of singletons of the same "
58 "underlying type; check for multiple definitions "
59 "of type folly::Singleton<"
60 << type.name() << ">\n";
69 if (!leakedSingletons_.empty()) {
70 std::string leakedTypes;
71 for (const auto& singleton : leakedSingletons_) {
72 leakedTypes += "\t" + singleton.name() + "\n";
74 LOG(DFATAL) << "Singletons of the following types had living references "
75 << "after destroyInstances was finished:\n" << leakedTypes
76 << "beware! It is very likely that those singleton instances "
81 std::vector<detail::TypeDescriptor> leakedSingletons_;
84 #if defined(__APPLE__) || defined(_MSC_VER)
85 // OS X doesn't support constructor priorities.
86 FatalHelper fatalHelper;
88 FatalHelper __attribute__ ((__init_priority__ (101))) fatalHelper;
93 SingletonVault::~SingletonVault() { destroyInstances(); }
95 void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
96 auto state = state_.rlock();
97 stateCheck(SingletonVaultState::Running, *state);
99 if (UNLIKELY(state->registrationComplete)) {
100 LOG(ERROR) << "Registering singleton after registrationComplete().";
103 auto singletons = singletons_.wlock();
105 singletons->emplace(entry->type(), entry).second, std::logic_error);
108 void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
109 auto state = state_.rlock();
110 stateCheck(SingletonVaultState::Running, *state);
112 if (UNLIKELY(state->registrationComplete)) {
113 LOG(ERROR) << "Registering for eager-load after registrationComplete().";
116 CHECK_THROW(singletons_.rlock()->count(entry->type()), std::logic_error);
118 auto eagerInitSingletons = eagerInitSingletons_.wlock();
119 eagerInitSingletons->insert(entry);
122 void SingletonVault::registrationComplete() {
123 std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
125 auto state = state_.wlock();
126 stateCheck(SingletonVaultState::Running, *state);
128 if (state->registrationComplete) {
132 auto singletons = singletons_.rlock();
133 if (type_ == Type::Strict) {
134 for (const auto& p : *singletons) {
135 if (p.second->hasLiveInstance()) {
136 throw std::runtime_error(
137 "Singleton " + p.first.name() +
138 " created before registration was complete.");
143 state->registrationComplete = true;
146 void SingletonVault::doEagerInit() {
148 auto state = state_.rlock();
149 stateCheck(SingletonVaultState::Running, *state);
150 if (UNLIKELY(!state->registrationComplete)) {
151 throw std::logic_error("registrationComplete() not yet called");
155 auto eagerInitSingletons = eagerInitSingletons_.rlock();
156 for (auto* single : *eagerInitSingletons) {
157 single->createInstance();
161 void SingletonVault::doEagerInitVia(Executor& exe, folly::Baton<>* done) {
163 auto state = state_.rlock();
164 stateCheck(SingletonVaultState::Running, *state);
165 if (UNLIKELY(!state->registrationComplete)) {
166 throw std::logic_error("registrationComplete() not yet called");
170 auto eagerInitSingletons = eagerInitSingletons_.rlock();
172 std::make_shared<std::atomic<size_t>>(eagerInitSingletons->size());
173 for (auto* single : *eagerInitSingletons) {
174 // countdown is retained by shared_ptr, and will be alive until last lambda
175 // is done. notifyBaton is provided by the caller, and expected to remain
176 // present (if it's non-nullptr). singletonSet can go out of scope but
177 // its values, which are SingletonHolderBase pointers, are alive as long as
178 // SingletonVault is not being destroyed.
180 // decrement counter and notify if requested, whether initialization
181 // was successful, was skipped (already initialized), or exception thrown.
183 if (--(*countdown) == 0) {
184 if (done != nullptr) {
189 // if initialization is in progress in another thread, don't try to init
190 // here. Otherwise the current thread will block on 'createInstance'.
191 if (!single->creationStarted()) {
192 single->createInstance();
198 void SingletonVault::destroyInstances() {
199 auto stateW = state_.wlock();
200 if (stateW->state == SingletonVaultState::Quiescing) {
203 stateW->state = SingletonVaultState::Quiescing;
205 auto stateR = stateW.moveFromWriteToRead();
207 auto singletons = singletons_.rlock();
208 auto creationOrder = creationOrder_.rlock();
210 CHECK_GE(singletons->size(), creationOrder->size());
212 // Release all ReadMostlyMainPtrs at once
214 ReadMostlyMainPtrDeleter<> deleter;
215 for (auto& singleton_type : *creationOrder) {
216 singletons->at(singleton_type)->preDestroyInstance(deleter);
220 for (auto type_iter = creationOrder->rbegin();
221 type_iter != creationOrder->rend();
223 singletons->at(*type_iter)->destroyInstance();
226 for (auto& singleton_type : *creationOrder) {
227 auto singleton = singletons->at(singleton_type);
228 if (!singleton->hasLiveInstance()) {
232 fatalHelper.leakedSingletons_.push_back(singleton->type());
237 auto creationOrder = creationOrder_.wlock();
238 creationOrder->clear();
242 void SingletonVault::reenableInstances() {
243 auto state = state_.wlock();
245 stateCheck(SingletonVaultState::Quiescing, *state);
247 state->state = SingletonVaultState::Running;
250 void SingletonVault::scheduleDestroyInstances() {
251 // Add a dependency on folly::ThreadLocal to make sure all its static
252 // singletons are initalized first.
253 threadlocal_detail::StaticMeta<void, void>::instance();
255 class SingletonVaultDestructor {
257 ~SingletonVaultDestructor() {
258 SingletonVault::singleton()->destroyInstances();
262 // Here we intialize a singleton, which calls destroyInstances in its
263 // destructor. Because of singleton destruction order - it will be destroyed
264 // before all the singletons, which were initialized before it and after all
265 // the singletons initialized after it.
266 static SingletonVaultDestructor singletonVaultDestructor;