diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 28223e4e0b..86715572eb 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -13,6 +13,8 @@ on: env: CCACHE_DIR: ${{ github.workspace }}/ccache_dir GITHUB_TOKEN: ${{ github.token }} + # Fail Clang builds on SDK statics that need an exit-time destructor. + FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS: 1 xcodeVersion: "26.4" # Only affects Mac runners, and only for prerequisites. permissions: diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 05b5e4ef14..dac618b9d3 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -13,6 +13,8 @@ on: env: CCACHE_DIR: ${{ github.workspace }}/ccache_dir GITHUB_TOKEN: ${{ github.token }} + # Fail Clang builds on SDK statics that need an exit-time destructor. + FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS: 1 permissions: contents: read @@ -228,6 +230,13 @@ jobs: find build -name "*.a" find build -name "*.so" + # Linux builds use GCC, which has no -Wexit-time-destructors. + - name: Check firebase libraries for exit-time destructors (linux) + if: startsWith(matrix.os, 'ubuntu') + shell: bash + run: | + python scripts/gha/check_exit_time_destructors.py build/ + - name: Inspect firebase libraries for cpu arch and msvc runtime. shell: bash run: | diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 281c8d835a..cb2325a090 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -12,6 +12,8 @@ on: env: GITHUB_TOKEN: ${{ github.token }} + # Fail Clang builds on SDK statics that need an exit-time destructor. + FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS: 1 permissions: contents: read diff --git a/CMakeLists.txt b/CMakeLists.txt index 36dae1d520..c7a337027d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -79,6 +79,17 @@ option(FIREBASE_USE_LINUX_CXX11_ABI option(FIREBASE_GITHUB_ACTION_BUILD "Indicates that this build was created from a GitHub Action" OFF) +# Defaults to the environment variable of the same name, which the CI +# workflows set, so the check reaches CMake however it is launched (build +# scripts, Gradle, Xcode). See cmake/exit_time_destructors.cmake. +set(firebase_werror_exit_time_destructors_default OFF) +if("$ENV{FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS}") + set(firebase_werror_exit_time_destructors_default ON) +endif() +option(FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS + "Treat exit-time destructors in SDK libraries as errors (Clang only)." + ${firebase_werror_exit_time_destructors_default}) + option(FIREBASE_QUICK_TEST "Enable quick tests will skip tests which requires access to the SECRET" OFF) @@ -116,6 +127,7 @@ endif() list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_LIST_DIR}/cmake) include(external_rules) include(cpp_pack) +include(exit_time_destructors) if(FIREBASE_CPP_BUILD_TESTS OR FIREBASE_CPP_BUILD_STUB_TESTS) enable_testing() diff --git a/analytics/CMakeLists.txt b/analytics/CMakeLists.txt index f45af19e64..ebdb455f7d 100644 --- a/analytics/CMakeLists.txt +++ b/analytics/CMakeLists.txt @@ -130,6 +130,8 @@ target_compile_definitions(firebase_analytics -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_analytics) + if(ANDROID) diff --git a/analytics/src/analytics_desktop.cc b/analytics/src/analytics_desktop.cc index 6fc3625173..492a633c85 100644 --- a/analytics/src/analytics_desktop.cc +++ b/analytics/src/analytics_desktop.cc @@ -28,6 +28,7 @@ #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/variant.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "firebase/log.h" #if defined(_WIN32) @@ -48,12 +49,29 @@ static HMODULE g_analytics_module = 0; // Future data for analytics. // This is initialized in `Initialize()` and cleaned up in `Terminate()`. static bool g_initialized = false; -static LogCallback g_log_callback; -static std::mutex g_log_callback_mutex; + +static LogCallback& GetLogCallback() { + static NoDestructor log_callback; + return *log_callback; +} + +static std::mutex& LogCallbackMutex() { + static NoDestructor log_callback_mutex; + return *log_callback_mutex; +} + static int g_fake_instance_id = 0; static bool g_analytics_collection_enabled = true; -static std::string g_app_id; -static std::string g_package_name; + +static std::string& AppId() { + static NoDestructor app_id; + return *app_id; +} + +static std::string& PackageName() { + static NoDestructor package_name; + return *package_name; +} // Initializes the Analytics desktop API. // This function must be called before any other Analytics methods. @@ -91,15 +109,15 @@ void Initialize(const App& app) { LogInfo("Analytics: Loaded Google Analytics module."); // Initialize Google Analytics C API - g_app_id = app.options().app_id(); - g_package_name = app.options().package_name(); + AppId() = app.options().app_id(); + PackageName() = app.options().package_name(); GoogleAnalytics_Options* c_options = GoogleAnalytics_Options_Create(); if (!c_options) { LogError("Analytics: Failed to create GoogleAnalytics_Options."); } else { - c_options->app_id = g_app_id.c_str(); - c_options->package_name = g_package_name.c_str(); + c_options->app_id = AppId().c_str(); + c_options->package_name = PackageName().c_str(); c_options->analytics_collection_enabled_at_first_launch = g_analytics_collection_enabled; @@ -416,8 +434,8 @@ void GoogleAnalyticsWrapperLogCallback(int32_t log_level, const char* message) { LogCallback callback_to_call; { - std::lock_guard lock(g_log_callback_mutex); - callback_to_call = g_log_callback; + std::lock_guard lock(LogCallbackMutex()); + callback_to_call = GetLogCallback(); } if (callback_to_call) { @@ -433,8 +451,8 @@ void SetLogCallback(const LogCallback& callback) { FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized()); // The C API does not support user data, so we must use a global variable. { - std::lock_guard lock(g_log_callback_mutex); - g_log_callback = callback; + std::lock_guard lock(LogCallbackMutex()); + GetLogCallback() = callback; } if (callback) { GoogleAnalytics_SetLogCallback(GoogleAnalyticsWrapperLogCallback); diff --git a/analytics/src/analytics_ios.mm b/analytics/src/analytics_ios.mm index e064faa665..9c0fe568c4 100644 --- a/analytics/src/analytics_ios.mm +++ b/analytics/src/analytics_ios.mm @@ -32,6 +32,7 @@ #include "app/src/include/firebase/internal/mutex.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/thread.h" #include "app/src/time.h" #include "app/src/util.h" @@ -120,13 +121,16 @@ uint64_t GetResetTimeElapsedMilliseconds() const { const uint64_t AnalyticsDataResetter::kResetTimeoutMilliseconds = 5000; static const double kMillisecondsPerSecond = 1000.0; -static Mutex g_mutex; // NOLINT +static Mutex& AnalyticsMutex() { + static NoDestructor mutex; + return *mutex; +} static bool g_initialized = false; static AnalyticsDataResetter* g_resetter = nullptr; // Initialize the API. void Initialize(const ::firebase::App& app) { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); g_initialized = true; g_resetter = new AnalyticsDataResetter(); internal::RegisterTerminateOnDefaultAppDestroy(); @@ -142,7 +146,7 @@ void Initialize(const ::firebase::App& app) { // Terminate the API. void Terminate() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); internal::FutureData::Destroy(); internal::UnregisterTerminateOnDefaultAppDestroy(); delete g_resetter; @@ -237,7 +241,7 @@ void LogEvent(const char* name) { } Future LogAppleTransaction(const char* transaction_id) { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); auto* api = internal::FutureData::Get()->api(); @@ -251,7 +255,7 @@ void LogEvent(const char* name) { [AppleTransactionVerifier verifyWithTransactionId:SafeString(transaction_id) completion:^(BOOL isFound) { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); if (!internal::IsInitialized()) return; auto* api = internal::FutureData::Get()->api(); @@ -266,7 +270,7 @@ void LogEvent(const char* name) { } Future LogAppleTransactionLastResult() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); return static_cast&>( internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnLogAppleTransaction)); @@ -449,7 +453,7 @@ void SetSessionTimeoutDuration(int64_t milliseconds) { } void ResetAnalyticsData() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized()); g_resetter->Reset(); } @@ -467,7 +471,7 @@ void NotifyAppLifecycleChange(AppLifecycleState) {} void SetDesktopDebugMode(bool) {} Future GetAnalyticsInstanceId() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); auto* api = internal::FutureData::Get()->api(); const auto future_handle = @@ -477,7 +481,7 @@ Thread get_id_thread( [](SafeFutureHandle* handle) { for (;;) { { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); if (!internal::IsInitialized()) break; std::string instance_id = g_resetter->GetInstanceId(); if (!instance_id.empty()) { @@ -495,19 +499,19 @@ Thread get_id_thread( } Future GetAnalyticsInstanceIdLastResult() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); return static_cast&>( internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnGetAnalyticsInstanceId)); } Future GetSessionId() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); auto* api = internal::FutureData::Get()->api(); const auto future_handle = api->SafeAlloc(internal::kAnalyticsFnGetSessionId); [FIRAnalytics sessionIDWithCompletion:^(int64_t session_id, NSError* _Nullable error) { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); if (!internal::IsInitialized()) return; if (error) { api->Complete(future_handle, -1, util::NSStringToString(error.localizedDescription).c_str()); @@ -519,7 +523,7 @@ Thread get_id_thread( } Future GetSessionIdLastResult() { - MutexLock lock(g_mutex); + MutexLock lock(AnalyticsMutex()); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); return static_cast&>( internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnGetSessionId)); diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 5cc8f879b7..82f87c18de 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -249,6 +249,7 @@ set(utility_common_HDRS src/future_manager.h src/intrusive_list.h src/log.h + src/no_destructor.h src/optional.h src/path.h src/pthread_condvar.h @@ -301,6 +302,12 @@ if(ANDROID OR IOS) ${FLATBUFFERS_SOURCE_DIR}/src/idl_gen_text.cpp ${FLATBUFFERS_SOURCE_DIR}/src/reflection.cpp ${FLATBUFFERS_SOURCE_DIR}/src/util.cpp) + # Third-party FlatBuffers sources define static globals with non-trivial + # destructors; exempt them from the SDK's exit-time destructor check below. + set_source_files_properties( + ${app_flatbuffers_srcs} + PROPERTIES COMPILE_OPTIONS + "$<$:-Wno-exit-time-destructors>") set(app_flatbuffers_lib) else() set(app_flatbuffers_srcs) @@ -331,6 +338,8 @@ else() target_compile_options(firebase_app PRIVATE -fno-exceptions) endif() +firebase_cpp_reject_exit_time_destructors(firebase_app) + target_include_directories(firebase_app PUBLIC ${CMAKE_CURRENT_LIST_DIR}/src/include diff --git a/app/rest/CMakeLists.txt b/app/rest/CMakeLists.txt index f051d1f9fd..0bbcd1a162 100644 --- a/app/rest/CMakeLists.txt +++ b/app/rest/CMakeLists.txt @@ -44,6 +44,8 @@ set(rest_SRCS add_library(firebase_rest_lib STATIC ${rest_SRCS}) +firebase_cpp_reject_exit_time_destructors(firebase_rest_lib) + target_include_directories(firebase_rest_lib PUBLIC ${FIREBASE_CPP_SDK_ROOT_DIR} diff --git a/app/src/app_common.cc b/app/src/app_common.cc index 70647eee29..8647fdab4b 100644 --- a/app/src/app_common.cc +++ b/app/src/app_common.cc @@ -34,6 +34,7 @@ #include "app/src/include/firebase/internal/mutex.h" #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" // strtok_r is strtok_s on Windows. @@ -170,13 +171,18 @@ const char* kBuildSource = "custom_built"; const char* kApiClientHeader = "x-firebase-client"; const char* kXFirebaseGmpIdHeader = "X-Firebase-GMPID"; -SystemLogger g_system_logger; // NOLINT +// Wrapped in NoDestructor so per-App loggers remain valid if static Firebase +// instances log during process exit. +static SystemLogger& GetSystemLogger() { + static NoDestructor system_logger; + return *system_logger; +} // Private cross platform data associated with an app. struct AppData { // TODO(b/140528778): Remove kLogLevelVerbose here and add [GS]etLogLevel // member functions to app. - AppData() : logger(&g_system_logger, kLogLevelVerbose) {} + AppData() : logger(&GetSystemLogger(), kLogLevelVerbose) {} // App associated with this data. App* app; @@ -376,10 +382,10 @@ void RemoveApp(App* app) { delete g_apps; g_apps = nullptr; } - } - callback::Terminate(last_app); - if (last_app) { - LibraryRegistry::Terminate(); + callback::Terminate(last_app); + if (last_app) { + LibraryRegistry::Terminate(); + } } } } diff --git a/app/src/app_desktop.cc b/app/src/app_desktop.cc index 412ef5dede..f7e9d11fdb 100644 --- a/app/src/app_desktop.cc +++ b/app/src/app_desktop.cc @@ -32,6 +32,7 @@ #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/semaphore.h" #include "app/src/util.h" @@ -40,6 +41,13 @@ DEFINE_FIREBASE_VERSION_STRING(Firebase); namespace internal { +// Directory prefix searched by AppOptions::LoadDefault when Create() is +// invoked without explicit options. +static std::string& DefaultConfigPath() { + static NoDestructor default_config_path; + return *default_config_path; +} + // Attempts to load a config file from the path specified, and use it to // populate the AppOptions pointer. Returns true on success, false otherwise. bool LoadAppOptionsFromJsonConfigFile(const char* path, AppOptions* options) { @@ -88,7 +96,7 @@ bool LoadAppOptionsFromJsonConfigFile(const char* path, AppOptions* options) { } // namespace internal -// Searches internal::g_default_config_path for filenames matching +// Searches internal::DefaultConfigPath() for filenames matching // kDefaultGoogleServicesNames attempting to load the app options from each // config file in turn. AppOptions* AppOptions::LoadDefault(AppOptions* options) { @@ -106,7 +114,7 @@ AppOptions* AppOptions::LoadDefault(AppOptions* options) { FIREBASE_ARRAYSIZE(kDefaultGoogleServicesNames); for (size_t i = 0; i < number_of_config_filenames; i++) { std::string full_path = - internal::g_default_config_path + kDefaultGoogleServicesNames[i]; + internal::DefaultConfigPath() + kDefaultGoogleServicesNames[i]; if (internal::LoadAppOptionsFromJsonConfigFile(full_path.c_str(), options)) { return options; @@ -200,7 +208,7 @@ void App::RegisterLibrary(const char* library, const char* version, const char* App::GetUserAgent() { return app_common::GetUserAgent(); } void App::SetDefaultConfigPath(const char* path) { - internal::g_default_config_path = path; + internal::DefaultConfigPath() = path; #if defined(WIN32) const char kSeperator = '\\'; @@ -208,10 +216,10 @@ void App::SetDefaultConfigPath(const char* path) { const char kSeperator = '/'; #endif - if (!internal::g_default_config_path.empty()) { - char last_character = internal::g_default_config_path.back(); + if (!internal::DefaultConfigPath().empty()) { + char last_character = internal::DefaultConfigPath().back(); if (last_character != '\\' && last_character != '/') { - internal::g_default_config_path += kSeperator; + internal::DefaultConfigPath() += kSeperator; } } } diff --git a/app/src/app_desktop.h b/app/src/app_desktop.h index e32062b5ca..65c039c83f 100644 --- a/app/src/app_desktop.h +++ b/app/src/app_desktop.h @@ -43,10 +43,5 @@ class AppInternal { firebase::heartbeat::DateProviderImpl date_provider_; }; -// When Create() is invoked without arguments, it checks for a file named -// google-services-desktop.json, to load options from. This specifies the -// path to search. -static std::string g_default_config_path; // NOLINT - } // namespace internal } // namespace firebase diff --git a/app/src/log_stdio.cc b/app/src/log_stdio.cc index 7625d9df81..9bdd01383d 100644 --- a/app/src/log_stdio.cc +++ b/app/src/log_stdio.cc @@ -28,6 +28,7 @@ #endif // FIREBASE_PLATFORM_WINDOWS #include "app/src/include/firebase/internal/mutex.h" +#include "app/src/no_destructor.h" namespace firebase { @@ -42,9 +43,14 @@ static const char* kLogLevelPrefix[] = { }; #if FIREBASE_PLATFORM_WINDOWS -// Guards the log buffer on Windows. -static Mutex g_log_mutex; // NOLINT -#endif // FIREBASE_PLATFORM_WINDOWS +// Guards the OutputDebugString log buffer on Windows. Wrapped in NoDestructor +// so logging from static destructors at process exit does not lock a closed +// Windows mutex handle. +static Mutex& PlatformLogMutex() { + static NoDestructor log_mutex; + return *log_mutex; +} +#endif // FIREBASE_PLATFORM_WINDOWS // Initializes the logging module. void LogInitialize() {} @@ -62,7 +68,7 @@ void LogMessageV(LogLevel log_level, const char* format, va_list args) { // Platform specific logging. #if FIREBASE_PLATFORM_WINDOWS { - MutexLock lock(g_log_mutex); + MutexLock lock(PlatformLogMutex()); static char log_buffer[1024]; size_t prefix_length = strlen(prefix); strcpy(log_buffer, prefix); // // NOLINT diff --git a/app/src/no_destructor.h b/app/src/no_destructor.h new file mode 100644 index 0000000000..62e97df296 --- /dev/null +++ b/app/src/no_destructor.h @@ -0,0 +1,110 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_NO_DESTRUCTOR_H_ +#define FIREBASE_APP_SRC_NO_DESTRUCTOR_H_ + +#include +#include +#include + +namespace firebase { +namespace internal { + +// Wraps an instance of T in inline aligned storage whose destructor is never +// called. +// +// Use only for function-local statics. NoDestructor never destroys T, so an +// automatic variable or data member of this type leaks whatever T owns. This +// cannot be enforced at compile time: rejecting trivially destructible T would +// break NoDestructor, which is trivially destructible on some +// standard libraries and not on others. +// +// Intended for function-local statics that must outlive process teardown, such +// as global registries, mutexes, and loggers accessed when user-owned static +// Firebase objects run their destructors during exit(): +// +// - A plain `static T value;` registers an exit-time destructor (`__cxa_atexit` +// / `atexit`) that runs in reverse construction order, so destructors of +// other static objects constructed earlier can observe a destroyed `T`. +// - A namespace-scope `static T* value = new T();` avoids exit-time +// destruction, but introduces dynamic initialization order hazards across +// translation units before `main()`. +// - A function-local `static NoDestructor value;` is initialized thread- +// safely on first call (C++11 [stmt.dcl]), stores `T` inline with no extra +// heap allocation, has a trivial destructor so no exit-time destructor is +// registered, and remains reachable via static storage so leak checkers do +// not report it as leaked. +// +// Example: +// static Mutex& RegistryMutex() { +// static NoDestructor mutex; +// return *mutex; +// } +template +class NoDestructor { + public: + // Constructs the wrapped T in place, forwarding any arguments. + // Participates in overload resolution only when T is constructible from the + // arguments, so NoDestructor is not implicitly convertible from argument + // lists T itself rejects. Without this, GCC 10 treats a braced list such as + // `{1, 2}` as a candidate for the deleted copy constructor too and reports + // an ambiguity. + // Also disabled when decaying a single argument yields NoDestructor itself so + // non-const lvalue copy attempts hit the deleted copy constructor instead of + // forwarding into T's constructors (for example, firebase::Variant). + template ::value && + !std::is_same::type&...), + void(NoDestructor&)>::value, + int>::type = 0> + explicit NoDestructor(Args&&... args) { + new (storage_) T(std::forward(args)...); + } + + // Explicit copy/move overloads for T so brace-enclosed initializers (such as + // `NoDestructor>({1, 2})`) can deduce T. + explicit NoDestructor(const T& x) { new (storage_) T(x); } + explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); } + + NoDestructor(const NoDestructor&) = delete; + NoDestructor& operator=(const NoDestructor&) = delete; + + // Trivially destructible: intentionally never destroys the wrapped T. + ~NoDestructor() = default; + + T& operator*() { return *get(); } + T* operator->() { return get(); } + T* get() { return std::launder(reinterpret_cast(storage_)); } + + const T& operator*() const { return *get(); } + const T* operator->() const { return get(); } + const T* get() const { + return std::launder(reinterpret_cast(storage_)); + } + + private: + alignas(T) unsigned char storage_[sizeof(T)]; +}; + +} // namespace internal + +using internal::NoDestructor; + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_NO_DESTRUCTOR_H_ diff --git a/app/src/reference_counted_future_impl.cc b/app/src/reference_counted_future_impl.cc index 96026fcfef..8375675ad7 100644 --- a/app/src/reference_counted_future_impl.cc +++ b/app/src/reference_counted_future_impl.cc @@ -20,12 +20,14 @@ #include #include #include +#include #include "app/src/assert.h" #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/internal/mutex.h" #include "app/src/intrusive_list.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" // Set this to 1 to enable verbose logging in this module. #if !defined(FIREBASE_FUTURE_TRACE_ENABLE) @@ -47,9 +49,10 @@ static_assert(sizeof(FutureBase) == sizeof(Future), typedef void DataDeleteFn(void* data_to_delete); typedef std::pair BackingPair; -// NOLINTNEXTLINE -const FutureHandle ReferenceCountedFutureImpl::kInvalidHandle( - kInvalidFutureHandle); +const FutureHandle& ReferenceCountedFutureImpl::InvalidHandle() { + static const NoDestructor invalid_handle(kInvalidFutureHandle); + return *invalid_handle; +} namespace { @@ -74,7 +77,7 @@ class FutureProxyManager { MutexLock lock(mutex_); for (FutureHandle& h : clients_) { api_->ForceReleaseFuture(h); - h = ReferenceCountedFutureImpl::kInvalidHandle; + h = ReferenceCountedFutureImpl::InvalidHandle(); } clients_.clear(); } @@ -110,7 +113,7 @@ class FutureProxyManager { MutexLock lock(mutex_); for (FutureHandle& h : clients_) { if (h == handle) { - h = ReferenceCountedFutureImpl::kInvalidHandle; + h = ReferenceCountedFutureImpl::InvalidHandle(); // Release one reference. This can delete subject_, which in turn will // delete `this`, as the subject owns the proxy. This is expected and // fine; as long as we don't do anything after the ReleaseFuture call. @@ -123,7 +126,7 @@ class FutureProxyManager { void CompleteClients(int error, const char* error_msg) { MutexLock lock(mutex_); for (const FutureHandle& h : clients_) { - if (h != ReferenceCountedFutureImpl::kInvalidHandle) { + if (h != ReferenceCountedFutureImpl::InvalidHandle()) { api_->Complete(h, error, error_msg); } } diff --git a/app/src/reference_counted_future_impl.h b/app/src/reference_counted_future_impl.h index 0ca87712d7..b7d7c477f7 100644 --- a/app/src/reference_counted_future_impl.h +++ b/app/src/reference_counted_future_impl.h @@ -27,6 +27,7 @@ #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/include/firebase/internal/mutex.h" +#include "app/src/no_destructor.h" namespace firebase { @@ -66,16 +67,17 @@ class SafeFutureHandle { // See FutureHandle::Detach. void Detach() { handle_.Detach(); } - static const SafeFutureHandle kInvalidHandle; + // Type-safe version of kInvalidFutureHandle. Wrapped in NoDestructor so ODR + // uses of SafeFutureHandle never register an exit-time destructor. + static const SafeFutureHandle& InvalidHandle() { + static const NoDestructor invalid_handle; + return *invalid_handle; + } private: FutureHandle handle_; }; -// Type-safe version of kInvalidFutureHandle. -template -const SafeFutureHandle SafeFutureHandle::kInvalidHandle; - /// @brief Backing class for Futures that allows a Future to have multiple /// copies. When no copies remain, the Future is invalidated. /// @@ -98,9 +100,10 @@ const SafeFutureHandle SafeFutureHandle::kInvalidHandle; // unsafe methods. class ReferenceCountedFutureImpl : public detail::FutureApiInterface { public: - /// This handle will never be returned by @ref Alloc, so you can use it - /// to signify an uninitialized or invalid value. - static const FutureHandle kInvalidHandle; + /// Returns a handle that will never be returned by @ref Alloc, used to + /// signify an uninitialized or invalid value without registering a static + /// exit-time destructor. + static const FutureHandle& InvalidHandle(); /// Returned by @ref GetFutureError when the passed in handle is invalid. static constexpr int kErrorFutureIsNoLongerValid = -1; diff --git a/app/src/secure/user_secure_linux_internal.cc b/app/src/secure/user_secure_linux_internal.cc index 2dcfb74c1b..ab9bdfe1fb 100644 --- a/app/src/secure/user_secure_linux_internal.cc +++ b/app/src/secure/user_secure_linux_internal.cc @@ -16,8 +16,6 @@ #include -#include - #include "app/src/log.h" #include "app/src/secure/user_secure_data_handle.h" diff --git a/app/tests/CMakeLists.txt b/app/tests/CMakeLists.txt index 2ed0a7e7a1..b0013817ea 100644 --- a/app/tests/CMakeLists.txt +++ b/app/tests/CMakeLists.txt @@ -161,6 +161,21 @@ firebase_cpp_cc_test(firebase_app_cleanup_notifier_test firebase_app ) +firebase_cpp_cc_test(firebase_app_no_destructor_test + SOURCES + no_destructor_test.cc + DEPENDS + firebase_app +) + +firebase_cpp_cc_test(firebase_app_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_app + flatbuffers +) + firebase_cpp_cc_test(firebase_app_cpp11_thread_test SOURCES thread_test.cc diff --git a/app/tests/app_desktop_test.cc b/app/tests/app_desktop_test.cc index d6ace2da68..3dda405de1 100644 --- a/app/tests/app_desktop_test.cc +++ b/app/tests/app_desktop_test.cc @@ -21,10 +21,12 @@ #include #include #include +#include #include #include "app/src/app_common.h" #include "app/src/app_identifier.h" +#include "app/src/callback.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" @@ -252,4 +254,33 @@ TEST(AppDesktopTest, TestLoadAppOptionsFromJsonConfigFileInInternationalPath) { EXPECT_TRUE(ChangeDirectoryUtf8(previous_directory)); EXPECT_TRUE(RemoveDirectoryUtf8(new_dir)); } + +// app_common::RemoveApp() is also called for Apps that AddApp() never +// registered (platform initialization failed first). That must not release the +// callback reference AddApp() took for the Apps that are still registered. +TEST(AppDesktopTest, RemovingUnregisteredAppKeepsCallbacksInitialized) { + AppOptions options; + options.set_app_id("fake app id"); + options.set_api_key("fake api key"); + options.set_project_id("fake project id"); + + std::unique_ptr registered(App::Create(options, "registered")); + ASSERT_NE(registered, nullptr); + std::unique_ptr unregistered(App::Create(options, "unregistered")); + ASSERT_NE(unregistered, nullptr); + + // Unregister the second App the way ~App() does. + app_common::RemoveApp(unregistered.get()); + ASSERT_EQ(App::GetInstance("unregistered"), nullptr); + ASSERT_TRUE(callback::IsInitialized()); + + // The App is no longer registered, so removing it again must be a no-op. + app_common::RemoveApp(unregistered.get()); + EXPECT_TRUE(callback::IsInitialized()); + + unregistered.reset(); + EXPECT_TRUE(callback::IsInitialized()); + registered.reset(); + EXPECT_FALSE(callback::IsInitialized()); +} } // namespace firebase diff --git a/app/tests/future_test.cc b/app/tests/future_test.cc index 5e1fe96a83..fe041e9cb9 100644 --- a/app/tests/future_test.cc +++ b/app/tests/future_test.cc @@ -952,14 +952,14 @@ TEST_F(FutureTest, VerifyNotLeakedWhenOverridden) { SafeFutureHandle last_result_handle; last_result_handle = future_impl_.SafeAlloc(0); EXPECT_THAT(last_result_handle.get(), - Ne(SafeFutureHandle::kInvalidHandle.get())); + Ne(SafeFutureHandle::InvalidHandle().get())); EXPECT_TRUE(future_impl_.ValidFuture(last_result_handle)); id = last_result_handle.get().id(); } { auto new_last_result_handle = future_impl_.SafeAlloc(0); EXPECT_THAT(new_last_result_handle.get(), - Ne(SafeFutureHandle::kInvalidHandle.get())); + Ne(SafeFutureHandle::InvalidHandle().get())); EXPECT_FALSE(future_impl_.ValidFuture(id)); } } diff --git a/app/tests/no_destructor_test.cc b/app/tests/no_destructor_test.cc new file mode 100644 index 0000000000..111f287b75 --- /dev/null +++ b/app/tests/no_destructor_test.cc @@ -0,0 +1,150 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app/src/no_destructor.h" + +#include +#include +#include +#include +#include + +#include "app/src/include/firebase/variant.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace { + +// Records how many times it has been constructed and destroyed. +struct Tracked { + explicit Tracked(int value_in) : value(value_in) { ++constructed; } + ~Tracked() { ++destroyed; } + + int value; + static int constructed; + static int destroyed; +}; +int Tracked::constructed = 0; +int Tracked::destroyed = 0; + +struct alignas(64) OverAligned { + explicit OverAligned(uint64_t seed_in) : seed(seed_in) { ++constructed; } + ~OverAligned() { ++destroyed; } + + uint64_t seed; + static int constructed; + static int destroyed; +}; +int OverAligned::constructed = 0; +int OverAligned::destroyed = 0; + +// NoDestructor must be trivially destructible so function-local statics do +// not register __cxa_atexit / atexit handlers, and must remain non-copyable and +// non-movable even when T has broad converting constructors (such as Variant). +static_assert(std::is_trivially_destructible>::value, + "NoDestructor must be trivially destructible."); +static_assert(!std::is_copy_constructible>::value, + "NoDestructor must not be copy constructible."); +static_assert(!std::is_move_constructible>::value, + "NoDestructor must not be move constructible."); +static_assert(!std::is_copy_assignable>::value, + "NoDestructor must not be copy assignable."); +static_assert(!std::is_move_assignable>::value, + "NoDestructor must not be move assignable."); +static_assert( + !std::is_constructible, + NoDestructor&>::value, + "Non-const lvalue NoDestructor must not hijack forwarding ctor."); +static_assert( + !std::is_constructible, + const NoDestructor&>::value, + "Const lvalue NoDestructor must not be copy constructible."); +static_assert(!std::is_constructible, + NoDestructor&&>::value, + "Rvalue NoDestructor must not be move constructible."); + +// The forwarding constructor must only accept argument lists T accepts. +// std::vector has no (int, int, int) constructor. +static_assert( + !std::is_constructible>, int, int, + int>::value, + "NoDestructor must not be constructible from arguments T rejects."); +static_assert( + std::is_constructible, size_t, char>::value, + "NoDestructor must forward arguments T accepts."); + +TEST(NoDestructorTest, ForwardsConstructorArguments) { + // Static: std::string allocates here with the legacy libstdc++ ABI. + static NoDestructor str("hello"); + EXPECT_EQ(*str, "hello"); + EXPECT_EQ(str->size(), 5u); + EXPECT_EQ(str.get(), &*str); +} + +TEST(NoDestructorTest, DefaultConstructs) { + // Static, as in production use, so the map node allocated below stays + // reachable and LeakSanitizer does not report it. + static NoDestructor> map; + EXPECT_TRUE(map->empty()); + (*map)[1] = 2; + EXPECT_EQ(map->at(1), 2); +} + +TEST(NoDestructorTest, BraceEnclosedInitializerList) { + // Static so the vector's heap buffer stays reachable (see DefaultConstructs). + static NoDestructor> values({10, 20, 30}); + ASSERT_EQ(values->size(), 3u); + EXPECT_EQ((*values)[0], 10); + EXPECT_EQ((*values)[1], 20); + EXPECT_EQ((*values)[2], 30); +} + +TEST(NoDestructorTest, DoesNotRunDestructorWhenGoingOutOfScope) { + Tracked::constructed = 0; + Tracked::destroyed = 0; + { + NoDestructor tracked(42); + EXPECT_EQ(tracked->value, 42); + EXPECT_EQ(Tracked::constructed, 1); + } + EXPECT_EQ(Tracked::constructed, 1); + EXPECT_EQ(Tracked::destroyed, 0); +} + +TEST(NoDestructorTest, PreservesOverAlignedStorage) { + OverAligned::constructed = 0; + OverAligned::destroyed = 0; + { + NoDestructor aligned(0x12345678ULL); + EXPECT_EQ(reinterpret_cast(aligned.get()) % alignof(OverAligned), + 0u); + EXPECT_EQ(aligned->seed, 0x12345678ULL); + const NoDestructor& const_aligned = aligned; + EXPECT_EQ(const_aligned->seed, 0x12345678ULL); + } + EXPECT_EQ(OverAligned::constructed, 1); + EXPECT_EQ(OverAligned::destroyed, 0); +} + +TEST(NoDestructorTest, ConstAccess) { + static const NoDestructor str("const"); + EXPECT_EQ(*str, "const"); + EXPECT_EQ(str->size(), 5u); + EXPECT_EQ(str.get(), &*str); +} + +} // namespace +} // namespace firebase diff --git a/app/tests/static_destruction_test.cc b/app/tests/static_destruction_test.cc new file mode 100644 index 0000000000..9df963daee --- /dev/null +++ b/app/tests/static_destruction_test.cc @@ -0,0 +1,274 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "app/src/callback.h" +#include "app/src/cleanup_notifier.h" +#include "app/src/include/firebase/app.h" +#include "app/src/include/firebase/future.h" +#include "app/src/log.h" +#include "app/src/reference_counted_future_impl.h" +#include "app/src/util.h" +#include "gtest/gtest.h" + +// Smoke test: tears down firebase_app state (Apps, CleanupNotifier, callbacks, +// Futures, logging) from static destructors that run after main() returns. +// It does not detect a regression on its own, because destruction order +// between these globals and SDK globals in other translation units is +// unspecified. The guarantee comes from building with +// FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS and from +// scripts/gha/check_exit_time_destructors.py. + +namespace firebase { +namespace { + +// GoogleTest has already computed its exit status by the time static +// destructors run after main() returns, so post-main checks must abort directly +// on failure to fail CTest reliably. +void AbortIfFalse(bool condition, const char* description) { + if (!condition) { + std::fprintf(stderr, "StaticDestructionTest post-main check failed: %s\n", + description); + std::fflush(stderr); + std::abort(); + } +} + +AppOptions MakeTestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:abcdef123456"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test-project"); + options.set_database_url( + "https://static-destruction-test-project.firebaseio.com"); + options.set_storage_bucket("static-destruction-test-project.appspot.com"); + return options; +} + +// Simulates a Firebase product instance registered with an App's +// CleanupNotifier so both normal teardown (subscriber before App) and +// out-of-order teardown (App before subscriber) can be exercised. +class ScopedCleanupSubscriber { + public: + explicit ScopedCleanupSubscriber(App* app) : app_(app) { + CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app_); + AbortIfFalse(notifier != nullptr, + "CleanupNotifier::FindByOwner(app) returned nullptr"); + notifier->RegisterObject(this, &ScopedCleanupSubscriber::OnOwnerCleanedUp); + } + + ~ScopedCleanupSubscriber() { Cleanup(); } + + bool cleaned_up() const { return cleaned_up_; } + + private: + static void OnOwnerCleanedUp(void* obj) { + static_cast(obj)->Cleanup(); + } + + void Cleanup() { + if (cleaned_up_) return; + cleaned_up_ = true; + CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app_); + if (notifier != nullptr) { + notifier->UnregisterObject(this); + } + app_ = nullptr; + } + + App* app_; + bool cleaned_up_ = false; +}; + +int g_post_main_callback_runs = 0; +bool g_exit_time_holder_destroyed = false; + +void RecordPostMainCallback() { ++g_post_main_callback_runs; } + +// Defined BEFORE g_exit_time_sdk_holder in this translation unit so C++ +// constructs it first and destroys it AFTER ~ExitTimeSdkHolder() runs during +// process exit ([basic.start.term]). Verifies that the SDK's registries, +// mutexes, callbacks, futures, and loggers remain usable even for the final +// static destructor in the binary. +struct FinalPostMainVerifier { + bool armed = false; + + ~FinalPostMainVerifier() { + if (!armed) return; + + AbortIfFalse(g_exit_time_holder_destroyed, + "ExitTimeSdkHolder must be destroyed before " + "FinalPostMainVerifier"); + AbortIfFalse(App::GetApps().empty(), + "All Apps should be unregistered after ExitTimeSdkHolder " + "teardown"); + AbortIfFalse(App::GetInstance() == nullptr, + "Default App should be nullptr after ExitTimeSdkHolder " + "teardown"); + AbortIfFalse( + CleanupNotifier::FindByOwner(reinterpret_cast(0x1)) == nullptr, + "CleanupNotifier registry lookup failed during late exit"); + AbortIfFalse(ReferenceCountedFutureImpl::InvalidHandle().id() == + kInvalidFutureHandle, + "ReferenceCountedFutureImpl::InvalidHandle() corrupted"); + AbortIfFalse(SafeFutureHandle::InvalidHandle().get().id() == + ReferenceCountedFutureImpl::InvalidHandle().id(), + "SafeFutureHandle::InvalidHandle() mismatch"); + + const int before = g_post_main_callback_runs; + callback::AddCallback(new callback::CallbackVoid(&RecordPostMainCallback)); + callback::PollCallbacks(); + AbortIfFalse(g_post_main_callback_runs == before + 1, + "callback::PollCallbacks() did not run queued callback during " + "process exit"); + + LogInfo("StaticDestructionTest: post-main static teardown verified."); + } +}; + +// Defined AFTER g_final_post_main_verifier so its destructor runs during real +// __cxa_atexit / atexit processing after main() returns, tearing down live App +// instances, CleanupNotifier subscribers (in both orders), and Future backing +// state. +struct ExitTimeSdkHolder { + bool armed = false; + std::unique_ptr default_app; + std::unique_ptr subscriber_deleted_before_app; + std::unique_ptr secondary_app; + std::unique_ptr subscriber_outliving_app; + std::unique_ptr future_impl; + Future exit_future; + SafeFutureHandle exit_future_handle; + + ~ExitTimeSdkHolder() { + if (!armed) return; + + // 1. Complete and release a live Future during static destruction. + AbortIfFalse(future_impl != nullptr, "future_impl must be initialized"); + future_impl->CompleteWithResult(exit_future_handle, 0, "", 77); + AbortIfFalse(exit_future.status() == kFutureStatusComplete, + "exit_future did not complete during static destruction"); + AbortIfFalse(exit_future.result() != nullptr && *exit_future.result() == 77, + "exit_future result mismatch during static destruction"); + exit_future.Release(); + // Drop the last reference before deleting the backing API, which otherwise + // warns that a Future still exists. + exit_future_handle = SafeFutureHandle(); + future_impl.reset(); + + // 2. Normal destruction order during exit(): subscriber before its App. + subscriber_deleted_before_app.reset(); + default_app.reset(); + + // 3. Reverse destruction order during exit(): App destroyed while its + // dependent subscriber still exists (the exact pattern triggered when a + // user's static App is destroyed before a static product wrapper). + secondary_app.reset(); + AbortIfFalse(subscriber_outliving_app != nullptr && + subscriber_outliving_app->cleaned_up(), + "CleanupNotifier failed to clean up subscriber when App was " + "destroyed during process exit"); + subscriber_outliving_app.reset(); + + g_exit_time_holder_destroyed = true; + } +}; + +FinalPostMainVerifier g_final_post_main_verifier; +ExitTimeSdkHolder g_exit_time_sdk_holder; + +int g_in_test_callback_runs = 0; +void RecordInTestCallback() { ++g_in_test_callback_runs; } + +TEST(StaticDestructionTest, OutOfOrderCleanupAndRepeatedAppReinitialization) { + const AppOptions options = MakeTestAppOptions(); + + // Exercise repeated create -> destroy -> recreate cycles in a single process + // (for example, plugin/domain reloads without restarting the host process). + for (int cycle = 0; cycle < 3; ++cycle) { + std::unique_ptr default_app(App::Create(options)); + ASSERT_NE(default_app, nullptr); + EXPECT_EQ(App::GetInstance(), default_app.get()); + + const std::string secondary_name = + "cycle_secondary_" + std::to_string(cycle); + std::unique_ptr secondary_app( + App::Create(options, secondary_name.c_str())); + ASSERT_NE(secondary_app, nullptr); + EXPECT_EQ(App::GetInstance(secondary_name.c_str()), secondary_app.get()); + EXPECT_EQ(App::GetApps().size(), 2u); + + auto subscriber_first = + std::make_unique(default_app.get()); + auto subscriber_late = + std::make_unique(secondary_app.get()); + + const int callbacks_before = g_in_test_callback_runs; + callback::AddCallback(new callback::CallbackVoid(&RecordInTestCallback)); + callback::PollCallbacks(); + EXPECT_EQ(g_in_test_callback_runs, callbacks_before + 1); + + // Normal order: subscriber destroyed before App. + subscriber_first.reset(); + default_app.reset(); + EXPECT_EQ(App::GetInstance(), nullptr); + + // Out-of-order: App destroyed before subscriber. + void* destroyed_app_address = secondary_app.get(); + secondary_app.reset(); + EXPECT_TRUE(subscriber_late->cleaned_up()); + EXPECT_EQ(CleanupNotifier::FindByOwner(destroyed_app_address), nullptr); + subscriber_late.reset(); + + EXPECT_TRUE(App::GetApps().empty()); + } +} + +TEST(StaticDestructionTest, SurvivesPostMainStaticDestruction) { + const AppOptions options = MakeTestAppOptions(); + + g_exit_time_sdk_holder.default_app.reset(App::Create(options)); + ASSERT_NE(g_exit_time_sdk_holder.default_app, nullptr); + g_exit_time_sdk_holder.subscriber_deleted_before_app = + std::make_unique( + g_exit_time_sdk_holder.default_app.get()); + + g_exit_time_sdk_holder.secondary_app.reset( + App::Create(options, "post_main_secondary_app")); + ASSERT_NE(g_exit_time_sdk_holder.secondary_app, nullptr); + g_exit_time_sdk_holder.subscriber_outliving_app = + std::make_unique( + g_exit_time_sdk_holder.secondary_app.get()); + + g_exit_time_sdk_holder.future_impl = + std::make_unique(1); + g_exit_time_sdk_holder.exit_future_handle = + g_exit_time_sdk_holder.future_impl->SafeAlloc(0); + g_exit_time_sdk_holder.exit_future = + Future(g_exit_time_sdk_holder.future_impl.get(), + g_exit_time_sdk_holder.exit_future_handle.get()); + EXPECT_EQ(g_exit_time_sdk_holder.exit_future.status(), kFutureStatusPending); + + g_exit_time_sdk_holder.armed = true; + g_final_post_main_verifier.armed = true; +} + +} // namespace +} // namespace firebase diff --git a/app_check/CMakeLists.txt b/app_check/CMakeLists.txt index 338190e298..2cd44fbab4 100644 --- a/app_check/CMakeLists.txt +++ b/app_check/CMakeLists.txt @@ -165,6 +165,8 @@ target_compile_definitions(firebase_app_check -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_app_check) + if(ANDROID) firebase_cpp_proguard_file(app_check) elseif(IOS) diff --git a/app_check/src/android/play_integrity_provider_android.cc b/app_check/src/android/play_integrity_provider_android.cc index 94b669176b..2b27fe97a2 100644 --- a/app_check/src/android/play_integrity_provider_android.cc +++ b/app_check/src/android/play_integrity_provider_android.cc @@ -121,8 +121,12 @@ AppCheckProvider* PlayIntegrityProviderFactoryInternal::CreateProvider( } // namespace internal PlayIntegrityProviderFactory* PlayIntegrityProviderFactory::GetInstance() { - static PlayIntegrityProviderFactory g_play_integrity_provider_factory; - return &g_play_integrity_provider_factory; + // Heap-allocated function-local singleton (PlayIntegrityProviderFactory has a + // private constructor) so the factory is never destroyed during exit() while + // AppCheckInternal still references it or its created providers. + static PlayIntegrityProviderFactory* g_play_integrity_provider_factory = + new PlayIntegrityProviderFactory(); + return g_play_integrity_provider_factory; } PlayIntegrityProviderFactory::PlayIntegrityProviderFactory() diff --git a/app_check/src/common/app_check.cc b/app_check/src/common/app_check.cc index 4e3c065488..8dca464e35 100644 --- a/app_check/src/common/app_check.cc +++ b/app_check/src/common/app_check.cc @@ -25,6 +25,7 @@ #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "app_check/src/common/common.h" @@ -61,7 +62,13 @@ namespace app_check { DEFINE_FIREBASE_VERSION_STRING(FirebaseAppCheck); -Mutex g_app_check_lock; // NOLINT +// Function-local static wrapped in NoDestructor so it is constructed on first +// use and never destroyed; an AppCheck owned by a static object can still lock +// it from its destructor during process exit. +static Mutex& AppCheckLock() { + static NoDestructor mutex; + return *mutex; +} static std::map<::firebase::App*, AppCheck*>* g_app_check_map = nullptr; // Define the destructors for the virtual listener/provider/factory classes. @@ -86,7 +93,7 @@ namespace internal { AppCheck* GetExistingAppCheckInstance(::firebase::App* app) { if (!app) return nullptr; - MutexLock lock(g_app_check_lock); + MutexLock lock(AppCheckLock()); if (g_app_check_map) { auto it = g_app_check_map->find(app); if (it != g_app_check_map->end()) { @@ -101,7 +108,7 @@ AppCheck* GetExistingAppCheckInstance(::firebase::App* app) { AppCheck* AppCheck::GetInstance(::firebase::App* app) { if (!app) return nullptr; - MutexLock lock(g_app_check_lock); + MutexLock lock(AppCheckLock()); if (!g_app_check_map) { g_app_check_map = new std::map<::firebase::App*, AppCheck*>(); } @@ -127,7 +134,7 @@ AppCheck::AppCheck(::firebase::App* app) { AppCheck::~AppCheck() { DeleteInternal(); } void AppCheck::DeleteInternal() { - MutexLock lock(g_app_check_lock); + MutexLock lock(AppCheckLock()); if (!internal_) return; diff --git a/app_check/src/common/debug_provider_common.cc b/app_check/src/common/debug_provider_common.cc index e01aba203a..af2353eca9 100644 --- a/app_check/src/common/debug_provider_common.cc +++ b/app_check/src/common/debug_provider_common.cc @@ -30,8 +30,12 @@ namespace firebase { namespace app_check { DebugAppCheckProviderFactory* DebugAppCheckProviderFactory::GetInstance() { - static DebugAppCheckProviderFactory g_debug_app_check_provider_factory; - return &g_debug_app_check_provider_factory; + // Heap-allocated function-local singleton (DebugAppCheckProviderFactory has a + // private constructor) so the factory is never destroyed during exit() while + // AppCheckInternal still references it or its created providers. + static DebugAppCheckProviderFactory* g_debug_app_check_provider_factory = + new DebugAppCheckProviderFactory(); + return g_debug_app_check_provider_factory; } DebugAppCheckProviderFactory::DebugAppCheckProviderFactory() diff --git a/app_check/src/ios/app_attest_provider_ios.mm b/app_check/src/ios/app_attest_provider_ios.mm index 222fb01777..64a9251e76 100644 --- a/app_check/src/ios/app_attest_provider_ios.mm +++ b/app_check/src/ios/app_attest_provider_ios.mm @@ -99,8 +99,11 @@ virtual void GetLimitedUseToken( } // namespace internal AppAttestProviderFactory* AppAttestProviderFactory::GetInstance() { - static AppAttestProviderFactory g_app_attest_provider_factory; - return &g_app_attest_provider_factory; + // Heap-allocated function-local singleton (AppAttestProviderFactory has a + // private constructor) so the factory is never destroyed during exit() while + // AppCheckInternal still references it or its created providers. + static AppAttestProviderFactory* g_app_attest_provider_factory = new AppAttestProviderFactory(); + return g_app_attest_provider_factory; } AppAttestProviderFactory::AppAttestProviderFactory() diff --git a/app_check/src/ios/device_check_provider_ios.mm b/app_check/src/ios/device_check_provider_ios.mm index 3f660fb639..ee13ad9d61 100644 --- a/app_check/src/ios/device_check_provider_ios.mm +++ b/app_check/src/ios/device_check_provider_ios.mm @@ -103,8 +103,12 @@ virtual void GetLimitedUseToken( } // namespace internal DeviceCheckProviderFactory* DeviceCheckProviderFactory::GetInstance() { - static DeviceCheckProviderFactory g_device_check_check_provider_factory; - return &g_device_check_check_provider_factory; + // Heap-allocated function-local singleton (DeviceCheckProviderFactory has a + // private constructor) so the factory is never destroyed during exit() while + // AppCheckInternal still references it or its created providers. + static DeviceCheckProviderFactory* g_device_check_check_provider_factory = + new DeviceCheckProviderFactory(); + return g_device_check_check_provider_factory; } DeviceCheckProviderFactory::DeviceCheckProviderFactory() diff --git a/app_check/tests/CMakeLists.txt b/app_check/tests/CMakeLists.txt index 95a0035b2c..77dd7cf82e 100644 --- a/app_check/tests/CMakeLists.txt +++ b/app_check/tests/CMakeLists.txt @@ -33,3 +33,11 @@ firebase_cpp_cc_test( firebase_rest_lib firebase_testing ) + +firebase_cpp_cc_test( + firebase_app_check_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_app_check +) diff --git a/app_check/tests/static_destruction_test.cc b/app_check/tests/static_destruction_test.cc new file mode 100644 index 0000000000..3b1e3f5eb9 --- /dev/null +++ b/app_check/tests/static_destruction_test.cc @@ -0,0 +1,70 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A AppCheck owned by a static object is destroyed during exit(), after main() +// has returned, and must still be able to remove itself from the SDK's +// registry of AppCheck instances. See +// https://github.com/firebase/firebase-cpp-sdk/issues/110 for the Auth case. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "app_check/src/include/firebase/app_check.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace app_check { +namespace { + +// Owns an App and its AppCheck the way an application-level singleton would. +// Members are destroyed in reverse order of declaration. +// +// The opposite order is not covered: an App deletes its AppCheck when it is +// destroyed, so an AppCheck must never be deleted after its App. +struct ExitTimeOwner { + std::unique_ptr app; + // Destroyed before `app`. + std::unique_ptr app_check; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + return options; +} + +TEST(AppCheckStaticDestructionTest, AppCheckOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + g_exit_time_owner.app_check.reset( + AppCheck::GetInstance(g_exit_time_owner.app.get())); + ASSERT_NE(g_exit_time_owner.app_check, nullptr); +} + +} // namespace +} // namespace app_check +} // namespace firebase diff --git a/auth/CMakeLists.txt b/auth/CMakeLists.txt index 93055b0edd..ce29a0a51e 100644 --- a/auth/CMakeLists.txt +++ b/auth/CMakeLists.txt @@ -184,6 +184,8 @@ target_compile_definitions(firebase_auth -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_auth) + if(ANDROID) firebase_cpp_proguard_file(auth) elseif(IOS) diff --git a/auth/src/auth.cc b/auth/src/auth.cc index 23a483178f..4c11c9c530 100644 --- a/auth/src/auth.cc +++ b/auth/src/auth.cc @@ -31,6 +31,7 @@ #include "app/src/include/firebase/internal/common.h" #include "app/src/include/firebase/internal/mutex.h" #include "app/src/include/firebase/version.h" +#include "app/src/no_destructor.h" #include "app/src/semaphore.h" #include "app/src/util.h" #include "auth/src/common.h" @@ -53,14 +54,29 @@ DEFINE_FIREBASE_VERSION_STRING(FirebaseAuth); // and an Auth requires an App. So, the user acquires the Auth via an App // reference. // TODO(jsanmiya): Ensure all the Auths are destroyed on shutdown. -std::map g_auths; +// Function-local static wrapped in NoDestructor so it is constructed on first +// use and never destroyed; an Auth owned by a static (e.g. a static +// std::unique_ptr) can still remove itself during process exit. +static std::map& Auths() { + static NoDestructor> auths; + return *auths; +} Mutex* g_auths_mutex = new Mutex(); +// Must be called with *g_auths_mutex held. +static Auth* FindAuthLocked(App* app) { + std::map::iterator it = Auths().find(app); + if (it != Auths().end()) { + return it->second; + } + return nullptr; +} + // static Auth* Auth::GetAuth(App* app, InitResult* init_result_out) { MutexLock lock(*g_auths_mutex); // Return the Auth if it already exists. - Auth* existing_auth = FindAuth(app); + Auth* existing_auth = FindAuthLocked(app); if (existing_auth) { if (init_result_out != nullptr) *init_result_out = kInitResultSuccess; // Log heartbeat data when instance getters are called. @@ -79,7 +95,7 @@ Auth* Auth::GetAuth(App* app, InitResult* init_result_out) { // Stick it in the global map so we remember it, and can delete it on // shutdown. - g_auths[app] = auth; + Auths()[app] = auth; if (init_result_out) *init_result_out = kInitResultSuccess; return auth; @@ -88,12 +104,7 @@ Auth* Auth::GetAuth(App* app, InitResult* init_result_out) { // static Auth* Auth::FindAuth(App* app) { MutexLock lock(*g_auths_mutex); - // Return the Auth if it already exists. - std::map::iterator it = g_auths.find(app); - if (it != g_auths.end()) { - return it->second; - } - return nullptr; + return FindAuthLocked(app); } // Auth uses the pimpl mechanism to hide internal data types from the interface. @@ -143,17 +154,15 @@ void Auth::DeleteInternal() { int num_auths_remaining = 0; { - // Remove `this` from the g_auths map. - // The mapping is 1:1, so we should only ever delete one. - for (auto it = g_auths.begin(); it != g_auths.end(); ++it) { - if (it->second == this) { - LogDebug("Deleting Auth %p for App %p", this, it->first); - g_auths.erase(it); - break; - } + // Remove `this` from the Auths map by its owning App key. + std::map& auths = Auths(); + auto it = auths.find(auth_data_->app); + if (it != auths.end()) { + LogDebug("Deleting Auth %p for App %p", this, it->first); + auths.erase(it); } - num_auths_remaining = g_auths.size(); + num_auths_remaining = auths.size(); } auth_data_->ClearListeners(); diff --git a/auth/src/desktop/rpcs/get_account_info_response.h b/auth/src/desktop/rpcs/get_account_info_response.h index eb9b5d80bc..137f3f6e67 100644 --- a/auth/src/desktop/rpcs/get_account_info_response.h +++ b/auth/src/desktop/rpcs/get_account_info_response.h @@ -23,6 +23,7 @@ #include #include +#include "app/src/no_destructor.h" #include "auth/src/desktop/rpcs/auth_response.h" #include "auth/src/desktop/visual_studio_compatibility.h" @@ -92,9 +93,10 @@ class GetAccountInfoResponse : public AuthResponse { if (!application_data_->users.empty()) { return application_data_->users[0]->providerUserInfo; } - static std::vector> + static const NoDestructor< + std::vector>> fallback; - return fallback; + return *fallback; } }; diff --git a/auth/tests/CMakeLists.txt b/auth/tests/CMakeLists.txt index 92ebb6957a..18fc4d191b 100644 --- a/auth/tests/CMakeLists.txt +++ b/auth/tests/CMakeLists.txt @@ -301,3 +301,11 @@ firebase_cpp_cc_test( firebase_auth firebase_testing ) + +firebase_cpp_cc_test( + firebase_auth_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_auth +) diff --git a/auth/tests/auth_test.cc b/auth/tests/auth_test.cc index a0fd854ae3..246c43fde8 100644 --- a/auth/tests/auth_test.cc +++ b/auth/tests/auth_test.cc @@ -149,6 +149,31 @@ TEST_F(AuthTest, TestAuthCreation) { delete firebase_app; } +TEST_F(AuthTest, TestAuthIsRecreatedAfterDeletion) { + // Deleting an Auth removes its own entry, and only its own entry, from the + // App-to-Auth map. + firebase_app_ = testing::CreateApp(); + Auth* deleted_auth = Auth::GetAuth(firebase_app_); + ASSERT_NE(nullptr, deleted_auth); + + App* other_app = testing::CreateApp(testing::MockAppOptions(), "other_app"); + ASSERT_NE(nullptr, other_app); + Auth* other_auth = Auth::GetAuth(other_app); + ASSERT_NE(nullptr, other_auth); + + delete deleted_auth; + EXPECT_EQ(other_auth, Auth::GetAuth(other_app)); + + // A stale map entry would hand back the deleted Auth here, which TearDown() + // would then delete a second time. + firebase_auth_ = Auth::GetAuth(firebase_app_); + ASSERT_NE(nullptr, firebase_auth_); + EXPECT_EQ(firebase_app_, &firebase_auth_->app()); + + delete other_auth; + delete other_app; +} + // Creates and destroys multiple auth objects to ensure destruction doesn't // result in data races due to callbacks from the Java layer. TEST_F(AuthTest, TestAuthCreateDestroy) { diff --git a/auth/tests/static_destruction_test.cc b/auth/tests/static_destruction_test.cc new file mode 100644 index 0000000000..808cf5f823 --- /dev/null +++ b/auth/tests/static_destruction_test.cc @@ -0,0 +1,83 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Regression test for https://github.com/firebase/firebase-cpp-sdk/issues/110: +// an Auth owned by a static object is destroyed during exit(), after main() +// has returned, and must still be able to remove itself from the SDK's +// App-to-Auth registry. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "auth/src/include/firebase/auth.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace auth { +namespace { + +// Owns Apps and Auths the way an application-level singleton would. Members are +// destroyed in reverse order of declaration. +struct ExitTimeOwner { + // Destroyed after `app_destroyed_first`, so by then it has already been + // cleaned up by its App. + std::unique_ptr auth_outliving_app; + std::unique_ptr app_destroyed_first; + + std::unique_ptr app; + // Destroyed before `app`, which is the documented order. + std::unique_ptr auth; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + return options; +} + +TEST(AuthStaticDestructionTest, AuthOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + InitResult init_result = kInitResultFailedMissingDependency; + g_exit_time_owner.auth.reset( + Auth::GetAuth(g_exit_time_owner.app.get(), &init_result)); + ASSERT_EQ(init_result, kInitResultSuccess); + ASSERT_NE(g_exit_time_owner.auth, nullptr); + + g_exit_time_owner.app_destroyed_first.reset( + App::Create(TestAppOptions(), "app_destroyed_first")); + ASSERT_NE(g_exit_time_owner.app_destroyed_first, nullptr); + init_result = kInitResultFailedMissingDependency; + g_exit_time_owner.auth_outliving_app.reset( + Auth::GetAuth(g_exit_time_owner.app_destroyed_first.get(), &init_result)); + ASSERT_EQ(init_result, kInitResultSuccess); + ASSERT_NE(g_exit_time_owner.auth_outliving_app, nullptr); +} + +} // namespace +} // namespace auth +} // namespace firebase diff --git a/cmake/exit_time_destructors.cmake b/cmake/exit_time_destructors.cmake new file mode 100644 index 0000000000..b29bd1af82 --- /dev/null +++ b/cmake/exit_time_destructors.cmake @@ -0,0 +1,38 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Makes Clang diagnose static and global C++ objects in `target` that need a +# destructor to run at process exit. Such SDK state can be destroyed before +# user-owned static Firebase objects that still use it; wrap it in +# firebase::NoDestructor (app/src/no_destructor.h) instead. +# +# The diagnostic is a warning by default, and an error when +# FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS is ON, so that a declaration in a +# third-party header cannot break builds of the SDK from source. +# +# Only Clang and AppleClang implement -Wexit-time-destructors. Builds with +# other compilers are covered by scripts/gha/check_exit_time_destructors.py. +# The flag is restricted to C++ so C and Swift sources do not receive it. +# +# Args: +# target: The library target to check. +function(firebase_cpp_reject_exit_time_destructors target) + if(FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS) + set(exit_time_destructors_flag "-Werror=exit-time-destructors") + else() + set(exit_time_destructors_flag "-Wexit-time-destructors") + endif() + target_compile_options(${target} PRIVATE + $<$,$>:${exit_time_destructors_flag}>) +endfunction() diff --git a/database/CMakeLists.txt b/database/CMakeLists.txt index a6b07b3ddf..3cd3301587 100644 --- a/database/CMakeLists.txt +++ b/database/CMakeLists.txt @@ -217,6 +217,8 @@ target_compile_definitions(firebase_database ${additional_DEFINES} ) +firebase_cpp_reject_exit_time_destructors(firebase_database) + if(ANDROID) firebase_cpp_proguard_file(database) elseif(IOS) diff --git a/database/src/android/database_android.cc b/database/src/android/database_android.cc index ee5d72051a..3380e1157c 100644 --- a/database/src/android/database_android.cc +++ b/database/src/android/database_android.cc @@ -23,6 +23,7 @@ #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/include/firebase/log.h" +#include "app/src/no_destructor.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util.h" #include "app/src/util_android.h" @@ -39,8 +40,6 @@ namespace firebase { namespace database { namespace internal { -Mutex g_database_reference_constructor_mutex; // NOLINT - const char kApiIdentifier[] = "Database"; // clang-format off @@ -164,7 +163,10 @@ METHOD_LOOKUP_DEFINITION( "com/google/firebase/database/internal/cpp/CppChildEventListener", CPP_CHILD_EVENT_LISTENER_METHODS) -Mutex DatabaseInternal::init_mutex_; // NOLINT +static Mutex& InitMutex() { + static NoDestructor init_mutex; + return *init_mutex; +} int DatabaseInternal::initialize_count_ = 0; std::map* DatabaseInternal::java_error_to_cpp_ = nullptr; @@ -253,7 +255,7 @@ const char* kCppLogLevelToLoggerLevelName[] = { }; bool DatabaseInternal::Initialize(App* app) { - MutexLock init_lock(init_mutex_); + MutexLock init_lock(InitMutex()); if (initialize_count_ == 0) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); @@ -385,7 +387,7 @@ void DatabaseInternal::ReleaseClasses(App* app) { } void DatabaseInternal::Terminate(App* app) { - MutexLock init_lock(init_mutex_); + MutexLock init_lock(InitMutex()); assert(initialize_count_ > 0); initialize_count_--; if (initialize_count_ == 0) { diff --git a/database/src/android/database_android.h b/database/src/android/database_android.h index 5056e41ed4..ad260e52d8 100644 --- a/database/src/android/database_android.h +++ b/database/src/android/database_android.h @@ -41,7 +41,7 @@ namespace database { namespace internal { // For constructing, copying or moving DatabaseReferences atomically. -extern Mutex g_database_reference_constructor_mutex; +Mutex& DatabaseReferenceConstructorMutex(); // This is the Android implementation of Database. class DatabaseInternal { @@ -192,7 +192,6 @@ class DatabaseInternal { // Initialize classes loaded from embedded files. static bool InitializeEmbeddedClasses(App* app); - static Mutex init_mutex_; static int initialize_count_; static std::map* java_error_to_cpp_; App* app_; diff --git a/database/src/common/database.cc b/database/src/common/database.cc index ac17b9382c..43ca3fb34e 100644 --- a/database/src/common/database.cc +++ b/database/src/common/database.cc @@ -26,6 +26,7 @@ #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" // DatabaseInternal is defined in these 3 files, one implementation for each OS. @@ -56,9 +57,23 @@ DEFINE_FIREBASE_VERSION_STRING(FirebaseDatabase); using internal::DatabaseInternal; using DatabaseMap = std::map, Database*>; -Mutex g_databases_lock; // NOLINT + +// Function-local static wrapped in NoDestructor so it is constructed on first +// use and never destroyed; a Database owned by a static object can still lock +// it from its destructor during process exit. +static Mutex& DatabasesLock() { + static NoDestructor mutex; + return *mutex; +} static DatabaseMap* g_databases = nullptr; +namespace internal { +Mutex& DatabaseReferenceConstructorMutex() { + static NoDestructor mutex; + return *mutex; +} +} // namespace internal + namespace { DatabaseMap::key_type MakeKey(App* app, const std::string& url) { return std::make_pair(std::string(app->name()), url); @@ -71,7 +86,7 @@ Database* Database::GetInstance(App* app, const char* url, LogError("Database::GetInstance(): The app must not be null."); return nullptr; } - MutexLock lock(g_databases_lock); + MutexLock lock(DatabasesLock()); if (!g_databases) { g_databases = new DatabaseMap(); } @@ -118,7 +133,7 @@ Database::Database(::firebase::App* app, internal::DatabaseInternal* internal) } void Database::DeleteInternal() { - MutexLock lock(g_databases_lock); + MutexLock lock(DatabasesLock()); if (!internal_) return; @@ -138,7 +153,7 @@ void Database::DeleteInternal() { app_notifier->UnregisterObject(this); { - MutexLock db_ref_lock(internal::g_database_reference_constructor_mutex); + MutexLock db_ref_lock(internal::DatabaseReferenceConstructorMutex()); // Force cleanup to happen first. internal_->cleanup().CleanupAll(); } diff --git a/database/src/common/database_reference.cc b/database/src/common/database_reference.cc index dce0de7481..d837382feb 100644 --- a/database/src/common/database_reference.cc +++ b/database/src/common/database_reference.cc @@ -80,14 +80,14 @@ void DatabaseReference::SwitchCleanupRegistrationBackToQuery() { DatabaseReference::DatabaseReference(DatabaseReferenceInternal* internal) : Query(internal), internal_(internal) { - MutexLock lock(internal::g_database_reference_constructor_mutex); + MutexLock lock(internal::DatabaseReferenceConstructorMutex()); SwitchCleanupRegistrationToDatabaseReference(); } DatabaseReference::DatabaseReference(const DatabaseReference& reference) : Query(), internal_(nullptr) { - MutexLock lock(internal::g_database_reference_constructor_mutex); + MutexLock lock(internal::DatabaseReferenceConstructorMutex()); internal_ = reference.internal_ ? new DatabaseReferenceInternal(*reference.internal_) @@ -98,7 +98,7 @@ DatabaseReference::DatabaseReference(const DatabaseReference& reference) DatabaseReference& DatabaseReference::operator=( const DatabaseReference& reference) { - MutexLock lock(internal::g_database_reference_constructor_mutex); + MutexLock lock(internal::DatabaseReferenceConstructorMutex()); internal_ = reference.internal_ ? new DatabaseReferenceInternal(*reference.internal_) @@ -112,7 +112,7 @@ DatabaseReference& DatabaseReference::operator=( #if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) DatabaseReference::DatabaseReference(DatabaseReference&& reference) : Query(), internal_(reference.internal_) { - MutexLock lock(internal::g_database_reference_constructor_mutex); + MutexLock lock(internal::DatabaseReferenceConstructorMutex()); reference.internal_ = nullptr; Query::operator=(std::move(reference)); @@ -120,7 +120,7 @@ DatabaseReference::DatabaseReference(DatabaseReference&& reference) } DatabaseReference& DatabaseReference::operator=(DatabaseReference&& reference) { - MutexLock lock(internal::g_database_reference_constructor_mutex); + MutexLock lock(internal::DatabaseReferenceConstructorMutex()); internal_ = reference.internal_; reference.internal_ = nullptr; diff --git a/database/src/desktop/core/operation.cc b/database/src/desktop/core/operation.cc index 70923c62c6..28307938ab 100644 --- a/database/src/desktop/core/operation.cc +++ b/database/src/desktop/core/operation.cc @@ -17,6 +17,7 @@ #include #include "app/src/assert.h" +#include "app/src/no_destructor.h" #include "app/src/path.h" #include "database/src/desktop/util_desktop.h" @@ -24,10 +25,17 @@ namespace firebase { namespace database { namespace internal { -const OperationSource OperationSource::kUser(OperationSource::kSourceUser, - Optional(), false); -const OperationSource OperationSource::kServer(OperationSource::kSourceServer, - Optional(), false); +const OperationSource& OperationSource::User() { + static const NoDestructor user( + OperationSource::kSourceUser, Optional(), false); + return *user; +} + +const OperationSource& OperationSource::Server() { + static const NoDestructor server( + OperationSource::kSourceServer, Optional(), false); + return *server; +} OperationSource OperationSource::ForServerTaggedQuery( const QueryParams& params) { @@ -50,7 +58,7 @@ Operation Operation::Merge(const OperationSource& source, const Path& path, Operation Operation::AckUserWrite(const Path& path, const Tree& affected_tree, AckStatus status) { - return Operation(Operation::kTypeAckUserWrite, OperationSource::kUser, path, + return Operation(Operation::kTypeAckUserWrite, OperationSource::User(), path, Variant(), CompoundWrite(), affected_tree, status); } diff --git a/database/src/desktop/core/operation.h b/database/src/desktop/core/operation.h index 8ed5d521f3..a7367535a9 100644 --- a/database/src/desktop/core/operation.h +++ b/database/src/desktop/core/operation.h @@ -56,8 +56,8 @@ struct OperationSource { static OperationSource ForServerTaggedQuery(const QueryParams& params); - static const OperationSource kUser; - static const OperationSource kServer; + static const OperationSource& User(); + static const OperationSource& Server(); }; enum AckStatus { diff --git a/database/src/desktop/core/repo.cc b/database/src/desktop/core/repo.cc index 31598208c9..15b4107340 100644 --- a/database/src/desktop/core/repo.cc +++ b/database/src/desktop/core/repo.cc @@ -24,6 +24,7 @@ #include "app/src/function_registry.h" #include "app/src/include/firebase/internal/mutex.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/scheduler.h" #include "app/src/variant_util.h" #include "database/src/desktop/connection/persistent_connection.h" @@ -53,7 +54,10 @@ using callback::NewCallback; namespace database { namespace internal { -static Mutex g_scheduler_mutex; // NOLINT +static Mutex& SchedulerMutex() { + static NoDestructor scheduler_mutex; + return *scheduler_mutex; +} static int g_scheduler_ref_count = 0; scheduler::Scheduler* Repo::s_scheduler_; @@ -106,7 +110,7 @@ Repo::Repo(App* app, DatabaseInternal* database, const char* url, url_ = host_info_.ToString(); { - MutexLock lock(g_scheduler_mutex); + MutexLock lock(SchedulerMutex()); g_scheduler_ref_count++; if (s_scheduler_ == nullptr) s_scheduler_ = new scheduler::Scheduler(); } @@ -133,7 +137,7 @@ Repo::~Repo() { safe_this_.ClearReference(); connection_.reset(nullptr); { - MutexLock lock(g_scheduler_mutex); + MutexLock lock(SchedulerMutex()); if (g_scheduler_ref_count) g_scheduler_ref_count--; if (g_scheduler_ref_count == 0) { delete s_scheduler_; diff --git a/database/src/desktop/core/sync_tree.cc b/database/src/desktop/core/sync_tree.cc index d6d4b306d9..f9040e199e 100644 --- a/database/src/desktop/core/sync_tree.cc +++ b/database/src/desktop/core/sync_tree.cc @@ -299,7 +299,7 @@ std::vector SyncTree::ApplyListenComplete(const Path& path) { persistence_manager_->RunInTransaction([&, this]() -> bool { this->persistence_manager_->SetQueryComplete(QuerySpec(path)); results = this->ApplyOperationToSyncPoints( - Operation::ListenComplete(OperationSource::kServer, path)); + Operation::ListenComplete(OperationSource::Server(), path)); return true; }); return results; @@ -312,7 +312,7 @@ std::vector SyncTree::ApplyServerMerge( CompoundWrite merge = CompoundWrite::FromPathMerge(changed_children); this->persistence_manager_->UpdateServerCache(path, merge); results = this->ApplyOperationToSyncPoints( - Operation::Merge(OperationSource::kServer, path, merge)); + Operation::Merge(OperationSource::Server(), path, merge)); return true; }); return results; @@ -447,7 +447,7 @@ std::vector SyncTree::ApplyUserMerge( } pending_write_tree_->AddMerge(path, children, write_id); results = ApplyOperationToSyncPoints( - Operation::Merge(OperationSource::kUser, path, children)); + Operation::Merge(OperationSource::User(), path, children)); return true; }); return results; @@ -468,7 +468,7 @@ std::vector SyncTree::ApplyUserOverwrite( pending_write_tree_->AddOverwrite(path, new_data, write_id, visibility); if (visibility == kOverwriteVisible) { events = this->ApplyOperationToSyncPoints( - Operation::Overwrite(OperationSource::kUser, path, new_data)); + Operation::Overwrite(OperationSource::User(), path, new_data)); } return true; }); diff --git a/database/src/desktop/core/write_tree.cc b/database/src/desktop/core/write_tree.cc index 735198f8f6..a7426c218e 100644 --- a/database/src/desktop/core/write_tree.cc +++ b/database/src/desktop/core/write_tree.cc @@ -168,7 +168,7 @@ Optional WriteTree::CalcCompleteEventCache( if (complete_server_cache != nullptr) { layered_cache = complete_server_cache; } else { - layered_cache = &kNullVariant; + layered_cache = &GetNullVariant(); } return Optional(sub_merge.Apply(*layered_cache)); } diff --git a/database/src/desktop/database_desktop.cc b/database/src/desktop/database_desktop.cc index a7e0a5e544..54a9b87731 100644 --- a/database/src/desktop/database_desktop.cc +++ b/database/src/desktop/database_desktop.cc @@ -41,8 +41,6 @@ using callback::NewCallback; namespace database { namespace internal { -Mutex g_database_reference_constructor_mutex; // NOLINT - SingleValueListener::SingleValueListener(DatabaseInternal* database, const QuerySpec& query_spec, ReferenceCountedFutureImpl* future, diff --git a/database/src/desktop/database_desktop.h b/database/src/desktop/database_desktop.h index 6dc991111d..5d64d691a1 100644 --- a/database/src/desktop/database_desktop.h +++ b/database/src/desktop/database_desktop.h @@ -45,7 +45,7 @@ namespace database { namespace internal { // For constructing, copying or moving DatabaseReferences atomically. -extern Mutex g_database_reference_constructor_mutex; +Mutex& DatabaseReferenceConstructorMutex(); typedef int64_t WriteId; diff --git a/database/src/desktop/persistence/persistence_manager.cc b/database/src/desktop/persistence/persistence_manager.cc index 55f1fd0445..a2e2e599ba 100644 --- a/database/src/desktop/persistence/persistence_manager.cc +++ b/database/src/desktop/persistence/persistence_manager.cc @@ -16,7 +16,6 @@ #include #include -#include #include #include #include diff --git a/database/src/desktop/persistence/prune_forest.cc b/database/src/desktop/persistence/prune_forest.cc index 15ab043762..449bc343f9 100644 --- a/database/src/desktop/persistence/prune_forest.cc +++ b/database/src/desktop/persistence/prune_forest.cc @@ -19,6 +19,7 @@ #include #include "app/src/assert.h" +#include "app/src/no_destructor.h" #include "app/src/path.h" #include "database/src/desktop/core/tree.h" @@ -26,8 +27,15 @@ namespace firebase { namespace database { namespace internal { -static const Tree kPruneTree(true); // NOLINT -static const Tree kKeepTree(false); // NOLINT +static const Tree& PruneTree() { + static const NoDestructor> prune_tree(true); + return *prune_tree; +} + +static const Tree& KeepTree() { + static const NoDestructor> keep_tree(false); + return *keep_tree; +} static bool KeepPredicate(bool prune) { return !prune; } static bool PrunePredicate(bool prune) { return prune; } @@ -84,7 +92,7 @@ void PruneForestRef::Prune(const Path& path) { if (prune_forest_->RootMostValueMatching(path, PrunePredicate) != nullptr) { // This path will already be pruned } else { - *prune_forest_->GetOrMakeSubtree(path) = kPruneTree; + *prune_forest_->GetOrMakeSubtree(path) = PruneTree(); } } @@ -92,7 +100,7 @@ void PruneForestRef::Keep(const Path& path) { if (prune_forest_->RootMostValueMatching(path, KeepPredicate) != nullptr) { // This path will already be kept } else { - *prune_forest_->GetOrMakeSubtree(path) = kKeepTree; + *prune_forest_->GetOrMakeSubtree(path) = KeepTree(); } } @@ -101,7 +109,7 @@ void PruneForestRef::KeepAll(const Path& path, if (prune_forest_->RootMostValueMatching(path, KeepPredicate) != nullptr) { // This path will already be kept. } else { - DoAll(path, children, kKeepTree); + DoAll(path, children, KeepTree()); } } @@ -114,7 +122,7 @@ void PruneForestRef::PruneAll(const Path& path, if (prune_forest_->RootMostValueMatching(path, PrunePredicate) != nullptr) { // This path will already be pruned. } else { - DoAll(path, children, kPruneTree); + DoAll(path, children, PruneTree()); } } diff --git a/database/src/desktop/query_params_comparator.cc b/database/src/desktop/query_params_comparator.cc index 803c18a971..636dafda3a 100644 --- a/database/src/desktop/query_params_comparator.cc +++ b/database/src/desktop/query_params_comparator.cc @@ -19,6 +19,7 @@ #include #include "app/src/assert.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "database/src/desktop/util_desktop.h" @@ -33,20 +34,34 @@ const char QueryParamsComparator::kMaxKey[] = "[MAX_KEY]"; // down values with these types. These are never compared to other variants // directly - they should only be used with the QueryParamsComparator, which // uses the Variant::type() to do comparisons. -static const Variant kMinVariant = Variant::FromStaticBlob( // NOLINT - QueryParamsComparator::kMinKey, sizeof(QueryParamsComparator::kMinKey)); -static const Variant kMaxVariant = Variant::FromStaticBlob( // NOLINT - QueryParamsComparator::kMaxKey, sizeof(QueryParamsComparator::kMaxKey)); +static const Variant& MinVariant() { + static const NoDestructor min_variant(Variant::FromStaticBlob( + QueryParamsComparator::kMinKey, sizeof(QueryParamsComparator::kMinKey))); + return *min_variant; +} + +static const Variant& MaxVariant() { + static const NoDestructor max_variant(Variant::FromStaticBlob( + QueryParamsComparator::kMaxKey, sizeof(QueryParamsComparator::kMaxKey))); + return *max_variant; +} -const std::pair QueryParamsComparator::kMinNode = // NOLINT - std::make_pair(QueryParamsComparator::kMinKey, kMinVariant); -const std::pair QueryParamsComparator::kMaxNode = // NOLINT - std::make_pair(QueryParamsComparator::kMaxKey, kMaxVariant); +const std::pair& QueryParamsComparator::MinNode() { + static const NoDestructor> min_node( + std::make_pair(QueryParamsComparator::kMinKey, MinVariant())); + return *min_node; +} + +const std::pair& QueryParamsComparator::MaxNode() { + static const NoDestructor> max_node( + std::make_pair(QueryParamsComparator::kMaxKey, MaxVariant())); + return *max_node; +} static int VariantIsSentinel(const Variant& key, const Variant& value) { - if (key == QueryParamsComparator::kMinKey && value == kMinVariant) { + if (key == QueryParamsComparator::kMinKey && value == MinVariant()) { return -1; - } else if (key == QueryParamsComparator::kMaxKey && value == kMaxVariant) { + } else if (key == QueryParamsComparator::kMaxKey && value == MaxVariant()) { return 1; } else { return 0; @@ -179,14 +194,14 @@ int QueryParamsComparator::CompareValues(const Variant& variant_a, // If we encounted a special sentinel value, figure out what we actually want // the precendence to be. if (precedence_a == kPrecedenceSentinel) { - assert(*value_a == kMinVariant || *value_a == kMaxVariant); + assert(*value_a == MinVariant() || *value_a == MaxVariant()); precedence_a = - (*value_a == kMinVariant) ? kPrecedenceFirst : kPrecedenceLast; + (*value_a == MinVariant()) ? kPrecedenceFirst : kPrecedenceLast; } if (precedence_b == kPrecedenceSentinel) { - assert(*value_b == kMinVariant || *value_b == kMaxVariant); + assert(*value_b == MinVariant() || *value_b == MaxVariant()); precedence_b = - (*value_b == kMinVariant) ? kPrecedenceFirst : kPrecedenceLast; + (*value_b == MinVariant()) ? kPrecedenceFirst : kPrecedenceLast; } // Values coming down from the server should never contain blobs or vectors. diff --git a/database/src/desktop/query_params_comparator.h b/database/src/desktop/query_params_comparator.h index c1a4fdb8c0..f8e26398c5 100644 --- a/database/src/desktop/query_params_comparator.h +++ b/database/src/desktop/query_params_comparator.h @@ -88,8 +88,8 @@ class QueryParamsComparator { // These values will always be sorted before or after all over values. static const char kMinKey[]; static const char kMaxKey[]; - static const std::pair kMinNode; - static const std::pair kMaxNode; + static const std::pair& MinNode(); + static const std::pair& MaxNode(); private: int CompareChildren(const Variant& value_a, const Variant& value_b) const; diff --git a/database/src/desktop/util_desktop.cc b/database/src/desktop/util_desktop.cc index ac2f10868b..537add97f7 100644 --- a/database/src/desktop/util_desktop.cc +++ b/database/src/desktop/util_desktop.cc @@ -19,13 +19,13 @@ #include #include #include -#include #include #include #include #include "app/src/assert.h" #include "app/src/include/firebase/variant.h" +#include "app/src/no_destructor.h" #include "database/src/common/query_spec.h" #include "database/src/desktop/view/indexed_filter.h" #include "database/src/desktop/view/limited_filter.h" @@ -47,7 +47,10 @@ namespace firebase { namespace database { namespace internal { -const Variant kNullVariant = Variant::Null(); // NOLINT +const Variant& GetNullVariant() { + static const NoDestructor null_variant(Variant::Null()); + return *null_variant; +} const char kValueKey[] = ".value"; const char kPriorityKey[] = ".priority"; @@ -93,14 +96,14 @@ static const Variant& VariantGetImmediateChild(const Variant* variant, if (IsPriorityKey(key)) { return GetVariantPriority(*variant); } else { - return kNullVariant; + return GetNullVariant(); } } else { if (IsPriorityKey(key)) { return GetVariantPriority(*variant); } else { const Variant* result = MapGet(&variant->map(), key); - return result ? *result : kNullVariant; + return result ? *result : GetNullVariant(); } } } @@ -112,7 +115,7 @@ const Variant& VariantGetChild(const Variant* variant, const Path& path) { } else if (IsPriorityKey(path.FrontDirectory().str())) { return GetVariantPriority(*variant); } else { - return kNullVariant; + return GetNullVariant(); } } else { std::string front = path.FrontDirectory().str(); @@ -625,11 +628,11 @@ Variant* GetVariantValue(Variant* variant) { const Variant& GetVariantPriority(const Variant& variant) { if (!variant.is_map()) { - return kNullVariant; + return GetNullVariant(); } auto iter = variant.map().find(kPriorityKey); if (iter == variant.map().end()) { - return kNullVariant; + return GetNullVariant(); } return iter->second; } @@ -1075,7 +1078,7 @@ std::pair GetStartPost(const QueryParams& params) { if (HasStart(params)) { return MakePost(params, GetStartName(params), GetStartValue(params)); } else { - return QueryParamsComparator::kMinNode; + return QueryParamsComparator::MinNode(); } } @@ -1083,7 +1086,7 @@ std::pair GetEndPost(const QueryParams& params) { if (HasEnd(params)) { return MakePost(params, GetEndName(params), GetEndValue(params)); } else { - return QueryParamsComparator::kMaxNode; + return QueryParamsComparator::MaxNode(); } } diff --git a/database/src/desktop/util_desktop.h b/database/src/desktop/util_desktop.h index ef168ad87c..c6e47d0901 100644 --- a/database/src/desktop/util_desktop.h +++ b/database/src/desktop/util_desktop.h @@ -42,7 +42,7 @@ class VariantFilter; // Rather than construct a null_variant in the current scope any place where // this happens, it can be helpful to have a persistent one that can be used // from anywhere. -extern const Variant kNullVariant; +const Variant& GetNullVariant(); // The virtual key for the value. This has special meaning to the database, and // for all intents and purposes the value at this location in the map should be @@ -87,7 +87,7 @@ bool PatchVariant(const Variant& patch_data, Variant* out_data); // Get a child of a given variant, respecting .value and .priorty virtual keys // appropriately. This will always return some value. If there is a value at the // given path, a reference to that value will be returned. If there is not, a -// reference to kNullVariant will be returned. +// reference to GetNullVariant() will be returned. // // This function is designed to perfectly mimic the behavior of Node.getChild in // the Java API. This should be used in place of GetInternalVariant, which is diff --git a/database/src/desktop/view/limited_filter.cc b/database/src/desktop/view/limited_filter.cc index 9c65f26d6e..e03b121100 100644 --- a/database/src/desktop/view/limited_filter.cc +++ b/database/src/desktop/view/limited_filter.cc @@ -43,8 +43,9 @@ IndexedVariant LimitedFilter::UpdateChild( const CompleteChildSource* source, ChildChangeAccumulator* opt_change_accumulator) const { const Variant& variant = - ranged_filter_->Matches(std::make_pair(key, new_child)) ? new_child - : kNullVariant; + ranged_filter_->Matches(std::make_pair(key, new_child)) + ? new_child + : GetNullVariant(); const Variant* child = GetInternalVariant(&indexed_variant.variant(), key); if (child && (*child == variant)) { diff --git a/database/src/desktop/view/ranged_filter.cc b/database/src/desktop/view/ranged_filter.cc index a68c3d5017..7ff26e851a 100644 --- a/database/src/desktop/view/ranged_filter.cc +++ b/database/src/desktop/view/ranged_filter.cc @@ -41,7 +41,8 @@ IndexedVariant RangedFilter::UpdateChild( const Variant& new_child, const Path& affected_path, const CompleteChildSource* source, ChildChangeAccumulator* opt_change_accumulator) const { - const Variant& variant = Matches(key, new_child) ? new_child : kNullVariant; + const Variant& variant = + Matches(key, new_child) ? new_child : GetNullVariant(); return indexed_filter_->UpdateChild(indexed_variant, key, variant, affected_path, source, opt_change_accumulator); diff --git a/database/src/desktop/view/view_processor.cc b/database/src/desktop/view/view_processor.cc index 2db179b8a3..c6d80a9cec 100644 --- a/database/src/desktop/view/view_processor.cc +++ b/database/src/desktop/view/view_processor.cc @@ -658,7 +658,7 @@ ViewCache ViewProcessor::AckUserWrite(const ViewCache& view_cache, server_cache.IsCompleteForPath(ack_path)) { const Variant* variant = GetInternalVariant(&server_cache.variant(), ack_path); - if (!variant) variant = &kNullVariant; + if (!variant) variant = &GetNullVariant(); return ApplyServerOverwrite(view_cache, ack_path, *variant, writes_cache, opt_complete_cache, filter_server_node, accumulator); diff --git a/database/src/ios/database_ios.h b/database/src/ios/database_ios.h index 08072cd062..4671aaff52 100644 --- a/database/src/ios/database_ios.h +++ b/database/src/ios/database_ios.h @@ -39,7 +39,7 @@ namespace database { namespace internal { // For constructing, copying or moving DatabaseReferences atomically. -extern Mutex g_database_reference_constructor_mutex; +Mutex& DatabaseReferenceConstructorMutex(); // This defines the class FIRDatabasePointer, which is a C++-compatible wrapper // around the FIRDatabase Obj-C class. diff --git a/database/src/ios/database_ios.mm b/database/src/ios/database_ios.mm index 50f0879bb5..ac54579158 100644 --- a/database/src/ios/database_ios.mm +++ b/database/src/ios/database_ios.mm @@ -27,8 +27,6 @@ namespace database { namespace internal { -Mutex g_database_reference_constructor_mutex; // NOLINT - DatabaseInternal::DatabaseInternal(App* app) : app_(app), logger_(app_common::FindAppLoggerByName(app->name())) { @try { diff --git a/database/tests/CMakeLists.txt b/database/tests/CMakeLists.txt index d498817f4d..3f868447a0 100644 --- a/database/tests/CMakeLists.txt +++ b/database/tests/CMakeLists.txt @@ -396,3 +396,10 @@ if(MSVC) ) endif() +firebase_cpp_cc_test( + firebase_rtdb_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_database +) diff --git a/database/tests/desktop/core/operation_test.cc b/database/tests/desktop/core/operation_test.cc index a1eb76eee6..db32beb4d3 100644 --- a/database/tests/desktop/core/operation_test.cc +++ b/database/tests/desktop/core/operation_test.cc @@ -97,7 +97,7 @@ TEST(OperationSource, ForServerTaggedQuery) { } TEST(Operation, Overwrite) { - Operation op = Operation::Overwrite(OperationSource::kServer, Path("A/B/C"), + Operation op = Operation::Overwrite(OperationSource::Server(), Path("A/B/C"), Variant(100)); EXPECT_EQ(op.type, Operation::kTypeOverwrite); EXPECT_EQ(op.source.source, OperationSource::kSourceServer); @@ -115,7 +115,7 @@ TEST(Operation, Merge) { }; CompoundWrite write = CompoundWrite::FromPathMerge(merge); Operation op = - Operation::Merge(OperationSource::kServer, Path("A/B/C"), write); + Operation::Merge(OperationSource::Server(), Path("A/B/C"), write); EXPECT_EQ(op.type, Operation::kTypeMerge); EXPECT_EQ(op.source.source, OperationSource::kSourceServer); @@ -153,7 +153,7 @@ TEST(Operation, AckUserWrite) { TEST(Operation, ListenComplete) { Operation op = - Operation::ListenComplete(OperationSource::kServer, Path("A/B/C")); + Operation::ListenComplete(OperationSource::Server(), Path("A/B/C")); EXPECT_EQ(op.type, Operation::kTypeListenComplete); EXPECT_EQ(op.source.source, OperationSource::kSourceServer); EXPECT_FALSE(op.source.query_params.has_value()); @@ -168,8 +168,9 @@ TEST(OperationDeathTest, DISABLED_ListenCompleteWithWrongSource) { TEST(OperationDeathTest, ListenCompleteWithWrongSource) { #endif // ListenCompletes must come from the server, not the user. - EXPECT_DEATH(Operation::ListenComplete(OperationSource::kUser, Path("A/B/C")), - DEATHTEST_SIGABRT); + EXPECT_DEATH( + Operation::ListenComplete(OperationSource::User(), Path("A/B/C")), + DEATHTEST_SIGABRT); } TEST(Operation, OperationForChildOverwriteEmptyPath) { @@ -178,7 +179,7 @@ TEST(Operation, OperationForChildOverwriteEmptyPath) { std::make_pair("bbb", 200), std::make_pair("ccc", 300), }; - Operation op = Operation::Overwrite(OperationSource::kServer, Path(), + Operation op = Operation::Overwrite(OperationSource::Server(), Path(), Variant(variant_data)); Optional result = OperationForChild(op, "aaa"); EXPECT_TRUE(result.has_value()); @@ -195,7 +196,7 @@ TEST(Operation, OperationForChildOverwriteNonEmptyPath) { std::make_pair("bbb", 200), std::make_pair("ccc", 300), }; - Operation op = Operation::Overwrite(OperationSource::kServer, Path("A/B/C"), + Operation op = Operation::Overwrite(OperationSource::Server(), Path("A/B/C"), Variant(variant_data)); Optional result = OperationForChild(op, "A"); EXPECT_TRUE(result.has_value()); @@ -214,7 +215,7 @@ TEST(Operation, OperationForChildMergeEmptyPath) { std::make_pair(Path("ccc/ddd"), 300), }; CompoundWrite write = CompoundWrite::FromPathMerge(merge_data); - Operation op = Operation::Merge(OperationSource::kServer, Path(), write); + Operation op = Operation::Merge(OperationSource::Server(), Path(), write); Optional result = OperationForChild(op, "zzz"); @@ -227,7 +228,7 @@ TEST(Operation, OperationForChildMergeEmptyPath) { std::make_pair(Path("ccc/ddd"), 300), }; CompoundWrite write = CompoundWrite::FromPathMerge(merge_data); - Operation op = Operation::Merge(OperationSource::kServer, Path(), write); + Operation op = Operation::Merge(OperationSource::Server(), Path(), write); Optional result = OperationForChild(op, "aaa"); @@ -245,7 +246,7 @@ TEST(Operation, OperationForChildMergeEmptyPath) { std::make_pair(Path("ccc/ddd"), 300), }; CompoundWrite write = CompoundWrite::FromPathMerge(merge_data); - Operation op = Operation::Merge(OperationSource::kServer, Path(), write); + Operation op = Operation::Merge(OperationSource::Server(), Path(), write); Optional result = OperationForChild(op, "ccc"); @@ -266,7 +267,7 @@ TEST(Operation, OperationForChildMergeNonEmptyPath) { }; CompoundWrite write = CompoundWrite::FromPathMerge(merge_data); Operation op = - Operation::Merge(OperationSource::kServer, Path("A/B/C"), write); + Operation::Merge(OperationSource::Server(), Path("A/B/C"), write); Optional result = OperationForChild(op, "A"); @@ -288,7 +289,7 @@ TEST(Operation, OperationForChildMergeNonEmptyPath) { }; CompoundWrite write = CompoundWrite::FromPathMerge(merge_data); Operation op = - Operation::Merge(OperationSource::kServer, Path("A/B/C"), write); + Operation::Merge(OperationSource::Server(), Path("A/B/C"), write); Optional result = OperationForChild(op, "Z"); @@ -419,7 +420,7 @@ TEST(Operation, } TEST(Operation, OperationForChildListenCompleteEmptyPath) { - Operation op = Operation::ListenComplete(OperationSource::kServer, Path()); + Operation op = Operation::ListenComplete(OperationSource::Server(), Path()); Optional result = OperationForChild(op, "Z"); @@ -433,7 +434,7 @@ TEST(Operation, OperationForChildListenCompleteEmptyPath) { TEST(Operation, OperationForChildListenCompleteNonEmptyPath) { Operation op = - Operation::ListenComplete(OperationSource::kServer, Path("A/B/C")); + Operation::ListenComplete(OperationSource::Server(), Path("A/B/C")); Optional result = OperationForChild(op, "A"); diff --git a/database/tests/desktop/view/view_processor_test.cc b/database/tests/desktop/view/view_processor_test.cc index b07721a57d..d842a34777 100644 --- a/database/tests/desktop/view/view_processor_test.cc +++ b/database/tests/desktop/view/view_processor_test.cc @@ -57,7 +57,7 @@ TEST(ViewProcessor, ApplyOperationUserOverwrite_WithEmptyPath) { // Create a user-initiated overwrite with an empty path to change a value. Operation operation = - Operation::Overwrite(OperationSource::kUser, Path(), Variant("apples")); + Operation::Overwrite(OperationSource::User(), Path(), Variant("apples")); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path()); @@ -94,7 +94,7 @@ TEST(ViewProcessor, ApplyOperationUserOverwrite_WithPriorityPath) { ViewCache old_view_cache(initial_local_cache, initial_server_cache); // Create a user-initiated overwrite with an empty path to change a value. - Operation operation = Operation::Overwrite(OperationSource::kUser, + Operation operation = Operation::Overwrite(OperationSource::User(), Path(".priority"), Variant(100)); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path()); @@ -133,7 +133,7 @@ TEST(ViewProcessor, ApplyOperationUserOverwrite_WithRegularPath) { // Create a user-initiated overwrite with a non-empty path to change a value. Operation operation = Operation::Overwrite( - OperationSource::kUser, Path("aaa/bbb"), Variant("apples")); + OperationSource::User(), Path("aaa/bbb"), Variant("apples")); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path("aaa/bbb")); @@ -186,8 +186,8 @@ TEST(ViewProcessor, ApplyOperationServerOverwrite_WithEmptyPath) { ViewCache old_view_cache(initial_local_cache, initial_server_cache); // Create a server-initiated overwrite with an empty path to change a value. - Operation operation = - Operation::Overwrite(OperationSource::kServer, Path(), Variant("apples")); + Operation operation = Operation::Overwrite(OperationSource::Server(), Path(), + Variant("apples")); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path()); Variant complete_cache; @@ -223,7 +223,7 @@ TEST(ViewProcessor, ApplyOperationServerOverwrite_RegularPath) { ViewCache old_view_cache(initial_local_cache, initial_server_cache); Operation operation = - Operation::Overwrite(OperationSource::kServer, Path("aaa"), + Operation::Overwrite(OperationSource::Server(), Path("aaa"), Variant(std::map{ std::make_pair("bbb", "apples"), })); @@ -285,7 +285,7 @@ TEST(ViewProcessor, ApplyOperationServerOverwrite_DistantDescendantChange) { // Make sure the data being updated is deeply nested in the variant. Operation operation = Operation::Overwrite( - OperationSource::kServer, Path("aaa/bbb/ccc"), Variant(-9999)); + OperationSource::Server(), Path("aaa/bbb/ccc"), Variant(-9999)); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path()); @@ -355,7 +355,8 @@ TEST(ViewProcessor, ApplyOperationUserMerge) { .AddWrite(Path("aaa/bbb/ccc"), Variant("apples")) .AddWrite(Path("aaa/ddd"), Variant("bananas")) .AddWrite(Path("aaa/eee/fff"), Variant("vegetables")); - Operation operation = Operation::Merge(OperationSource::kUser, Path(), write); + Operation operation = + Operation::Merge(OperationSource::User(), Path(), write); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path()); Variant complete_cache; @@ -450,7 +451,7 @@ TEST(ViewProcessor, ApplyOperationServerMerge) { .AddWrite(Path("bbb/ddd"), Variant("bananas")) .AddWrite(Path("bbb/eee/fff"), Variant("vegetables")); Operation operation = - Operation::Merge(OperationSource::kServer, Path("aaa"), write); + Operation::Merge(OperationSource::Server(), Path("aaa"), write); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path("aaa")); @@ -696,7 +697,7 @@ TEST(ViewProcessor, ApplyOperationListenComplete) { // Create a server-initiated listen complete with an empty path to change a // value. Operation operation = - Operation::ListenComplete(OperationSource::kServer, Path()); + Operation::ListenComplete(OperationSource::Server(), Path()); WriteTree writes_cache; WriteTreeRef writes_cache_ref = writes_cache.ChildWrites(Path()); diff --git a/database/tests/static_destruction_test.cc b/database/tests/static_destruction_test.cc new file mode 100644 index 0000000000..afef5ed60b --- /dev/null +++ b/database/tests/static_destruction_test.cc @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A Database owned by a static object is destroyed during exit(), after main() +// has returned, and must still be able to remove itself from the SDK's +// registry of Database instances. See +// https://github.com/firebase/firebase-cpp-sdk/issues/110 for the Auth case. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "database/src/include/firebase/database.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace database { +namespace { + +// Owns Apps and Database instances the way an application-level singleton +// would. Members are destroyed in reverse order of declaration. +struct ExitTimeOwner { + // Destroyed after `app_destroyed_first`, so by then it has already been + // cleaned up by its App. + std::unique_ptr database_outliving_app; + std::unique_ptr app_destroyed_first; + + std::unique_ptr app; + // Destroyed before `app`, which is the documented order. + std::unique_ptr database; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + options.set_database_url("https://static-destruction-test.firebaseio.com"); + return options; +} + +TEST(DatabaseStaticDestructionTest, DatabaseOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + g_exit_time_owner.database.reset( + Database::GetInstance(g_exit_time_owner.app.get())); + ASSERT_NE(g_exit_time_owner.database, nullptr); + + g_exit_time_owner.app_destroyed_first.reset( + App::Create(TestAppOptions(), "app_destroyed_first")); + ASSERT_NE(g_exit_time_owner.app_destroyed_first, nullptr); + g_exit_time_owner.database_outliving_app.reset( + Database::GetInstance(g_exit_time_owner.app_destroyed_first.get())); + ASSERT_NE(g_exit_time_owner.database_outliving_app, nullptr); +} + +} // namespace +} // namespace database +} // namespace firebase diff --git a/firestore/CMakeLists.txt b/firestore/CMakeLists.txt index a278e26c96..3292ca4252 100644 --- a/firestore/CMakeLists.txt +++ b/firestore/CMakeLists.txt @@ -414,6 +414,12 @@ target_compile_definitions(firebase_firestore PUBLIC -DPB_FIELD_32BIT -DPB_ENABLE_MALLOC -DPB_NO_PACKED_STRUCTS ) +# firebase_cpp_reject_exit_time_destructors() is not applied here. Firestore +# sources include firebase-ios-sdk headers that declare function-local +# statics with destructors (Firestore/core/src/api/stages.h, +# Firestore/core/src/model/field_index.h), which Clang reports in every +# translation unit that includes them. + if(ANDROID) firebase_cpp_proguard_file(firestore) diff --git a/firestore/src/android/firestore_android.cc b/firestore/src/android/firestore_android.cc index db2c74d4a1..611bd8500a 100644 --- a/firestore/src/android/firestore_android.cc +++ b/firestore/src/android/firestore_android.cc @@ -22,6 +22,7 @@ #include "app/src/assert.h" #include "app/src/embedded_file.h" #include "app/src/include/firebase/future.h" +#include "app/src/no_destructor.h" #include "app/src/reference_counted_future_impl.h" #include "firestore/firestore_resources.h" #include "firestore/src/android/aggregate_query_android.h" @@ -234,8 +235,11 @@ class JavaFirestoreMap { Global firestores_; }; -// init_mutex protects all the globals below. -Mutex init_mutex; // NOLINT +// InitMutex() protects all the globals below. +Mutex& InitMutex() { + static NoDestructor init_mutex; + return *init_mutex; +} int initialize_count = 0; Loader* global_loader = nullptr; @@ -296,7 +300,7 @@ FirestoreInternal::FirestoreInternal(App* app, const std::string& database_id) { /* static */ bool FirestoreInternal::Initialize(App* app) { - MutexLock init_lock(init_mutex); + MutexLock init_lock(InitMutex()); if (initialize_count == 0) { jni::Initialize(app->java_vm()); @@ -381,7 +385,7 @@ bool FirestoreInternal::Initialize(App* app) { /* static */ void FirestoreInternal::ReleaseClassesLocked(Env& env) { - // Assumes `init_mutex` is held. + // Assumes `InitMutex()` is held. String::Terminate(env); delete global_loader; @@ -390,7 +394,7 @@ void FirestoreInternal::ReleaseClassesLocked(Env& env) { /* static */ void FirestoreInternal::Terminate(App* app) { - MutexLock init_lock(init_mutex); + MutexLock init_lock(InitMutex()); FIREBASE_ASSERT(initialize_count > 0); initialize_count--; if (initialize_count == 0) { @@ -676,7 +680,7 @@ void Firestore::set_log_level(LogLevel log_level) { bool logging_enabled = log_level < LogLevel::kLogLevelInfo; { - MutexLock lock(init_mutex); + MutexLock lock(InitMutex()); // Set the initial_log_state on every invocation, just in case Firestore // is terminated for long enough to unload the Firestore classes within diff --git a/firestore/src/common/util.cc b/firestore/src/common/util.cc index 67a795e586..a8717c44e4 100644 --- a/firestore/src/common/util.cc +++ b/firestore/src/common/util.cc @@ -16,12 +16,14 @@ #include "firestore/src/common/util.h" +#include "app/src/no_destructor.h" + namespace firebase { namespace firestore { const std::string& EmptyString() { - static const std::string kEmptyString; - return kEmptyString; + static const NoDestructor kEmptyString; + return *kEmptyString; } } // namespace firestore diff --git a/functions/CMakeLists.txt b/functions/CMakeLists.txt index 62d3b0fe06..e9407bf861 100644 --- a/functions/CMakeLists.txt +++ b/functions/CMakeLists.txt @@ -82,6 +82,8 @@ target_compile_definitions(firebase_functions -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_functions) + if(ANDROID) firebase_cpp_proguard_file(functions) elseif(IOS) @@ -105,5 +107,10 @@ elseif(IOS) endif() endif() +if(FIREBASE_CPP_BUILD_TESTS) + # Add the tests subdirectory + add_subdirectory(tests) +endif() + cpp_pack_library(firebase_functions "") cpp_pack_public_headers() diff --git a/functions/src/android/functions_android.cc b/functions/src/android/functions_android.cc index 0d2df8a711..93b6dfd15f 100644 --- a/functions/src/android/functions_android.cc +++ b/functions/src/android/functions_android.cc @@ -19,6 +19,7 @@ #include #include "app/src/include/firebase/app.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "app/src/util_android.h" #include "functions/src/android/callable_reference_android.h" @@ -102,7 +103,10 @@ METHOD_LOOKUP_DEFINITION( "com/google/firebase/functions/FirebaseFunctionsException$Code", FUNCTIONS_EXCEPTION_CODE_METHODS) -Mutex FunctionsInternal::init_mutex_; // NOLINT +static Mutex& InitMutex() { + static NoDestructor init_mutex; + return *init_mutex; +} int FunctionsInternal::initialize_count_ = 0; FunctionsInternal::FunctionsInternal(App* app, const char* region) @@ -142,7 +146,7 @@ FunctionsInternal::~FunctionsInternal() { } bool FunctionsInternal::Initialize(App* app) { - MutexLock init_lock(init_mutex_); + MutexLock init_lock(InitMutex()); if (initialize_count_ == 0) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); @@ -162,7 +166,7 @@ bool FunctionsInternal::Initialize(App* app) { } void FunctionsInternal::Terminate(App* app) { - MutexLock init_lock(init_mutex_); + MutexLock init_lock(InitMutex()); assert(initialize_count_ > 0); initialize_count_--; if (initialize_count_ == 0) { diff --git a/functions/src/android/functions_android.h b/functions/src/android/functions_android.h index 21a9f234e2..0d04011469 100644 --- a/functions/src/android/functions_android.h +++ b/functions/src/android/functions_android.h @@ -92,7 +92,6 @@ class FunctionsInternal { // Initialize classes loaded from embedded files. static bool InitializeEmbeddedClasses(App* app); - static Mutex init_mutex_; static int initialize_count_; static std::map java_error_to_cpp_; diff --git a/functions/src/common/functions.cc b/functions/src/common/functions.cc index df262eeac5..1acdca4824 100644 --- a/functions/src/common/functions.cc +++ b/functions/src/common/functions.cc @@ -27,6 +27,7 @@ #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" // QueryInternal is defined in these 3 files, one implementation for each OS. @@ -54,7 +55,13 @@ DEFINE_FIREBASE_VERSION_STRING(FirebaseFunctions); constexpr const char* kDefaultRegion = "us-central1"; -Mutex g_functions_lock; // NOLINT +// Function-local static wrapped in NoDestructor so it is constructed on first +// use and never destroyed; a Functions owned by a static object can still lock +// it from its destructor during process exit. +static Mutex& FunctionsLock() { + static NoDestructor mutex; + return *mutex; +} static std::map, Functions*>* g_functions = nullptr; @@ -65,7 +72,7 @@ Functions* Functions::GetInstance(::firebase::App* app, Functions* Functions::GetInstance(::firebase::App* app, const char* region, InitResult* init_result_out) { - MutexLock lock(g_functions_lock); + MutexLock lock(FunctionsLock()); if (!g_functions) { g_functions = new std::map, Functions*>(); } @@ -118,7 +125,7 @@ Functions::Functions(::firebase::App* app, const char* region) { Functions::~Functions() { DeleteInternal(); } void Functions::DeleteInternal() { - MutexLock lock(g_functions_lock); + MutexLock lock(FunctionsLock()); if (!internal_) return; diff --git a/functions/tests/CMakeLists.txt b/functions/tests/CMakeLists.txt new file mode 100644 index 0000000000..fa51bb4b05 --- /dev/null +++ b/functions/tests/CMakeLists.txt @@ -0,0 +1,21 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +firebase_cpp_cc_test( + firebase_functions_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_functions +) diff --git a/functions/tests/static_destruction_test.cc b/functions/tests/static_destruction_test.cc new file mode 100644 index 0000000000..d991fee041 --- /dev/null +++ b/functions/tests/static_destruction_test.cc @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A Functions owned by a static object is destroyed during exit(), after main() +// has returned, and must still be able to remove itself from the SDK's +// registry of Functions instances. See +// https://github.com/firebase/firebase-cpp-sdk/issues/110 for the Auth case. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "functions/src/include/firebase/functions.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace functions { +namespace { + +// Owns Apps and Functions instances the way an application-level singleton +// would. Members are destroyed in reverse order of declaration. +struct ExitTimeOwner { + // Destroyed after `app_destroyed_first`, so by then it has already been + // cleaned up by its App. + std::unique_ptr functions_outliving_app; + std::unique_ptr app_destroyed_first; + + std::unique_ptr app; + // Destroyed before `app`, which is the documented order. + std::unique_ptr functions; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + return options; +} + +TEST(FunctionsStaticDestructionTest, + FunctionsOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + g_exit_time_owner.functions.reset( + Functions::GetInstance(g_exit_time_owner.app.get())); + ASSERT_NE(g_exit_time_owner.functions, nullptr); + + g_exit_time_owner.app_destroyed_first.reset( + App::Create(TestAppOptions(), "app_destroyed_first")); + ASSERT_NE(g_exit_time_owner.app_destroyed_first, nullptr); + g_exit_time_owner.functions_outliving_app.reset( + Functions::GetInstance(g_exit_time_owner.app_destroyed_first.get())); + ASSERT_NE(g_exit_time_owner.functions_outliving_app, nullptr); +} + +} // namespace +} // namespace functions +} // namespace firebase diff --git a/installations/CMakeLists.txt b/installations/CMakeLists.txt index 1ead2dfd92..758490a713 100644 --- a/installations/CMakeLists.txt +++ b/installations/CMakeLists.txt @@ -65,6 +65,8 @@ target_compile_definitions(firebase_installations -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_installations) + if(ANDROID) firebase_cpp_proguard_file(installations) elseif(IOS) diff --git a/installations/src/android/installations_android.cc b/installations/src/android/installations_android.cc index 73344b19ce..18fc5545b1 100644 --- a/installations/src/android/installations_android.cc +++ b/installations/src/android/installations_android.cc @@ -14,6 +14,7 @@ #include "installations/src/android/installations_android.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "app/src/util_android.h" #include "installations/src/common.h" @@ -55,7 +56,10 @@ METHOD_LOOKUP_DEFINITION( using firebase::internal::ReferenceCount; using firebase::internal::ReferenceCountLock; -ReferenceCount internal::InstallationsInternal::initializer_; // NOLINT +static ReferenceCount& Initializer() { + static NoDestructor initializer; + return *initializer; +} template struct FISDataHandle { @@ -134,8 +138,8 @@ void TokenResultCallback(JNIEnv* env, jobject result, } InstallationsInternal::InstallationsInternal(const firebase::App& app) - : app_(app), future_impl_(kInstallationsFnCount) { - ReferenceCountLock lock(&initializer_); + : app_(app), future_impl_(kInstallationsFnCount), internal_obj_(nullptr) { + ReferenceCountLock lock(&Initializer()); static const char* kApiIdentifier = "Installations"; LogDebug("%s API Initializing", kApiIdentifier); JNIEnv* env = app_.GetJNIEnv(); @@ -166,16 +170,31 @@ InstallationsInternal::InstallationsInternal(const firebase::App& app) jobject installations_instance_local = env->CallStaticObjectMethod( installations_class, installations::GetMethodId(installations::kGetInstance), platform_app); + env->DeleteLocalRef(platform_app); + if (util::CheckAndClearJniExceptions(env)) { + installations_instance_local = nullptr; + } FIREBASE_ASSERT(installations_instance_local); + if (!installations_instance_local) { + // FIREBASE_ASSERT() does not abort when the application installed its own + // log callback. Initialized() is false from here on, so Cleanup() is never + // called for this instance: drop the reference taken above. + if (lock.RemoveReference() == 1) { + ReleaseClasses(env); + util::Terminate(env); + } + return; + } internal_obj_ = env->NewGlobalRef(installations_instance_local); env->DeleteLocalRef(installations_instance_local); - env->DeleteLocalRef(platform_app); LogDebug("%s API Initialized", kApiIdentifier); } InstallationsInternal::~InstallationsInternal() { - JNIEnv* env = app_.GetJNIEnv(); - util::CancelCallbacks(env, jni_task_id_.c_str()); + if (Initialized()) { + JNIEnv* env = app_.GetJNIEnv(); + util::CancelCallbacks(env, jni_task_id_.c_str()); + } } bool InstallationsInternal::Initialized() const { @@ -183,7 +202,7 @@ bool InstallationsInternal::Initialized() const { } void InstallationsInternal::Cleanup() { - ReferenceCountLock lock(&initializer_); + ReferenceCountLock lock(&Initializer()); if (lock.RemoveReference() == 1) { JNIEnv* env = app_.GetJNIEnv(); ReleaseClasses(env); diff --git a/installations/src/android/installations_android.h b/installations/src/android/installations_android.h index d709d378ea..897b9a90af 100644 --- a/installations/src/android/installations_android.h +++ b/installations/src/android/installations_android.h @@ -54,8 +54,6 @@ class InstallationsInternal { void Cleanup(); private: - static firebase::internal::ReferenceCount initializer_; - const firebase::App& app_; /// Handle calls from Futures that the API returns. diff --git a/installations/src/installations.cc b/installations/src/installations.cc index 792e7a846f..9d9bc9b7a3 100644 --- a/installations/src/installations.cc +++ b/installations/src/installations.cc @@ -18,21 +18,41 @@ #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/internal/mutex.h" +#include "app/src/no_destructor.h" #include "installations/src/installations_internal.h" namespace firebase { namespace installations { std::map* g_installations = nullptr; // NOLINT -Mutex g_installations_mutex; // NOLINT + +// Function-local static wrapped in NoDestructor so it is constructed on first +// use and never destroyed; an Installations instance owned by a static object +// can still lock it from its destructor during process exit. +static Mutex& InstallationsMutex() { + static NoDestructor mutex; + return *mutex; +} using internal::InstallationsInternal; +// Must be called with InstallationsMutex() held. +static Installations* FindInstallationsLocked(App* app) { + if (!g_installations) { + return nullptr; + } + std::map::iterator it = g_installations->find(app); + if (it != g_installations->end()) { + return it->second; + } + return nullptr; +} + Installations* Installations::GetInstance(App* app) { - MutexLock lock(g_installations_mutex); + MutexLock lock(InstallationsMutex()); // Return the Installations if it already exists. - Installations* existing_installations = FindInstallations(app); + Installations* existing_installations = FindInstallationsLocked(app); if (existing_installations) { // Log heartbeat data when instance getters are called. // See go/firebase-platform-logging-design for more information. @@ -62,52 +82,31 @@ Installations* Installations::GetInstance(App* app) { // Stick it in the global map so we remember it, and can delete it on // shutdown. + if (!g_installations) { + g_installations = new std::map(); // NOLINT + } (*g_installations)[app] = installations; return installations; } + delete installations; return nullptr; } Installations* Installations::FindInstallations(App* app) { - MutexLock lock(g_installations_mutex); - if (!g_installations) { - g_installations = new std::map(); // NOLINT - return nullptr; - } - - // Return the Installations if it already exists. - std::map::iterator it = - g_installations->find(app); // NOLINT - if (it != g_installations->end()) { - return it->second; - } - return nullptr; + MutexLock lock(InstallationsMutex()); + return FindInstallationsLocked(app); } +// Private constructor called only from GetInstance() while InstallationsMutex() +// is already held. Installations::Installations(App* app) : app_(app) { - MutexLock lock(g_installations_mutex); + FIREBASE_ASSERT(app != nullptr); installations_internal_ = new InstallationsInternal(*app); } Installations::~Installations() { - MutexLock lock(g_installations_mutex); - - CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app_); - if (notifier) { - notifier->UnregisterObject(this); - } - DeleteInternal(); - - if (g_installations) { - // Remove installations from the g_installations map. - g_installations->erase(app_); - if (g_installations->empty()) { - delete g_installations; - g_installations = nullptr; - } - } app_ = nullptr; } @@ -116,36 +115,68 @@ bool Installations::InitInternal() { } void Installations::DeleteInternal() { - MutexLock lock(g_installations_mutex); + MutexLock lock(InstallationsMutex()); if (!installations_internal_) return; + // An instance whose initialization failed was never registered with the + // App's CleanupNotifier, added to g_installations, or left holding JNI/iOS + // class references. + if (!installations_internal_->Initialized()) { + delete installations_internal_; + installations_internal_ = nullptr; + return; + } + + CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app_); + if (notifier) { + notifier->UnregisterObject(this); + } + installations_internal_->Cleanup(); delete installations_internal_; installations_internal_ = nullptr; + + if (g_installations) { + // Remove installations from the g_installations map on both App-destruction + // cleanup and ~Installations() so a recreated App at the same address never + // finds a gutted Installations shell. + g_installations->erase(app_); + if (g_installations->empty()) { + delete g_installations; + g_installations = nullptr; + } + } } Future Installations::GetId() { - return installations_internal_->GetId(); + return installations_internal_ ? installations_internal_->GetId() + : Future(); } Future Installations::GetIdLastResult() { - return installations_internal_->GetIdLastResult(); + return installations_internal_ ? installations_internal_->GetIdLastResult() + : Future(); } Future Installations::GetToken(bool forceRefresh) { - return installations_internal_->GetToken(forceRefresh); + return installations_internal_ + ? installations_internal_->GetToken(forceRefresh) + : Future(); } Future Installations::GetTokenLastResult() { - return installations_internal_->GetTokenLastResult(); + return installations_internal_ ? installations_internal_->GetTokenLastResult() + : Future(); } Future Installations::Delete() { - return installations_internal_->Delete(); + return installations_internal_ ? installations_internal_->Delete() + : Future(); } Future Installations::DeleteLastResult() { - return installations_internal_->DeleteLastResult(); + return installations_internal_ ? installations_internal_->DeleteLastResult() + : Future(); } } // namespace installations diff --git a/installations/src/stub/installations_stub.cc b/installations/src/stub/installations_stub.cc index f221c378e2..7f8b099153 100644 --- a/installations/src/stub/installations_stub.cc +++ b/installations/src/stub/installations_stub.cc @@ -21,14 +21,22 @@ namespace installations { namespace internal { +static bool g_initialization_fails_for_testing = false; + InstallationsInternal::InstallationsInternal(const firebase::App& app) - : app_(app), future_impl_(kInstallationsFnCount) {} + : app_(app), + initialized_(!g_initialization_fails_for_testing), + future_impl_(kInstallationsFnCount) {} InstallationsInternal::~InstallationsInternal() {} void InstallationsInternal::LogHeartbeat(const firebase::App& app) {} -bool InstallationsInternal::Initialized() const { return true; } +bool InstallationsInternal::Initialized() const { return initialized_; } + +void InstallationsInternal::SetInitializationFailsForTesting(bool fails) { + g_initialization_fails_for_testing = fails; +} void InstallationsInternal::Cleanup() {} diff --git a/installations/src/stub/installations_stub.h b/installations/src/stub/installations_stub.h index 3471aaaace..23b2d61653 100644 --- a/installations/src/stub/installations_stub.h +++ b/installations/src/stub/installations_stub.h @@ -48,9 +48,16 @@ class InstallationsInternal { void Cleanup(); + // Makes instances constructed from now on report Initialized() == false, so + // that tests can reach the failed-initialization path of + // Installations::GetInstance(), which no desktop build takes otherwise. + static void SetInitializationFailsForTesting(bool fails); + private: const firebase::App& app_; // NOLINT + const bool initialized_; + /// Handle calls from Futures that the API returns. ReferenceCountedFutureImpl future_impl_; }; diff --git a/installations/tests/CMakeLists.txt b/installations/tests/CMakeLists.txt index 92e1300d04..6bfb990728 100644 --- a/installations/tests/CMakeLists.txt +++ b/installations/tests/CMakeLists.txt @@ -21,3 +21,11 @@ firebase_cpp_cc_test( firebase_installations firebase_testing ) + +firebase_cpp_cc_test( + firebase_installations_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_installations +) diff --git a/installations/tests/installations_test.cc b/installations/tests/installations_test.cc index 247be8ac69..b5bf25f387 100644 --- a/installations/tests/installations_test.cc +++ b/installations/tests/installations_test.cc @@ -33,6 +33,7 @@ #include "app/src/time.h" #include "app/tests/include/firebase/app_for_testing.h" #include "installations/src/include/firebase/installations.h" +#include "installations/src/installations_internal.h" // [END installations_includes] #if defined(FIREBASE_ANDROID_FOR_DESKTOP) @@ -46,6 +47,7 @@ #include "testing/ticker.h" using testing::Eq; +using testing::IsNull; using testing::NotNull; namespace firebase { @@ -144,5 +146,54 @@ TEST_F(InstallationsTest, GetTokenForceRefresh) { delete installations; } +TEST_F(InstallationsTest, DestroyAppBeforeInstallationsClearsCachedInstance) { + Installations* installations1 = Installations::GetInstance(firebase_app_); + ASSERT_THAT(installations1, NotNull()); + CheckSuccessWithValue(installations1->GetId(), std::string("FakeId")); + + // Deleting the App first runs CleanupNotifier -> DeleteInternal(), which + // tears down installations_internal_ and removes the entry from the per-App + // map so a recreated App cannot observe a gutted Installations shell. + delete firebase_app_; + firebase_app_ = nullptr; + EXPECT_EQ(installations1->GetId().status(), kFutureStatusInvalid); + + firebase_app_ = testing::CreateApp(); + ASSERT_THAT(firebase_app_, NotNull()); + + Installations* installations2 = Installations::GetInstance(firebase_app_); + ASSERT_THAT(installations2, NotNull()); + EXPECT_NE(installations2, installations1); + CheckSuccessWithValue(installations2->GetId(), std::string("FakeId")); + + // Deleting the already-cleaned-up installations1 (for example from a + // late-running static std::unique_ptr destructor) must be a no-op and must + // not evict installations2 even if the allocator reused the App* address. + delete installations1; + EXPECT_EQ(Installations::GetInstance(firebase_app_), installations2); + CheckSuccessWithValue(installations2->GetId(), std::string("FakeId")); + + delete installations2; +} + +#if FIREBASE_PLATFORM_DESKTOP && !defined(FIREBASE_ANDROID_FOR_DESKTOP) +// Only the desktop implementation can be told to fail initialization. +TEST_F(InstallationsTest, GetInstanceReturnsNullWhenInitializationFails) { + internal::InstallationsInternal::SetInitializationFailsForTesting(true); + // GetInstance() also has to delete the instance it could not initialize; + // only a leak checker can see that part. + Installations* failed_installations = + Installations::GetInstance(firebase_app_); + internal::InstallationsInternal::SetInitializationFailsForTesting(false); + EXPECT_THAT(failed_installations, IsNull()); + + // The instance that failed to initialize must not be cached for the App. + Installations* installations = Installations::GetInstance(firebase_app_); + ASSERT_THAT(installations, NotNull()); + CheckSuccessWithValue(installations->GetId(), std::string("FakeId")); + delete installations; +} +#endif // FIREBASE_PLATFORM_DESKTOP && !defined(FIREBASE_ANDROID_FOR_DESKTOP) + } // namespace installations } // namespace firebase diff --git a/installations/tests/static_destruction_test.cc b/installations/tests/static_destruction_test.cc new file mode 100644 index 0000000000..14b776464c --- /dev/null +++ b/installations/tests/static_destruction_test.cc @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A Installations owned by a static object is destroyed during exit(), after +// main() has returned, and must still be able to remove itself from the SDK's +// registry of Installations instances. See +// https://github.com/firebase/firebase-cpp-sdk/issues/110 for the Auth case. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "gtest/gtest.h" +#include "installations/src/include/firebase/installations.h" + +namespace firebase { +namespace installations { +namespace { + +// Owns Apps and Installations instances the way an application-level singleton +// would. Members are destroyed in reverse order of declaration. +struct ExitTimeOwner { + // Destroyed after `app_destroyed_first`, so by then it has already been + // cleaned up by its App. + std::unique_ptr installations_outliving_app; + std::unique_ptr app_destroyed_first; + + std::unique_ptr app; + // Destroyed before `app`, which is the documented order. + std::unique_ptr installations; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + return options; +} + +TEST(InstallationsStaticDestructionTest, + InstallationsOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + g_exit_time_owner.installations.reset( + Installations::GetInstance(g_exit_time_owner.app.get())); + ASSERT_NE(g_exit_time_owner.installations, nullptr); + + g_exit_time_owner.app_destroyed_first.reset( + App::Create(TestAppOptions(), "app_destroyed_first")); + ASSERT_NE(g_exit_time_owner.app_destroyed_first, nullptr); + g_exit_time_owner.installations_outliving_app.reset( + Installations::GetInstance(g_exit_time_owner.app_destroyed_first.get())); + ASSERT_NE(g_exit_time_owner.installations_outliving_app, nullptr); +} + +} // namespace +} // namespace installations +} // namespace firebase diff --git a/messaging/CMakeLists.txt b/messaging/CMakeLists.txt index a45ace818e..7f81123b97 100644 --- a/messaging/CMakeLists.txt +++ b/messaging/CMakeLists.txt @@ -101,6 +101,8 @@ target_compile_definitions(firebase_messaging -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_messaging) + if(ANDROID) firebase_cpp_proguard_file(messaging) diff --git a/messaging/src/android/cpp/messaging.cc b/messaging/src/android/cpp/messaging.cc index 74a8f2ea46..bdf26f33ff 100644 --- a/messaging/src/android/cpp/messaging.cc +++ b/messaging/src/android/cpp/messaging.cc @@ -35,6 +35,7 @@ #include "app/src/include/firebase/internal/mutex.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util.h" #include "app/src/util_android.h" @@ -72,7 +73,10 @@ static const ::firebase::App* g_app = nullptr; // Mutex used to arbitrate access to g_app between the thread calling this // module and MessageProcessingThread(). -static Mutex g_app_mutex; +static Mutex& AppMutex() { + static NoDestructor app_mutex; + return *app_mutex; +} // Global reference to the Firebase Cloud Messaging instance. // This is initialized in messaging::Initialize() and never released @@ -126,7 +130,10 @@ static std::string* g_lockfile_path; static Mutex* g_file_locker_mutex; // Mutex for managing if FutureData is safe to use, or if it has been deleted. -static Mutex g_future_data_mutex; +static Mutex& FutureDataMutex() { + static NoDestructor future_data_mutex; + return *future_data_mutex; +} static const char* kMessagingNotInitializedError = "Messaging not initialized."; @@ -312,7 +319,7 @@ static void ConsumeEvents() { // thread knows that it is time to quit. static bool TerminateRequested() { bool result; - MutexLock lock(g_app_mutex); + MutexLock lock(AppMutex()); // If the app is removed, Terminate() has been called. result = !g_app; return result; @@ -352,7 +359,7 @@ Future RequestPermissionLastResult() { void ProcessMessages() { JNIEnv* env; { - MutexLock lock(g_app_mutex); + MutexLock lock(AppMutex()); env = g_app ? g_app->GetJNIEnv() : nullptr; } if (HasListener() && env) { @@ -370,7 +377,7 @@ void ProcessMessages() { static void* MessageProcessingThread(void*) { JavaVM* jvm; { - MutexLock lock(g_app_mutex); + MutexLock lock(AppMutex()); jvm = g_app ? g_app->java_vm() : nullptr; if (jvm == nullptr) return nullptr; } @@ -513,7 +520,7 @@ static void FireIntentMessage(JNIEnv* env) { g_intent_message_fired = true; jobject activity; { - MutexLock lock(g_app_mutex); + MutexLock lock(AppMutex()); if (!g_app) return; activity = env->NewLocalRef(g_app->activity()); assert(env->ExceptionCheck() == false); @@ -601,7 +608,7 @@ InitResult Initialize(const ::firebase::App& app, Listener* listener, } { - MutexLock lock(g_app_mutex); + MutexLock lock(AppMutex()); g_app = &app; } g_registration_token_mutex = new Mutex(); @@ -699,7 +706,7 @@ void Terminate() { util::CancelCallbacks(env, kApiIdentifier); // Dereference the app. { - MutexLock lock(g_app_mutex); + MutexLock lock(AppMutex()); g_app = nullptr; } TerminateMessageProcessingThread(); @@ -726,7 +733,7 @@ void Terminate() { ReleaseClasses(env); util::Terminate(env); { - MutexLock lock(g_future_data_mutex); + MutexLock lock(FutureDataMutex()); FutureData::Destroy(); } } @@ -853,7 +860,7 @@ static void CompleteVoidCallback(JNIEnv* env, jobject result, FutureHandle handle(future_id); Error error = (result_code == util::kFutureResultSuccess) ? kErrorNone : kErrorUnknown; - MutexLock lock(g_future_data_mutex); + MutexLock lock(FutureDataMutex()); if (FutureData::Get() && FutureData::Get()->api()) { ReferenceCountedFutureImpl* api = FutureData::Get()->api(); api->Complete(handle, error, status_message); @@ -875,7 +882,7 @@ static void CompleteStringCallback(JNIEnv* env, jobject result, SafeFutureHandle* handle = reinterpret_cast*>(callback_data); Error error = success ? kErrorNone : kErrorUnknown; - MutexLock lock(g_future_data_mutex); + MutexLock lock(FutureDataMutex()); if (FutureData::Get() && FutureData::Get()->api()) { ReferenceCountedFutureImpl* api = FutureData::Get()->api(); api->CompleteWithResult(*handle, error, status_message, result_value); diff --git a/messaging/src/common.cc b/messaging/src/common.cc index 786cf13cae..feb5bf855c 100644 --- a/messaging/src/common.cc +++ b/messaging/src/common.cc @@ -23,6 +23,7 @@ #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/include/firebase/internal/mutex.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "messaging/src/include/firebase/messaging.h" @@ -45,7 +46,10 @@ FIREBASE_APP_REGISTER_CALLBACKS( namespace firebase { namespace messaging { -static Mutex g_listener_lock; // NOLINT +static Mutex& ListenerLock() { + static NoDestructor listener_lock; + return *listener_lock; +} static Listener* g_listener = nullptr; // Keep track of the most recent token received. @@ -94,7 +98,7 @@ void UnregisterTerminateOnDefaultAppDestroy() { } // namespace internal Listener* SetListener(Listener* listener) { - MutexLock lock(g_listener_lock); + MutexLock lock(ListenerLock()); Listener* previous_listener = g_listener; if (listener && !g_prev_token_received) { g_prev_token_received = new std::string; @@ -135,7 +139,7 @@ Listener* SetListener(Listener* listener) { // Determine whether a listener is present. bool HasListener() { - MutexLock lock(g_listener_lock); + MutexLock lock(ListenerLock()); return g_listener != nullptr; } @@ -144,12 +148,12 @@ Listener* SetListenerIfNotNull(Listener* listener) { } void NotifyListenerOnMessage(const Message& message) { - MutexLock lock(g_listener_lock); + MutexLock lock(ListenerLock()); if (g_listener) g_listener->OnMessage(message); } void NotifyListenerOnTokenReceived(const char* token) { - MutexLock lock(g_listener_lock); + MutexLock lock(ListenerLock()); // If we have a previous token that we've notified any listener about, check // to ensure no repeat. if (g_prev_token_received && *g_prev_token_received == token) { @@ -172,7 +176,7 @@ void NotifyListenerOnRegistrationReceived(const char* installationId) { if (!installationId || installationId[0] == '\0') { return; } - MutexLock lock(g_listener_lock); + MutexLock lock(ListenerLock()); if (!g_prev_registration_received) g_prev_registration_received = new std::string; *g_prev_registration_received = installationId; @@ -188,7 +192,7 @@ void NotifyListenerOnUnregistrationReceived(const char* installationId) { if (!installationId || installationId[0] == '\0') { return; } - MutexLock lock(g_listener_lock); + MutexLock lock(ListenerLock()); // If the unregistration is for a pending registration that we haven't sent to // a listener yet, clear the pending state. if (g_prev_registration_received && diff --git a/messaging/src/ios/messaging.mm b/messaging/src/ios/messaging.mm index 83d02305f8..c6ab195e5c 100644 --- a/messaging/src/ios/messaging.mm +++ b/messaging/src/ios/messaging.mm @@ -32,6 +32,7 @@ #include "app/src/include/firebase/internal/mutex.h" #include "app/src/include/firebase/version.h" #include "app/src/log.h" +#include "app/src/no_destructor.h" #include "app/src/util_ios.h" #include "messaging/src/common.h" @@ -79,11 +80,14 @@ + (NSString *)normalizeTopic:(NSString *)topic; DEFINE_FIREBASE_VERSION_STRING(FirebaseMessaging); static FIRCppDelegate *g_delegate = nil; -static Mutex g_delegate_mutex; // Mutex for g_delegate's properties +static Mutex& DelegateMutex() { + static NoDestructor delegate_mutex; // Mutex for g_delegate's properties + return *delegate_mutex; +} static MessagingOptions g_messaging_options; static bool MessagingIsInitialized() { - MutexLock lock(g_delegate_mutex); + MutexLock lock(DelegateMutex()); return g_delegate.isListenerSet; } @@ -126,7 +130,10 @@ static bool MessagingIsInitialized() { static bool g_message_notification_opened = false; -static SafeFutureHandle g_permission_prompt_future_handle; +static SafeFutureHandle& PermissionPromptFutureHandle() { + static NoDestructor> handle; + return *handle; +} static void RetrieveRegistrationToken(); @@ -150,7 +157,7 @@ InitResult Initialize( if (!g_app) { #if !defined(NDEBUG) { - MutexLock lock(g_delegate_mutex); + MutexLock lock(DelegateMutex()); assert(!g_delegate.isListenerSet); } #endif // !defined(NDEBUG) @@ -171,7 +178,7 @@ void NotifyListenerSet(Listener* listener) { // If no listener is specified, or the API is already initialized, do nothing. if (!listener) return; { - MutexLock lock(g_delegate_mutex); + MutexLock lock(DelegateMutex()); if (g_delegate.isListenerSet) return; g_delegate.isListenerSet = YES; } @@ -190,7 +197,7 @@ void NotifyListenerSet(Listener* listener) { // Create the future. ReferenceCountedFutureImpl* api = FutureData::Get()->api(); - g_permission_prompt_future_handle = + PermissionPromptFutureHandle() = api->SafeAlloc(kMessagingFnRequestPermission); // Run on UI thread. dispatch_async(dispatch_get_main_queue(), ^{ @@ -250,7 +257,7 @@ void NotifyListenerSet(Listener* listener) { g_launch_notification = nil; } }); - return MakeFuture(api, g_permission_prompt_future_handle); + return MakeFuture(api, PermissionPromptFutureHandle()); } Future RequestPermissionLastResult() { @@ -280,7 +287,7 @@ void Terminate() { // Ensure g_delegate still exists (it cannot be unallocated in case a token is received via a // different Firebase library e.g. Invites while Messaging is not enabled). { - MutexLock lock(g_delegate_mutex); + MutexLock lock(DelegateMutex()); g_delegate.isListenerSet = NO; g_delegate.cachedMessaging = nil; g_delegate.cachedFCMToken = nil; @@ -344,9 +351,9 @@ static void CompletePermissionFuture(::firebase::messaging::Error error) { ::firebase::ReferenceCountedFutureImpl* api = ::firebase::messaging::FutureData::Get()->api(); // The ReferenceCountedFutureImpl object should be initialized in Initialize(). FIREBASE_ASSERT_RETURN_VOID(api != nullptr); - if (api->ValidFuture(::firebase::messaging::g_permission_prompt_future_handle) && + if (api->ValidFuture(::firebase::messaging::PermissionPromptFutureHandle()) && RequestPermissionLastResult().status() == kFutureStatusPending) { - api->Complete(::firebase::messaging::g_permission_prompt_future_handle, error); + api->Complete(::firebase::messaging::PermissionPromptFutureHandle(), error); } } else { LogError("Attempting to complete future before FCM initialized."); @@ -974,30 +981,30 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)notificationCenter @implementation FIRCppDelegate - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { - ::firebase::messaging::g_delegate_mutex.Acquire(); + ::firebase::messaging::DelegateMutex().Acquire(); if (_isListenerSet) { - ::firebase::messaging::g_delegate_mutex.Release(); + ::firebase::messaging::DelegateMutex().Release(); ::firebase::LogInfo("FCM: new registration token received."); ::firebase::messaging::RetrieveRegistrationToken(); } else { _cachedMessaging = messaging; _cachedFCMToken = fcmToken; - ::firebase::messaging::g_delegate_mutex.Release(); + ::firebase::messaging::DelegateMutex().Release(); ::firebase::LogInfo( "FCM: registration token received, but no listener set yet - cached the token."); } } - (void)messaging:(FIRMessaging *)messaging didReceiveRegistration:(NSString *)installationId { - ::firebase::messaging::g_delegate_mutex.Acquire(); + ::firebase::messaging::DelegateMutex().Acquire(); if (_isListenerSet) { - ::firebase::messaging::g_delegate_mutex.Release(); + ::firebase::messaging::DelegateMutex().Release(); ::firebase::LogInfo("FCM: registration installation ID received."); ::firebase::messaging::NotifyListenerOnRegistrationReceived(installationId.UTF8String); } else { _cachedMessaging = messaging; _cachedRegistrationId = installationId; - ::firebase::messaging::g_delegate_mutex.Release(); + ::firebase::messaging::DelegateMutex().Release(); ::firebase::LogInfo( "FCM: registration installation ID received, but no listener set yet - cached the ID."); } @@ -1013,7 +1020,7 @@ - (void)processCachedRegistrationToken { NSString *token; NSString *regId; { - firebase::MutexLock lock(::firebase::messaging::g_delegate_mutex); + firebase::MutexLock lock(::firebase::messaging::DelegateMutex()); // TODO(butterfield): What if there's no cached message but there is a cached token? // The user may never get notified of the old token before a new one is registered. if (!_isListenerSet) { diff --git a/messaging/src/stub/messaging.cc b/messaging/src/stub/messaging.cc index c07b69a4f8..75b735bb3e 100644 --- a/messaging/src/stub/messaging.cc +++ b/messaging/src/stub/messaging.cc @@ -37,6 +37,7 @@ #include #include "app/src/include/firebase/internal/mutex.h" +#include "app/src/no_destructor.h" #endif // FIREBASE_MESSAGING_TEST_ENABLED namespace firebase { @@ -48,7 +49,10 @@ static bool g_initialized = false; #if FIREBASE_MESSAGING_TEST_ENABLED static pthread_t g_message_thread; -static Mutex g_message_thread_mutex; // NOLINT +static Mutex& MessageThreadMutex() { + static NoDestructor message_thread_mutex; + return *message_thread_mutex; +} static bool g_message_thread_run; static const int kMessageIntervalMilliseconds = 5000; #endif // FIREBASE_MESSAGING_TEST_ENABLED @@ -61,7 +65,7 @@ static void* MessageTestThread(void* arg) { int time_elapsed_milliseconds = 0; for (;;) { { - MutexLock lock(g_message_thread_mutex); + MutexLock lock(MessageThreadMutex()); if (!g_message_thread_run) break; } // Wait until kMessageIntervalMilliseconds has elapsed. @@ -103,7 +107,7 @@ InitResult Initialize(const ::firebase::App& /*app*/, Listener* listener, FutureData::Create(); #if FIREBASE_MESSAGING_TEST_ENABLED { - MutexLock lock(g_message_thread_mutex); + MutexLock lock(MessageThreadMutex()); if (g_message_thread_run) return kInitResultSuccess; g_message_thread_run = true; pthread_attr_t attr; @@ -129,7 +133,7 @@ void Terminate() { internal::UnregisterTerminateOnDefaultAppDestroy(); #if FIREBASE_MESSAGING_TEST_ENABLED { - MutexLock lock(g_message_thread_mutex); + MutexLock lock(MessageThreadMutex()); if (!g_message_thread_run) return; g_message_thread_run = false; } diff --git a/messaging/tests/CMakeLists.txt b/messaging/tests/CMakeLists.txt index dd3ed3a3b6..d177faaae1 100644 --- a/messaging/tests/CMakeLists.txt +++ b/messaging/tests/CMakeLists.txt @@ -76,3 +76,11 @@ if(ANDROID OR IOS) ) endif() + +firebase_cpp_cc_test( + firebase_messaging_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_messaging +) diff --git a/messaging/tests/static_destruction_test.cc b/messaging/tests/static_destruction_test.cc new file mode 100644 index 0000000000..2091e5c439 --- /dev/null +++ b/messaging/tests/static_destruction_test.cc @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A static object that owns a messaging::Listener unregisters it and +// terminates Messaging from its destructor during exit(), after main() has +// returned. Both calls must still be able to lock Messaging's listener state. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "gtest/gtest.h" +#include "messaging/src/include/firebase/messaging.h" + +namespace firebase { +namespace messaging { +namespace { + +class NoOpListener : public Listener { + public: + void OnMessage(const Message& /*message*/) override {} + void OnTokenReceived(const char* /*token*/) override {} +}; + +// Owns the App and the listener the way an application-level singleton would. +struct ExitTimeOwner { + ~ExitTimeOwner() { + if (!initialized) return; + SetListener(nullptr); + Terminate(); + } + + std::unique_ptr app; + NoOpListener listener; + bool initialized = false; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +TEST(MessagingStaticDestructionTest, ListenerOwnedByStaticIsRemovedAfterMain) { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + options.set_messaging_sender_id("1234567890"); + g_exit_time_owner.app.reset(App::Create(options)); + ASSERT_NE(g_exit_time_owner.app, nullptr); + + ASSERT_EQ(Initialize(*g_exit_time_owner.app, &g_exit_time_owner.listener), + kInitResultSuccess); + g_exit_time_owner.initialized = true; +} + +} // namespace +} // namespace messaging +} // namespace firebase diff --git a/release_build_files/readme.md b/release_build_files/readme.md index 46566c6817..c8984a6263 100644 --- a/release_build_files/readme.md +++ b/release_build_files/readme.md @@ -613,6 +613,19 @@ workflow use only during the development of your app, not for publicly shipping code. ## Release Notes +### Upcoming +- Changes + - General: Fixed a crash at process exit when an `App` or Firebase product + instance (`Analytics`, `AppCheck`, `Auth`, `Database`, `Firestore`, + `Functions`, `Installations`, `Messaging`, `RemoteConfig`, `Storage`, or + `UMP`) is owned by a static object (for example a static + `std::unique_ptr`) and destroyed after the SDK's own globals. + ([#110](https://github.com/firebase/firebase-cpp-sdk/issues/110)) + - Installations: Fixed a crash when an `Installations` object is used + after its `App` has been destroyed. Its methods now return an invalid + `Future` in that state, and `Installations::GetInstance()` on a newly + created `App` returns a new instance instead of the stale one. + ### 14.2.0 - Changes - General (Android): Update to Firebase Android BoM version 35.2.0. diff --git a/remote_config/CMakeLists.txt b/remote_config/CMakeLists.txt index cf48e8d85e..ca21bdebd9 100644 --- a/remote_config/CMakeLists.txt +++ b/remote_config/CMakeLists.txt @@ -140,6 +140,8 @@ target_compile_definitions(firebase_remote_config -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_remote_config) + if(ANDROID) firebase_cpp_proguard_file(remote_config) elseif(IOS) diff --git a/remote_config/src/android/remote_config_android.cc b/remote_config/src/android/remote_config_android.cc index 66cf18c821..bb992e43ab 100644 --- a/remote_config/src/android/remote_config_android.cc +++ b/remote_config/src/android/remote_config_android.cc @@ -25,6 +25,7 @@ #include "app/src/embedded_file.h" #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/version.h" +#include "app/src/no_destructor.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/time.h" #include "app/src/util.h" @@ -254,7 +255,10 @@ static const ValueSource kFirebaseRemoteConfigSourceToValueSourceMap[] = { kValueSourceRemoteValue, // FirebaseRemoteConfig.VALUE_SOURCE_REMOTE (2) }; -ReferenceCount RemoteConfigInternal::initializer_; // NOLINT +static ReferenceCount& Initializer() { + static NoDestructor initializer; + return *initializer; +} static bool CacheJNIMethodIds( JNIEnv* env, jobject activity, @@ -672,8 +676,8 @@ struct ConfigUpdateListenerWrapper { }; RemoteConfigInternal::RemoteConfigInternal(const firebase::App& app) - : app_(app), future_impl_(kRemoteConfigFnCount) { - ReferenceCountLock lock(&initializer_); + : app_(app), future_impl_(kRemoteConfigFnCount), internal_obj_(nullptr) { + ReferenceCountLock lock(&Initializer()); LogDebug("Firebase RemoteConfig API Initializing"); static const char* kApiIdentifier = "Remote Config"; jni_task_id_ = CreateApiIdentifier(kApiIdentifier, this); @@ -711,6 +715,16 @@ RemoteConfigInternal::RemoteConfigInternal(const firebase::App& app) env->DeleteLocalRef(platform_app); if (util::CheckAndClearJniExceptions(env)) config_instance_local = nullptr; FIREBASE_ASSERT(config_instance_local); + if (!config_instance_local) { + // FIREBASE_ASSERT() does not abort when the application installed its own + // log callback. Initialized() is false from here on, so Cleanup() is never + // called for this instance: drop the reference taken above. + if (lock.RemoveReference() == 1) { + ReleaseClasses(env); + util::Terminate(env); + } + return; + } internal_obj_ = env->NewGlobalRef(config_instance_local); env->DeleteLocalRef(config_instance_local); LogDebug("%s API Initialized", kApiIdentifier); @@ -722,8 +736,10 @@ RemoteConfigInternal::~RemoteConfigInternal() { // ConfigUpdateListenerRegistration instances to no longer point to the // corresponding internal objects. cleanup_notifier().CleanupAll(); - JNIEnv* env = app_.GetJNIEnv(); - util::CancelCallbacks(env, jni_task_id_.c_str()); + if (Initialized()) { + JNIEnv* env = app_.GetJNIEnv(); + util::CancelCallbacks(env, jni_task_id_.c_str()); + } } bool RemoteConfigInternal::Initialized() const { @@ -731,7 +747,7 @@ bool RemoteConfigInternal::Initialized() const { } void RemoteConfigInternal::Cleanup() { - ReferenceCountLock lock(&initializer_); + ReferenceCountLock lock(&Initializer()); if (lock.RemoveReference() == 1) { JNIEnv* env = app_.GetJNIEnv(); ReleaseClasses(env); diff --git a/remote_config/src/android/remote_config_android.h b/remote_config/src/android/remote_config_android.h index 8f85bc1d6d..dae7814596 100644 --- a/remote_config/src/android/remote_config_android.h +++ b/remote_config/src/android/remote_config_android.h @@ -108,7 +108,6 @@ class RemoteConfigInternal { } private: - static firebase::internal::ReferenceCount initializer_; // app const firebase::App& app_; diff --git a/remote_config/src/desktop/remote_config_desktop.cc b/remote_config/src/desktop/remote_config_desktop.cc index b2ba2a52e2..5be7a97b00 100644 --- a/remote_config/src/desktop/remote_config_desktop.cc +++ b/remote_config/src/desktop/remote_config_desktop.cc @@ -49,6 +49,8 @@ const bool RemoteConfigInternal::kDefaultValueForBool = false; static const char* kFilePathSuffix = "remote_config_data"; +static bool g_initialization_fails_for_testing = false; + template struct RCDataHandle { RCDataHandle( @@ -101,11 +103,15 @@ RemoteConfigInternal::~RemoteConfigInternal() { void RemoteConfigInternal::InternalInit() { file_manager_.Load(&configs_); AsyncSaveToFile(); - initialized_ = true; + initialized_ = !g_initialization_fails_for_testing; } bool RemoteConfigInternal::Initialized() const { return initialized_; } +void RemoteConfigInternal::SetInitializationFailsForTesting(bool fails) { + g_initialization_fails_for_testing = fails; +} + void RemoteConfigInternal::Cleanup() { // Do nothing. } diff --git a/remote_config/src/desktop/remote_config_desktop.h b/remote_config/src/desktop/remote_config_desktop.h index 566fb4f854..cc715cd55a 100644 --- a/remote_config/src/desktop/remote_config_desktop.h +++ b/remote_config/src/desktop/remote_config_desktop.h @@ -146,6 +146,11 @@ class RemoteConfigInternal { static Variant StringToVariant(const std::string& from); bool Initialized() const; + + // Makes instances constructed from now on report Initialized() == false, so + // that tests can reach the failed-initialization path of + // RemoteConfig::GetInstance(), which no desktop build takes otherwise. + static void SetInitializationFailsForTesting(bool fails); void Cleanup(); // When this is deleted, it will clean up all ListenerRegistrations. diff --git a/remote_config/src/remote_config.cc b/remote_config/src/remote_config.cc index 0c6b0a3c27..0494f11ea2 100644 --- a/remote_config/src/remote_config.cc +++ b/remote_config/src/remote_config.cc @@ -20,6 +20,7 @@ #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/internal/mutex.h" #include "app/src/include/firebase/internal/platform.h" +#include "app/src/no_destructor.h" #include "app/src/semaphore.h" #include "app/src/time.h" #include "include/firebase/remote_config.h" @@ -39,13 +40,41 @@ namespace firebase { namespace remote_config { -std::map g_rcs; -Mutex g_rc_mutex; // NOLINT +// The global map of Apps to RemoteConfigs. +// +// The map and its mutex are function-local statics wrapped in NoDestructor, +// so they are constructed on first use and never destroyed. That keeps them +// out of static initialization and destruction entirely: they are ready no +// matter which translation unit's initializers run first, and a RemoteConfig +// owned by a static (e.g. a static std::unique_ptr) can still be +// destroyed safely after this file's globals would otherwise have been torn +// down by the C++ runtime. The mutex in particular could never be destroyed +// safely, since another thread may be about to lock it. +using RemoteConfigMap = std::map; + +static RemoteConfigMap& RemoteConfigs() { + static NoDestructor remote_configs; + return *remote_configs; +} + +static Mutex& RemoteConfigsMutex() { + static NoDestructor mutex; + return *mutex; +} + +// Must be called with RemoteConfigsMutex() held. +static RemoteConfig* FindRemoteConfigLocked(App* app) { + RemoteConfigMap::iterator it = RemoteConfigs().find(app); + if (it != RemoteConfigs().end()) { + return it->second; + } + return nullptr; +} RemoteConfig* RemoteConfig::GetInstance(App* app) { - MutexLock lock(g_rc_mutex); + MutexLock lock(RemoteConfigsMutex()); // Return the RemoteConfig if it already exists. - RemoteConfig* existing_rc = FindRemoteConfig(app); + RemoteConfig* existing_rc = FindRemoteConfigLocked(app); if (existing_rc) { return existing_rc; } @@ -68,29 +97,32 @@ RemoteConfig* RemoteConfig::GetInstance(App* app) { rc->DeleteInternal(); }); - // Stick it in the global map so we remember it, and can delete it on - // shutdown. - g_rcs[app] = rc; + RemoteConfigs()[app] = rc; return rc; } + delete rc; return nullptr; } RemoteConfig* RemoteConfig::FindRemoteConfig(App* app) { - MutexLock lock(g_rc_mutex); - // Return the RemoteConfig if it already exists. - std::map::iterator it = g_rcs.find(app); - if (it != g_rcs.end()) { - return it->second; - } - return nullptr; + MutexLock lock(RemoteConfigsMutex()); + return FindRemoteConfigLocked(app); } void RemoteConfig::DeleteInternal() { - MutexLock lock(g_rc_mutex); + MutexLock lock(RemoteConfigsMutex()); if (!internal_) return; + // An instance whose initialization failed was never registered with the + // App's CleanupNotifier, added to RemoteConfigs(), or left holding JNI/iOS + // class references. + if (!internal_->Initialized()) { + delete internal_; + internal_ = nullptr; + return; + } + CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app()); assert(notifier); notifier->UnregisterObject(this); @@ -99,8 +131,8 @@ void RemoteConfig::DeleteInternal() { delete internal_; internal_ = nullptr; - // Remove rc from the g_rcs map. - g_rcs.erase(app()); + // Remove rc from the RemoteConfigs map. + RemoteConfigs().erase(app()); } RemoteConfig::RemoteConfig(App* app) { diff --git a/remote_config/tests/CMakeLists.txt b/remote_config/tests/CMakeLists.txt index d42f99818a..11475a4114 100644 --- a/remote_config/tests/CMakeLists.txt +++ b/remote_config/tests/CMakeLists.txt @@ -72,3 +72,11 @@ firebase_cpp_cc_test( DEFINES -DFIREBASE_TESTING ) + +firebase_cpp_cc_test( + firebase_remote_config_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_remote_config +) diff --git a/remote_config/tests/desktop/remote_config_desktop_test.cc b/remote_config/tests/desktop/remote_config_desktop_test.cc index 910ad938c3..9c42660f95 100644 --- a/remote_config/tests/desktop/remote_config_desktop_test.cc +++ b/remote_config/tests/desktop/remote_config_desktop_test.cc @@ -25,6 +25,7 @@ #include "remote_config/src/desktop/config_data.h" #include "remote_config/src/desktop/file_manager.h" #include "remote_config/src/desktop/metadata.h" +#include "remote_config/src/include/firebase/remote_config.h" namespace firebase { namespace remote_config { @@ -596,6 +597,51 @@ TEST_F(RemoteConfigDesktopTest, SetCustomSignalsPersistence) { EXPECT_EQ(loaded_signals.at("persisted_num"), Variant(999)); } +TEST(RemoteConfigInstanceTest, + DestroyAppBeforeRemoteConfigClearsCachedInstance) { + App* app = testing::CreateApp(); + ASSERT_NE(app, nullptr); + RemoteConfig* remote_config1 = RemoteConfig::GetInstance(app); + ASSERT_NE(remote_config1, nullptr); + + // Deleting the App first cleans up remote_config1 and removes it from the + // per-App map, so a recreated App gets a new RemoteConfig. + delete app; + app = testing::CreateApp(); + ASSERT_NE(app, nullptr); + RemoteConfig* remote_config2 = RemoteConfig::GetInstance(app); + ASSERT_NE(remote_config2, nullptr); + EXPECT_NE(remote_config2, remote_config1); + + // Deleting the already cleaned-up remote_config1 must not evict + // remote_config2, even if the allocator reused the App's address. + delete remote_config1; + EXPECT_EQ(RemoteConfig::GetInstance(app), remote_config2); + + delete remote_config2; + delete app; +} + +TEST(RemoteConfigInstanceTest, GetInstanceReturnsNullWhenInitializationFails) { + App* app = testing::CreateApp(); + ASSERT_NE(app, nullptr); + + RemoteConfigInternal::SetInitializationFailsForTesting(true); + // GetInstance() also has to delete the instance it could not initialize; + // only a leak checker can see that part. + RemoteConfig* failed_remote_config = RemoteConfig::GetInstance(app); + RemoteConfigInternal::SetInitializationFailsForTesting(false); + EXPECT_EQ(failed_remote_config, nullptr); + + // The instance that failed to initialize must not be cached for the App. + RemoteConfig* remote_config = RemoteConfig::GetInstance(app); + ASSERT_NE(remote_config, nullptr); + EXPECT_EQ(RemoteConfig::GetInstance(app), remote_config); + + delete remote_config; + delete app; +} + } // namespace internal } // namespace remote_config } // namespace firebase diff --git a/remote_config/tests/static_destruction_test.cc b/remote_config/tests/static_destruction_test.cc new file mode 100644 index 0000000000..f236460940 --- /dev/null +++ b/remote_config/tests/static_destruction_test.cc @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A RemoteConfig owned by a static object is destroyed during exit(), after +// main() has returned, and must still be able to remove itself from the SDK's +// registry of RemoteConfig instances. See +// https://github.com/firebase/firebase-cpp-sdk/issues/110 for the Auth case. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "gtest/gtest.h" +#include "remote_config/src/include/firebase/remote_config.h" + +namespace firebase { +namespace remote_config { +namespace { + +// Owns Apps and RemoteConfig instances the way an application-level singleton +// would. Members are destroyed in reverse order of declaration. +struct ExitTimeOwner { + // Destroyed after `app_destroyed_first`, so by then it has already been + // cleaned up by its App. + std::unique_ptr remote_config_outliving_app; + std::unique_ptr app_destroyed_first; + + std::unique_ptr app; + // Destroyed before `app`, which is the documented order. + std::unique_ptr remote_config; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + return options; +} + +TEST(RemoteConfigStaticDestructionTest, + RemoteConfigOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + g_exit_time_owner.remote_config.reset( + RemoteConfig::GetInstance(g_exit_time_owner.app.get())); + ASSERT_NE(g_exit_time_owner.remote_config, nullptr); + + g_exit_time_owner.app_destroyed_first.reset( + App::Create(TestAppOptions(), "app_destroyed_first")); + ASSERT_NE(g_exit_time_owner.app_destroyed_first, nullptr); + g_exit_time_owner.remote_config_outliving_app.reset( + RemoteConfig::GetInstance(g_exit_time_owner.app_destroyed_first.get())); + ASSERT_NE(g_exit_time_owner.remote_config_outliving_app, nullptr); +} + +} // namespace +} // namespace remote_config +} // namespace firebase diff --git a/scripts/gha/check_exit_time_destructors.py b/scripts/gha/check_exit_time_destructors.py new file mode 100644 index 0000000000..b3068d7fac --- /dev/null +++ b/scripts/gha/check_exit_time_destructors.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python + +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Checks that Firebase static libraries register no exit-time destructors. + +A static or global C++ object with a non-trivial destructor makes the compiler +register that destructor with `__cxa_atexit` (or `atexit`). SDK state destroyed +that way can be used afterwards by user-owned static Firebase objects, so the +SDK keeps such state in `firebase::NoDestructor` (app/src/no_destructor.h). + +Clang builds enforce this with -Werror=exit-time-destructors (see +cmake/exit_time_destructors.cmake). This script enforces it for compilers +without that diagnostic, such as GCC, by looking for object files that +reference the registration functions. + +Usage, from the root of the repo, after building into build/: + +$ python3 scripts/gha/check_exit_time_destructors.py build/ +""" + +import argparse +import os +import re +import subprocess +import sys + +# Libraries that must not register exit-time destructors. firebase_firestore is +# not listed: it includes firebase-ios-sdk headers that declare function-local +# statics with destructors. +CHECKED_LIBRARIES = ( + 'libfirebase_analytics.a', + 'libfirebase_app.a', + 'libfirebase_app_check.a', + 'libfirebase_auth.a', + 'libfirebase_database.a', + 'libfirebase_functions.a', + 'libfirebase_installations.a', + 'libfirebase_messaging.a', + 'libfirebase_remote_config.a', + 'libfirebase_rest_lib.a', + 'libfirebase_storage.a', + 'libfirebase_ump.a', +) + +# Undefined symbols that register a destructor to run at exit. Mach-O prefixes +# C symbols with an extra underscore. +REGISTRATION_SYMBOL = re.compile(r'^_?(__cxa_atexit|atexit)$') + + +def find_libraries(build_dir): + """Finds the checked libraries under a build directory. + + Args: + build_dir (str): Directory to search recursively. + + Returns: + dict(str, str): Path of each library that was found, keyed by file name. + """ + found = {} + for dirpath, _, filenames in os.walk(build_dir): + for filename in filenames: + if filename in CHECKED_LIBRARIES: + found.setdefault(filename, os.path.join(dirpath, filename)) + return found + + +def find_offending_objects(library, nm): + """Lists the object files in a library that register exit-time destructors. + + Args: + library (str): Path to a static library. + nm (str): The nm executable to run. + + Returns: + list(str): "object: symbol" for each offending reference. + """ + # -A prefixes each line with "library:object:", -u lists undefined symbols. + output = subprocess.run([nm, '-A', '-u', library], check=True, + stdout=subprocess.PIPE, universal_newlines=True).stdout + offenders = [] + for line in output.splitlines(): + fields = line.split() + if not fields or not REGISTRATION_SYMBOL.match(fields[-1]): + continue + object_file = fields[0].rstrip(':').split(':')[-1] + offenders.append('%s: %s' % (object_file, fields[-1])) + return offenders + + +def main(): + args = parse_cmdline_args() + libraries = find_libraries(args.build_dir) + missing = sorted(set(CHECKED_LIBRARIES) - set(libraries)) + if missing and not args.allow_missing: + print('Libraries not found under %s: %s' % (args.build_dir, + ', '.join(missing))) + return 1 + + failed = False + for name in sorted(libraries): + offenders = find_offending_objects(libraries[name], args.nm) + if not offenders: + print('OK: %s' % libraries[name]) + continue + failed = True + print('FAILED: %s registers exit-time destructors:' % libraries[name]) + for offender in offenders: + print(' %s' % offender) + if failed: + print('Wrap the static objects defined in the files above in ' + 'firebase::NoDestructor (app/src/no_destructor.h).') + return 1 if failed else 0 + + +def parse_cmdline_args(): + parser = argparse.ArgumentParser( + description='Check Firebase static libraries for exit-time destructors.') + parser.add_argument('build_dir', + help='Build directory to search for libraries.') + parser.add_argument('--nm', default='nm', help='The nm executable to use.') + parser.add_argument('--allow_missing', action='store_true', + help='Do not fail when a checked library was not built.') + return parser.parse_args() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/storage/CMakeLists.txt b/storage/CMakeLists.txt index 147bfdc18e..c7fe813e76 100644 --- a/storage/CMakeLists.txt +++ b/storage/CMakeLists.txt @@ -111,6 +111,8 @@ target_compile_definitions(firebase_storage ${additional_DEFINES} ) +firebase_cpp_reject_exit_time_destructors(firebase_storage) + if(ANDROID) firebase_cpp_proguard_file(storage) elseif(IOS) diff --git a/storage/src/android/storage_android.cc b/storage/src/android/storage_android.cc index 3619794a55..457d3b3e60 100644 --- a/storage/src/android/storage_android.cc +++ b/storage/src/android/storage_android.cc @@ -22,6 +22,7 @@ #include "app/src/embedded_file.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/common.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "app/src/util_android.h" #include "storage/src/android/controller_android.h" @@ -136,7 +137,10 @@ METHOD_LOOKUP_DEFINITION( "com/google/firebase/storage/internal/cpp/CppByteUploader", CPP_BYTE_UPLOADER_METHODS) -Mutex StorageInternal::init_mutex_; // NOLINT +static Mutex& InitMutex() { + static NoDestructor init_mutex; + return *init_mutex; +} int StorageInternal::initialize_count_ = 0; std::map* StorageInternal::java_error_to_cpp_ = nullptr; @@ -206,7 +210,7 @@ static const struct { }; bool StorageInternal::Initialize(App* app) { - MutexLock init_lock(init_mutex_); + MutexLock init_lock(InitMutex()); if (initialize_count_ == 0) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); @@ -283,7 +287,7 @@ bool StorageInternal::InitializeEmbeddedClasses(App* app) { } void StorageInternal::Terminate(App* app) { - MutexLock init_lock(init_mutex_); + MutexLock init_lock(InitMutex()); FIREBASE_ASSERT_RETURN_VOID(initialize_count_ > 0); initialize_count_--; if (initialize_count_ == 0) { diff --git a/storage/src/android/storage_android.h b/storage/src/android/storage_android.h index b25fa42e03..d8dfdf1641 100644 --- a/storage/src/android/storage_android.h +++ b/storage/src/android/storage_android.h @@ -127,7 +127,6 @@ class StorageInternal { // Initialize classes loaded from embedded files. static bool InitializeEmbeddedClasses(App* app); - static Mutex init_mutex_; static int initialize_count_; static std::map* java_error_to_cpp_; diff --git a/storage/src/common/list_result.cc b/storage/src/common/list_result.cc index 1aafac0b47..04b3fdce24 100644 --- a/storage/src/common/list_result.cc +++ b/storage/src/common/list_result.cc @@ -14,6 +14,7 @@ #include "firebase/storage/list_result.h" +#include "app/src/no_destructor.h" #include "list_result_internal.h" namespace firebase { @@ -59,18 +60,18 @@ StorageListResult& StorageListResult::operator=(StorageListResult&& other) { #endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) const std::vector& StorageListResult::prefixes() const { - static const std::vector empty_vector; - return internal_ ? internal_->prefixes_ : empty_vector; + static const NoDestructor> empty_vector; + return internal_ ? internal_->prefixes_ : *empty_vector; } const std::vector& StorageListResult::items() const { - static const std::vector empty_vector; - return internal_ ? internal_->items_ : empty_vector; + static const NoDestructor> empty_vector; + return internal_ ? internal_->items_ : *empty_vector; } const std::string& StorageListResult::next_page_token() const { - static const std::string empty_string; - return internal_ ? internal_->next_page_token_ : empty_string; + static const NoDestructor empty_string; + return internal_ ? internal_->next_page_token_ : *empty_string; } bool StorageListResult::is_valid() const { return internal_ != nullptr; } diff --git a/storage/src/common/storage.cc b/storage/src/common/storage.cc index 3c995042b1..cdc37cf00f 100644 --- a/storage/src/common/storage.cc +++ b/storage/src/common/storage.cc @@ -26,6 +26,7 @@ #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" +#include "app/src/no_destructor.h" #include "app/src/util.h" #include "storage/src/common/storage_uri_parser.h" @@ -52,7 +53,13 @@ namespace storage { DEFINE_FIREBASE_VERSION_STRING(FirebaseStorage); -Mutex g_storages_lock; // NOLINT +// Function-local static wrapped in NoDestructor so it is constructed on first +// use and never destroyed; a Storage owned by a static object can still lock it +// from its destructor during process exit. +static Mutex& StoragesLock() { + static NoDestructor mutex; + return *mutex; +} static std::map, Storage*>* g_storages = nullptr; Storage* Storage::GetInstance(::firebase::App* app, @@ -62,7 +69,7 @@ Storage* Storage::GetInstance(::firebase::App* app, Storage* Storage::GetInstance(::firebase::App* app, const char* url, InitResult* init_result_out) { - MutexLock lock(g_storages_lock); + MutexLock lock(StoragesLock()); if (!g_storages) { g_storages = new std::map, Storage*>(); } @@ -133,7 +140,7 @@ Storage::Storage(::firebase::App* app, const char* url) { } void Storage::DeleteInternal() { - MutexLock lock(g_storages_lock); + MutexLock lock(StoragesLock()); if (!internal_) return; // An instance whose initialization failed was never registered with the diff --git a/storage/src/desktop/metadata_desktop.cc b/storage/src/desktop/metadata_desktop.cc index 90121bf036..ef3553144b 100644 --- a/storage/src/desktop/metadata_desktop.cc +++ b/storage/src/desktop/metadata_desktop.cc @@ -19,7 +19,6 @@ #include #include -#include #include #include diff --git a/storage/src/desktop/storage_path.cc b/storage/src/desktop/storage_path.cc index c07766d987..cb98dc4cf7 100644 --- a/storage/src/desktop/storage_path.cc +++ b/storage/src/desktop/storage_path.cc @@ -16,7 +16,6 @@ #include -#include #include #include "app/rest/util.h" diff --git a/storage/tests/CMakeLists.txt b/storage/tests/CMakeLists.txt index d4ec18d6a0..b711e63ab8 100644 --- a/storage/tests/CMakeLists.txt +++ b/storage/tests/CMakeLists.txt @@ -23,3 +23,10 @@ firebase_cpp_cc_test( firebase_testing ) +firebase_cpp_cc_test( + firebase_storage_static_destruction_test + SOURCES + static_destruction_test.cc + DEPENDS + firebase_storage +) diff --git a/storage/tests/static_destruction_test.cc b/storage/tests/static_destruction_test.cc new file mode 100644 index 0000000000..68c4a889f7 --- /dev/null +++ b/storage/tests/static_destruction_test.cc @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A Storage owned by a static object is destroyed during exit(), after main() +// has returned, and must still be able to remove itself from the SDK's +// registry of Storage instances. See +// https://github.com/firebase/firebase-cpp-sdk/issues/110 for the Auth case. +// +// The checks happen after GoogleTest has reported its result, so a regression +// shows up as the test binary crashing or aborting on exit rather than as a +// failed expectation. + +#include + +#include "app/src/include/firebase/app.h" +#include "gtest/gtest.h" +#include "storage/src/include/firebase/storage.h" + +namespace firebase { +namespace storage { +namespace { + +// Owns Apps and Storage instances the way an application-level singleton +// would. Members are destroyed in reverse order of declaration. +struct ExitTimeOwner { + // Destroyed after `app_destroyed_first`, so by then it has already been + // cleaned up by its App. + std::unique_ptr storage_outliving_app; + std::unique_ptr app_destroyed_first; + + std::unique_ptr app; + // Destroyed before `app`, which is the documented order. + std::unique_ptr storage; +}; + +// Constructed during static initialization of this translation unit, which the +// linker places ahead of the SDK's libraries, so it is destroyed after any +// static the SDK itself registers for destruction at exit. +ExitTimeOwner g_exit_time_owner; + +AppOptions TestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("static-destruction-test"); + options.set_storage_bucket("static-destruction-test.appspot.com"); + return options; +} + +TEST(StorageStaticDestructionTest, StorageOwnedByStaticIsDestroyedAfterMain) { + g_exit_time_owner.app.reset(App::Create(TestAppOptions())); + ASSERT_NE(g_exit_time_owner.app, nullptr); + g_exit_time_owner.storage.reset( + Storage::GetInstance(g_exit_time_owner.app.get())); + ASSERT_NE(g_exit_time_owner.storage, nullptr); + + g_exit_time_owner.app_destroyed_first.reset( + App::Create(TestAppOptions(), "app_destroyed_first")); + ASSERT_NE(g_exit_time_owner.app_destroyed_first, nullptr); + g_exit_time_owner.storage_outliving_app.reset( + Storage::GetInstance(g_exit_time_owner.app_destroyed_first.get())); + ASSERT_NE(g_exit_time_owner.storage_outliving_app, nullptr); +} + +} // namespace +} // namespace storage +} // namespace firebase diff --git a/ump/CMakeLists.txt b/ump/CMakeLists.txt index 9442b1e069..f51ef06c41 100644 --- a/ump/CMakeLists.txt +++ b/ump/CMakeLists.txt @@ -77,6 +77,8 @@ target_compile_definitions(firebase_ump -DINTERNAL_EXPERIMENTAL=1 ) +firebase_cpp_reject_exit_time_destructors(firebase_ump) + if(ANDROID) firebase_cpp_proguard_file(ump) elseif(IOS) diff --git a/ump/src/android/consent_info_internal_android.cc b/ump/src/android/consent_info_internal_android.cc index 9c179679e9..a82174c428 100644 --- a/ump/src/android/consent_info_internal_android.cc +++ b/ump/src/android/consent_info_internal_android.cc @@ -23,6 +23,7 @@ #include #include "app/src/assert.h" +#include "app/src/no_destructor.h" #include "app/src/thread.h" #include "app/src/util_android.h" #include "firebase/internal/common.h" @@ -33,9 +34,16 @@ namespace ump { namespace internal { ConsentInfoInternalAndroid* ConsentInfoInternalAndroid::s_instance = nullptr; -firebase::Mutex ConsentInfoInternalAndroid::s_instance_mutex; -::firebase::Mutex g_cached_ump_embedded_files_mutex; +static firebase::Mutex& InstanceMutex() { + static NoDestructor instance_mutex; + return *instance_mutex; +} + +::firebase::Mutex& CachedUmpEmbeddedFilesMutex() { + static NoDestructor<::firebase::Mutex> cached_ump_embedded_files_mutex; + return *cached_ump_embedded_files_mutex; +} std::vector<::firebase::internal::EmbeddedFile>* g_cached_ump_embedded_files = nullptr; @@ -161,7 +169,7 @@ ConsentInfoInternalAndroid::~ConsentInfoInternalAndroid() { env->CallVoidMethod(helper_, consent_info_helper::GetMethodId( consent_info_helper::kDisconnect)); - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); s_instance = nullptr; env->DeleteGlobalRef(helper_); @@ -230,7 +238,7 @@ void ConsentInfoInternalAndroid::CacheEnumValues(JNIEnv* env) { void ConsentInfoInternalAndroid::JNI_ConsentInfoHelper_completeFuture( JNIEnv* env, jclass clazz, jint future_fn, jlong consent_info_internal_ptr, jlong future_handle, jint error_code, jobject error_message_obj) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (consent_info_internal_ptr == 0 || s_instance == nullptr) { // Calling this with a null pointer, or if there is no active // instance, is a no-op, so just return. @@ -259,7 +267,7 @@ ConsentInfoInternalAndroid::ConsentInfoInternalAndroid(JNIEnv* env, activity_(nullptr), helper_(nullptr), has_requested_consent_info_update_(false) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); FIREBASE_ASSERT(s_instance == nullptr); s_instance = this; @@ -268,8 +276,7 @@ ConsentInfoInternalAndroid::ConsentInfoInternalAndroid(JNIEnv* env, // Ensure we only load these files once. { - MutexLock lock( - ::firebase::ump::internal::g_cached_ump_embedded_files_mutex); + MutexLock lock(::firebase::ump::internal::CachedUmpEmbeddedFilesMutex()); if (::firebase::ump::internal::g_cached_ump_embedded_files == nullptr) { ::firebase::ump::internal::g_cached_ump_embedded_files = new std::vector(); diff --git a/ump/src/android/consent_info_internal_android.h b/ump/src/android/consent_info_internal_android.h index f5ab3b8916..ee79652240 100644 --- a/ump/src/android/consent_info_internal_android.h +++ b/ump/src/android/consent_info_internal_android.h @@ -48,7 +48,7 @@ bool RegisterNatives(); void ReleaseClasses(JNIEnv* env); namespace internal { -extern ::firebase::Mutex g_cached_ump_embedded_files_mutex; +::firebase::Mutex& CachedUmpEmbeddedFilesMutex(); extern std::vector<::firebase::internal::EmbeddedFile>* g_cached_ump_embedded_files; @@ -136,7 +136,6 @@ class ConsentInfoInternalAndroid : public ConsentInfoInternal { const EnumCache& enums() { return enums_; } static ConsentInfoInternalAndroid* s_instance; - static firebase::Mutex s_instance_mutex; EnumCache enums_; diff --git a/ump/src/ios/consent_info_internal_ios.h b/ump/src/ios/consent_info_internal_ios.h index f1db540258..69c46a0bda 100644 --- a/ump/src/ios/consent_info_internal_ios.h +++ b/ump/src/ios/consent_info_internal_ios.h @@ -50,7 +50,6 @@ class ConsentInfoInternalIos : public ConsentInfoInternal { private: static ConsentInfoInternalIos* s_instance; - static firebase::Mutex s_instance_mutex; static unsigned int s_instance_tag; void SetLoadedForm(UMPConsentForm *form) { diff --git a/ump/src/ios/consent_info_internal_ios.mm b/ump/src/ios/consent_info_internal_ios.mm index 437cf72833..f2217ba570 100644 --- a/ump/src/ios/consent_info_internal_ios.mm +++ b/ump/src/ios/consent_info_internal_ios.mm @@ -18,6 +18,7 @@ #include "ump/src/ios/consent_info_internal_ios.h" #include "app/src/assert.h" +#include "app/src/no_destructor.h" #include "app/src/thread.h" #include "app/src/util_ios.h" @@ -26,15 +27,19 @@ namespace internal { ConsentInfoInternalIos* ConsentInfoInternalIos::s_instance = nullptr; -firebase::Mutex ConsentInfoInternalIos::s_instance_mutex; unsigned int ConsentInfoInternalIos::s_instance_tag = 0; +static firebase::Mutex& InstanceMutex() { + static NoDestructor instance_mutex; + return *instance_mutex; +} + // This explicitly implements the constructor for the outer class, // ConsentInfoInternal. ConsentInfoInternal* ConsentInfoInternal::CreateInstance() { return new ConsentInfoInternalIos(); } ConsentInfoInternalIos::ConsentInfoInternalIos() : loaded_form_(nil) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); FIREBASE_ASSERT(s_instance == nullptr); s_instance = this; // Increment this with each created instance, to ensure that any leftover @@ -43,7 +48,7 @@ } ConsentInfoInternalIos::~ConsentInfoInternalIos() { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); s_instance = nullptr; } @@ -83,7 +88,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { Future ConsentInfoInternalIos::RequestConsentInfoUpdate( const ConsentRequestParameters& params) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (RequestConsentInfoUpdateLastResult().status() == kFutureStatusPending) { // This operation is already in progress. // Return a future with an error - this will not override the Fn entry. @@ -125,7 +130,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { callback_instance_tag = s_instance_tag; util::DispatchAsyncSafeMainQueue(^{ - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (!s_instance || s_instance_tag != callback_instance_tag) { // Instance changed or was invalidated, don't call the iOS method any more. return; @@ -133,7 +138,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { [UMPConsentInformation.sharedInstance requestConsentInfoUpdateWithParameters:ios_parameters completionHandler:^(NSError* _Nullable error) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (s_instance && s_instance_tag == callback_instance_tag) { if (!error) { CompleteFuture(handle, kConsentRequestSuccess); @@ -182,7 +187,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { } Future ConsentInfoInternalIos::LoadConsentForm() { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (LoadConsentFormLastResult().status() == kFutureStatusPending) { // This operation is already in progress. // Return a future with an error - this will not override the Fn entry. @@ -198,14 +203,14 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { callback_instance_tag = s_instance_tag; util::DispatchAsyncSafeMainQueue(^{ - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (!s_instance || s_instance_tag != callback_instance_tag) { // Instance changed or was invalidated, don't call the iOS method any more. return; } [UMPConsentForm loadWithCompletionHandler:^(UMPConsentForm* _Nullable form, NSError* _Nullable error) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (s_instance && s_instance_tag == callback_instance_tag) { if (form) { SetLoadedForm(form); @@ -223,7 +228,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { } Future ConsentInfoInternalIos::ShowConsentForm(FormParent parent) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (ShowConsentFormLastResult().status() == kFutureStatusPending) { // This operation is already in progress. // Return a future with an error - this will not override the Fn entry. @@ -241,14 +246,14 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { callback_instance_tag = s_instance_tag; util::DispatchAsyncSafeMainQueue(^{ - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (!s_instance || s_instance_tag != callback_instance_tag) { // Instance changed or was invalidated, don't call the iOS method any more. return; } [loaded_form_ presentFromViewController:parent completionHandler:^(NSError* _Nullable error) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (s_instance && s_instance_tag == callback_instance_tag) { if (!error) { CompleteFuture(handle, kConsentRequestSuccess); @@ -264,7 +269,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { } Future ConsentInfoInternalIos::LoadAndShowConsentFormIfRequired(FormParent parent) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (LoadAndShowConsentFormIfRequiredLastResult().status() == kFutureStatusPending) { // This operation is already in progress. // Return a future with an error - this will not override the Fn entry. @@ -279,7 +284,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { callback_instance_tag = s_instance_tag; util::DispatchAsyncSafeMainQueue(^{ - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (!s_instance || s_instance_tag != callback_instance_tag) { // Instance changed or was invalidated, don't call the iOS method any more. return; @@ -287,7 +292,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { [UMPConsentForm loadAndPresentIfRequiredFromViewController:parent completionHandler:^(NSError* _Nullable error) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (s_instance && s_instance_tag == callback_instance_tag) { if (!error) { CompleteFuture(handle, kConsentRequestSuccess); @@ -320,7 +325,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { } Future ConsentInfoInternalIos::ShowPrivacyOptionsForm(FormParent parent) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (ShowPrivacyOptionsFormLastResult().status() == kFutureStatusPending) { // This operation is already in progress. // Return a future with an error - this will not override the Fn entry. @@ -334,7 +339,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { callback_instance_tag = s_instance_tag; util::DispatchAsyncSafeMainQueue(^{ - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (!s_instance || s_instance_tag != callback_instance_tag) { // Instance changed or was invalidated, don't call the iOS method any more. return; @@ -342,7 +347,7 @@ static ConsentFormError CppFormErrorFromIosFormError(NSInteger code) { [UMPConsentForm presentPrivacyOptionsFormFromViewController:parent completionHandler:^(NSError* _Nullable error) { - MutexLock lock(s_instance_mutex); + MutexLock lock(InstanceMutex()); if (s_instance && s_instance_tag == callback_instance_tag) { if (!error) { CompleteFuture(handle, kConsentRequestSuccess);