fix bootstrap on osx
[folly.git] / folly / Singleton.cpp
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 #include <folly/Singleton.h>
18
19 #include <atomic>
20 #include <cstdio>
21 #include <cstdlib>
22 #include <iostream>
23 #include <string>
24
25 #include <folly/ScopeGuard.h>
26
27 namespace folly {
28
29 namespace detail {
30
31 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
32     const TypeDescriptor& type) {
33   // Ensure the availability of std::cerr
34   std::ios_base::Init ioInit;
35   std::cerr << "Double registration of singletons of the same "
36                "underlying type; check for multiple definitions "
37                "of type folly::Singleton<"
38             << type.name() << ">\n";
39   std::abort();
40 }
41 }
42
43 namespace {
44
45 struct FatalHelper {
46   ~FatalHelper() {
47     if (!leakedSingletons_.empty()) {
48       std::string leakedTypes;
49       for (const auto& singleton : leakedSingletons_) {
50         leakedTypes += "\t" + singleton.name() + "\n";
51       }
52       LOG(DFATAL) << "Singletons of the following types had living references "
53                   << "after destroyInstances was finished:\n" << leakedTypes
54                   << "beware! It is very likely that those singleton instances "
55                   << "are leaked.";
56     }
57   }
58
59   std::vector<detail::TypeDescriptor> leakedSingletons_;
60 };
61
62 #if defined(__APPLE__) || defined(_MSC_VER)
63 // OS X doesn't support constructor priorities.
64 FatalHelper fatalHelper;
65 #else
66 FatalHelper __attribute__ ((__init_priority__ (101))) fatalHelper;
67 #endif
68
69 }
70
71 SingletonVault::~SingletonVault() { destroyInstances(); }
72
73 void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
74   auto state = state_.rlock();
75   stateCheck(SingletonVaultState::Running, *state);
76
77   if (UNLIKELY(state->registrationComplete)) {
78     LOG(ERROR) << "Registering singleton after registrationComplete().";
79   }
80
81   auto singletons = singletons_.wlock();
82   CHECK_THROW(
83       singletons->emplace(entry->type(), entry).second, std::logic_error);
84 }
85
86 void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
87   auto state = state_.rlock();
88   stateCheck(SingletonVaultState::Running, *state);
89
90   if (UNLIKELY(state->registrationComplete)) {
91     LOG(ERROR) << "Registering for eager-load after registrationComplete().";
92   }
93
94   CHECK_THROW(singletons_.rlock()->count(entry->type()), std::logic_error);
95
96   auto eagerInitSingletons = eagerInitSingletons_.wlock();
97   eagerInitSingletons->insert(entry);
98 }
99
100 void SingletonVault::registrationComplete() {
101   std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
102
103   auto state = state_.wlock();
104   stateCheck(SingletonVaultState::Running, *state);
105
106   auto singletons = singletons_.rlock();
107   if (type_ == Type::Strict) {
108     for (const auto& p : *singletons) {
109       if (p.second->hasLiveInstance()) {
110         throw std::runtime_error(
111             "Singleton created before registration was complete.");
112       }
113     }
114   }
115
116   state->registrationComplete = true;
117 }
118
119 void SingletonVault::doEagerInit() {
120   {
121     auto state = state_.rlock();
122     stateCheck(SingletonVaultState::Running, *state);
123     if (UNLIKELY(!state->registrationComplete)) {
124       throw std::logic_error("registrationComplete() not yet called");
125     }
126   }
127
128   auto eagerInitSingletons = eagerInitSingletons_.rlock();
129   for (auto* single : *eagerInitSingletons) {
130     single->createInstance();
131   }
132 }
133
134 void SingletonVault::doEagerInitVia(Executor& exe, folly::Baton<>* done) {
135   {
136     auto state = state_.rlock();
137     stateCheck(SingletonVaultState::Running, *state);
138     if (UNLIKELY(!state->registrationComplete)) {
139       throw std::logic_error("registrationComplete() not yet called");
140     }
141   }
142
143   auto eagerInitSingletons = eagerInitSingletons_.rlock();
144   auto countdown =
145       std::make_shared<std::atomic<size_t>>(eagerInitSingletons->size());
146   for (auto* single : *eagerInitSingletons) {
147     // countdown is retained by shared_ptr, and will be alive until last lambda
148     // is done.  notifyBaton is provided by the caller, and expected to remain
149     // present (if it's non-nullptr).  singletonSet can go out of scope but
150     // its values, which are SingletonHolderBase pointers, are alive as long as
151     // SingletonVault is not being destroyed.
152     exe.add([=] {
153       // decrement counter and notify if requested, whether initialization
154       // was successful, was skipped (already initialized), or exception thrown.
155       SCOPE_EXIT {
156         if (--(*countdown) == 0) {
157           if (done != nullptr) {
158             done->post();
159           }
160         }
161       };
162       // if initialization is in progress in another thread, don't try to init
163       // here.  Otherwise the current thread will block on 'createInstance'.
164       if (!single->creationStarted()) {
165         single->createInstance();
166       }
167     });
168   }
169 }
170
171 void SingletonVault::destroyInstances() {
172   auto stateW = state_.wlock();
173   if (stateW->state == SingletonVaultState::Quiescing) {
174     return;
175   }
176   stateW->state = SingletonVaultState::Quiescing;
177
178   auto stateR = stateW.moveFromWriteToRead();
179   {
180     auto singletons = singletons_.rlock();
181     auto creationOrder = creationOrder_.rlock();
182
183     CHECK_GE(singletons->size(), creationOrder->size());
184
185     // Release all ReadMostlyMainPtrs at once
186     {
187       ReadMostlyMainPtrDeleter<> deleter;
188       for (auto& singleton_type : *creationOrder) {
189         singletons->at(singleton_type)->preDestroyInstance(deleter);
190       }
191     }
192
193     for (auto type_iter = creationOrder->rbegin();
194          type_iter != creationOrder->rend();
195          ++type_iter) {
196       singletons->at(*type_iter)->destroyInstance();
197     }
198
199     for (auto& singleton_type : *creationOrder) {
200       auto singleton = singletons->at(singleton_type);
201       if (!singleton->hasLiveInstance()) {
202         continue;
203       }
204
205       fatalHelper.leakedSingletons_.push_back(singleton->type());
206     }
207   }
208
209   {
210     auto creationOrder = creationOrder_.wlock();
211     creationOrder->clear();
212   }
213 }
214
215 void SingletonVault::reenableInstances() {
216   auto state = state_.wlock();
217
218   stateCheck(SingletonVaultState::Quiescing, *state);
219
220   state->state = SingletonVaultState::Running;
221 }
222
223 void SingletonVault::scheduleDestroyInstances() {
224   // Add a dependency on folly::ThreadLocal to make sure all its static
225   // singletons are initalized first.
226   threadlocal_detail::StaticMeta<void, void>::instance();
227
228   class SingletonVaultDestructor {
229    public:
230     ~SingletonVaultDestructor() {
231       SingletonVault::singleton()->destroyInstances();
232     }
233   };
234
235   // Here we intialize a singleton, which calls destroyInstances in its
236   // destructor. Because of singleton destruction order - it will be destroyed
237   // before all the singletons, which were initialized before it and after all
238   // the singletons initialized after it.
239   static SingletonVaultDestructor singletonVaultDestructor;
240 }
241
242 }