text
stringlengths
0
2.2M
[[noreturn]] void singletonThrowGetInvokedAfterDestruction(
const TypeDescriptor& type) {
throw std::runtime_error(
"Raw pointer to a singleton requested after its destruction."
" Singleton type is: " +
type.name());
}
// clang-format on
} // namespace detail
namespace {
struct FatalHelper {
~FatalHelper() {
if (!leakedSingletons_.empty()) {
std::string leakedTypes;
for (const auto& singleton : leakedSingletons_) {
leakedTypes += "\t" + singleton.name() + "\n";
}
LOG(DFATAL) << "Singletons of the following types had living references "
<< "after destroyInstances was finished:\n"
<< leakedTypes
<< "beware! It is very likely that those singleton instances "
<< "are leaked.";
}
}
std::vector<detail::TypeDescriptor> leakedSingletons_;
};
#if defined(__APPLE__) || defined(_MSC_VER)
// OS X doesn't support constructor priorities.
FatalHelper fatalHelper;
#else
FatalHelper __attribute__((__init_priority__(101))) fatalHelper;
#endif
} // namespace
SingletonVault::SingletonVault(Type type) noexcept : type_(type) {
AtFork::registerHandler(
this,
/*prepare*/
[this]() {
auto singletons = singletons_.rlock();
auto creationOrder = creationOrder_.rlock();
CHECK_GE(singletons->size(), creationOrder->size());
for (const auto& singletonType : *creationOrder) {
liveSingletonsPreFork_.insert(singletons->at(singletonType));
}
return true;
},
/*parent*/ [this]() { liveSingletonsPreFork_.clear(); },
/*child*/
[this]() {
for (auto singleton : liveSingletonsPreFork_) {
singleton->inChildAfterFork();
}
liveSingletonsPreFork_.clear();
});
}
SingletonVault::~SingletonVault() {
AtFork::unregisterHandler(this);
destroyInstances();
}
void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(state->registrationComplete) &&
type_.load(std::memory_order_relaxed) == Type::Strict) {
LOG(ERROR) << "Registering singleton after registrationComplete().";
}
auto singletons = singletons_.wlock();
CHECK_THROW(
singletons->emplace(entry->type(), entry).second, std::logic_error);
}
void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(state->registrationComplete) &&
type_.load(std::memory_order_relaxed) == Type::Strict) {
LOG(ERROR) << "Registering for eager-load after registrationComplete().";
}
CHECK_THROW(singletons_.rlock()->count(entry->type()), std::logic_error);
auto eagerInitSingletons = eagerInitSingletons_.wlock();
eagerInitSingletons->insert(entry);
}