Skip to content

Fix use-after-free when Firebase instances are destroyed during static destruction - #1949

Open
AustinBenoit wants to merge 31 commits into
mainfrom
fix/static-destruction-order
Open

AustinBenoit wants to merge 31 commits into
mainfrom
fix/static-destruction-order

Conversation

@AustinBenoit

@AustinBenoit AustinBenoit commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #110.

An App or product object owned by a static (for example static std::unique_ptr<Auth>) is destroyed during exit(). On main, the SDK's own static maps, mutexes, and loggers can already be destroyed by then, causing use-after-free or destroyed-mutex crashes.

This PR makes the SDK's statics outlive user objects, following the Google C++ Style Guide:

  • firebase::NoDestructor<T> (app/src/no_destructor.h), modeled on absl::NoDestructor: constructs a function-local static on first use and never destroys it.
  • Migrates SDK statics with exit-time destructors across firebase_app and all product libraries. Pre-existing heap-allocated statics are unchanged.
  • Enforces no regressions in CI: Clang CI builds enable -Werror=exit-time-destructors; Linux GCC jobs check all 12 non-Firestore archives with scripts/gha/check_exit_time_destructors.py.
  • Removes 5 unused #include <iostream> directives (each adds a std::ios_base::Init exit-time destructor on libstdc++ before GCC 13).

Behavior fixes found along the way:

  • Installations: destroying App before Installations now unregisters the cached instance; subsequent methods return an invalid Future instead of crashing.
  • Installations, Remote Config: instances that fail initialization are deleted instead of leaked.
  • Auth, App: Auth::DeleteInternal() erases its registry entry by key, and RemoveApp() ignores an unregistered App.

Known limits:

  • SDK statics are intentionally never destroyed, so leak checkers that report still-reachable memory will list them ([Bug] MemoryLeak #1446).
  • Firestore is migrated but excluded from enforcement because upstream firebase-ios-sdk headers declare statics with destructors.
  • MSVC has no -Wexit-time-destructors equivalent, so Windows-only sources are not checked automatically.

Testing

  • CI (05a86c00): 38/38 checks pass — all Desktop/Android/iOS builds, lint/format/docs checks, Linux archive check (12/12), and unit tests (118/118 on Linux ×4 and Windows Release x64).
  • Integration tests (0ee1ef54, before merging main #1987/#1988): run 45539928789 — 0 test failures across all 132 executed test apps (no flakes/retries):
    • Desktop (5 configs: Linux/Windows OpenSSL + BoringSSL, macOS BoringSSL): 55/55 pass.
    • Android real devices (3 host builds): 33/33 pass.
    • Android emulators (3 host builds): 33/33 pass.
    • iOS simulator: 11/11 pass.
    • iOS real devices (ios_target): 0 started — Firebase Test Lab currently rejects the configured iOS 16.6 device models (same failure on main). Last real-device iOS pass was run 43934762162 on d7f01ae5.
  • New unit/regression tests: post-main() static-destruction tests per product (all 8 product tests abort on main and pass here), NoDestructor unit tests, and regression tests for the behavior fixes above.
  • Sanitizers: Use after free triggered on application exit #110 repro (static App + Auth) hits ASan heap-use-after-free on main and is clean here; unmasked ASan+UBSan and TSan show no issues in PR code.
  • Enforcement proof: a throwaway negative-control branch adding one static std::string in app/src/app_common.cc failed macOS and Android Clang builds on that line and failed the Linux archive check; iOS CI build logs confirm -Werror=exit-time-destructors on all 11 non-Firestore targets.
  • Not covered: CI does not run unit tests on macOS or iOS.

Type of Change

Related (not fixed here): #1446. Follow-up to #345. Unity SDK SWIG-layer statics need a separate follow-up in firebase-unity-sdk.


Notes

  • Bug fixes and feature changes require an update to the Release Notes section of release_build_files/readme.md.
  • Read the contribution guidelines CONTRIBUTING.md.

Each product keeps a process-wide map of App -> instance plus a mutex, and
both are touched from the instance's destructor via DeleteInternal(). When
a user holds an instance in a static (e.g. a static std::unique_ptr<Auth>)
that is destroyed after the SDK's own globals, the destructor accesses an
already-destroyed map or mutex.

Auth and Remote Config stored the map as a static std::map, which produced a
heap-use-after-free in ~Auth()/~RemoteConfig(). Database, Storage, Functions,
Installations and App Check already heap-allocated the map but still used a
static Mutex, which is destroyed at exit before the lock in DeleteInternal().

Bring every product in line with the layout App and Firestore already use:
the map is lazily allocated and freed when the last instance goes away, and
the mutex is allocated once and never freed.

Fixes #110

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a potential crash at process exit by ensuring that global mutexes and maps for various Firebase SDK components (Auth, RemoteConfig, Database, Storage, Functions, Installations, and AppCheck) are handled safely. The changes involve dynamically allocating these objects to prevent destruction order issues during C++ runtime shutdown. The reviewer correctly identified that the current implementation of global mutex initialization is susceptible to the Static Initialization Order Fiasco (SIOF) and suggested using a function-local static pointer ('construct on first use' idiom) to mitigate this risk.

Comment thread app_check/src/common/app_check.cc Resolved
Comment thread app_check/src/common/app_check.cc Resolved
Comment thread app_check/src/common/app_check.cc Resolved
Comment thread app_check/src/common/app_check.cc Resolved
Comment thread database/src/common/database.cc Resolved
Comment thread remote_config/src/remote_config.cc Resolved
Comment thread remote_config/src/remote_config.cc Resolved
Comment thread storage/src/common/storage.cc Resolved
Comment thread storage/src/common/storage.cc Resolved
Comment thread storage/src/common/storage.cc Resolved
@AustinBenoit
AustinBenoit marked this pull request as draft October 26, 2026 15:42
Replace the namespace-scope `Mutex* g_x = new Mutex();` globals with
accessor functions that own a function-local static. Dynamic initialization
of a namespace-scope pointer is subject to static initialization order, so a
static initializer in another translation unit that called GetInstance()
would have found a null mutex. A function-local static is initialized on
first use, thread-safely, regardless of translation unit order, and the
pointer it holds is still never freed.

Auth and Remote Config now also keep their map behind the same kind of
accessor instead of lazily allocating and freeing a raw pointer, which
removes the null checks and manual lifetime management from the
GetInstance/Find/DeleteInternal paths. Callers only ever see references.
Introduce firebase::NoDestructor<T>, a small wrapper (modelled on
absl::NoDestructor) that constructs a T in place and never runs its
destructor. Use it for the registry mutexes of every product and the
registry maps of Auth and Remote Config in place of `static T* const t =
new T;`.

The objects are now stored inline in the function-local static rather than
on the heap, there is no `new` or raw pointer anywhere in the registry code,
and leak checkers have nothing to report since nothing is allocated. The
semantics are otherwise unchanged: constructed on first use, thread-safely,
regardless of translation unit order, and never destroyed.

Includes a unit test for NoDestructor.
@AustinBenoit

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a NoDestructor utility class to wrap function-local statics, such as global maps and mutexes, ensuring they are constructed on first use and never destroyed. This change prevents crashes at process exit when Firebase SDK instances (such as Auth, RemoteConfig, Database, Storage, Functions, Installations, or AppCheck) are owned by static objects and destroyed after the SDK's globals. The review feedback highlights several critical issues regarding redundant recursive locking or potential deadlocks in Auth, RemoteConfig, and Installations where locked functions call other functions that attempt to acquire the same mutex. Additionally, minor improvements are suggested for NoDestructor to use decayed array pointers instead of pointer-to-array types for cleaner and more portable casts.

Comment thread app/src/no_destructor.h Resolved
Comment thread app/src/no_destructor.h Resolved
Comment thread auth/src/auth.cc Resolved
Comment thread remote_config/src/remote_config.cc Resolved
Comment thread installations/src/installations.cc Resolved
Comment thread installations/src/installations.cc Resolved
- In NoDestructor, cast the decayed array pointer `storage_` rather than
  `&storage_` in placement new and `get()`.
- In Auth, RemoteConfig, and Installations, factor out `Find*Locked(App*)`
  helpers (and inline the internal cleanup in `~Installations()`) so callers
  that already hold the registry mutex do not recursively re-lock it.
@AustinBenoit

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the NoDestructor template class to wrap function-local statics, preventing process-exit crashes when Firebase SDK instances (such as Auth, RemoteConfig, Database, Storage, Functions, Installations, and AppCheck) are owned by static objects and destroyed after the SDK's globals. The feedback suggests optimizing the Auth map deletion by performing a direct key lookup instead of iterating through the map, and refactoring the Installations cleanup logic into a helper function to eliminate code duplication.

Comment thread auth/src/auth.cc Resolved
Comment thread installations/src/installations.cc Resolved
Comment thread installations/src/installations.cc Resolved
…odules

- Harden NoDestructor<T> with SFINAE forwarding-ctor guard, brace-init overloads, and std::launder access
- Migrate firebase_app, app/rest, and all product libraries (Analytics, AppCheck, Auth, Database, Firestore, Functions, Installations, Messaging, RemoteConfig, Storage, UMP) across Desktop, Android, and iOS onto function-local NoDestructor accessors
- Fix Installations out-of-order App deletion map retention, ABA safety, failed-init cleanup in Installations/RemoteConfig, and O(log N) Auth map removal
- Enable -Werror=exit-time-destructors on Clang/AppleClang across all 12 static library targets
- Add firebase_app_static_destruction_test, expanded NoDestructor unit tests, and Installations out-of-order teardown regression test
@AustinBenoit AustinBenoit added the tests-requested: full Trigger a FULL set of integration tests (uses expanded test matrix). label Oct 30, 2026
Conflicts:
- app/rest/util.cc: keep main's curl global ref-counting in
  CreateCurlPtr()/DestroyCurlPtr() and this branch's UtilCurlMutex()
  accessor.
- release_build_files/readme.md: keep both sets of release notes.

Also restore three unrelated clang-format hunks (app/src/app_desktop.cc,
app/src/util.h, database/tests/desktop/view/view_processor_test.cc) to
main's text so the file format check passes.
Require std::is_constructible<T, Args&&...> so NoDestructor<T> is not
implicitly convertible from argument lists T rejects. GCC 10 otherwise
reports NoDestructor<std::vector<int>>({10, 20, 30}) as ambiguous with the
deleted copy constructor.

Document that NoDestructor is for function-local statics only, and why that
cannot be enforced with a static_assert.
…-free

Make the map and vector test objects function-local statics so their heap
allocations stay reachable under LeakSanitizer.
Add firebase_cpp_reject_exit_time_destructors() in
cmake/exit_time_destructors.cmake. It adds -Wexit-time-destructors on
Clang, and -Werror=exit-time-destructors only when
FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS is ON, so a declaration in a
third-party header cannot break source builds of the SDK.

Stop applying the flag to firebase_firestore: firebase-ios-sdk headers it
includes declare function-local statics with destructors, which failed
every Clang build of Firestore.
Set FIREBASE_CPP_WERROR_EXIT_TIME_DESTRUCTORS in the desktop, Android and
iOS workflows; the CMake option defaults to that environment variable.

Add scripts/gha/check_exit_time_destructors.py, which fails when an SDK
static library references __cxa_atexit or atexit, and run it on the Linux
desktop jobs, where GCC has no equivalent diagnostic.
RemoveApp() no longer releases a callback reference when the App was never
added. Cover that with a test that fails without the change.
AddCallback logs, and logging locks a Mutex, so the claim that it avoids
constructing a Mutex during static initialization was wrong.
Avoids the "Future with handle 1 still exists" warning at exit. Describe the
test as the smoke test it is.
Replaces a namespace-scope "new std::mutex()" initializer, which depends on
static initialization order, with the pattern used elsewhere.
std::string allocates for short strings with the legacy libstdc++ ABI,
which the Linux build uses by default.
…null

InstallationsInternal and RemoteConfigInternal took a reference on the
shared JNI class cache before calling the Java getInstance(). When that
returned null (or threw) and FIREBASE_ASSERT() did not abort because the
application installed its own log callback, Initialized() stayed false
and the owning object's DeleteInternal() skipped Cleanup(), so the
reference was never released.

Release it in the constructor on that path. Installations also clears a
pending Java exception first, as Remote Config already did.

Not compiled or run: no Android toolchain on the machine this was
written on.
Each test binary keeps an App and a product instance in a namespace-scope
object and lets exit() destroy them after main() has returned, which is
the situation in issue #110. A regression makes the binary crash or abort
on exit.

Covered: Auth, Remote Config, Installations, App Check, Functions,
Storage, Database and Messaging (listener removal). All but App Check
also destroy a second App before its product instance; App Check is left
out of that order because an App deletes its own AppCheck.

On Linux with clang 19 every one of these aborts on origin/main and
exits 0 with this change. Auth and Remote Config fail there on a freed
std::map node; the others fail on the Mutex::Release() assertion for a
destroyed mutex, which Apple platforms do not enforce.

Functions had no unit tests, so this adds functions/tests.
…paths

Installations and Remote Config can only fail to initialize on Android,
so the desktop implementations get SetInitializationFailsForTesting() to
let unit tests reach the failed-init branch of GetInstance() and
DeleteInternal().

New tests:
- Installations and Remote Config: GetInstance() returns null when
  initialization fails and does not cache the failed instance. That the
  failed instance is deleted is only visible to a leak checker.
- Remote Config: destroying the App first clears the cached instance
  (counterpart of the Installations test).
- Auth: deleting an Auth removes only its own map entry and the App gets
  a working Auth again.
With libstdc++ before GCC 13, <iostream> defines a static
std::ios_base::Init in every translation unit that includes it, which
registers an exit-time destructor and fails
scripts/gha/check_exit_time_destructors.py. Nothing in the file uses it.
With libstdc++ older than GCC 13, including <iostream> gives the
translation unit a static std::ios_base::Init object, whose destructor
is registered to run at exit. None of these four files uses the standard
streams; util_desktop.cc and metadata_desktop.cc keep <sstream> for the
string streams they do use.
- Revert 14 files whose globals were already raw pointers (new Mutex() or
  nullptr maps) with no exit-time destructors, removing all 24 */& alignment
  changes in app/src/cleanup_notifier.{h,cc}, iterator-to-auto rewrites in
  app/src/util.cc, and unnecessary accessor renames across app, app/rest,
  database/common, and firestore/common.
- Keep already-pointer globals untouched in app_common.cc, app_check.cc,
  auth.cc, database.cc, functions.cc, installations.cc, and storage.cc so
  only statics with real exit-time destructors change.
- Restore gratuitously renamed or churned symbols in app_desktop.cc,
  device_check_provider_ios.mm, firestore/src/common/util.cc, and
  functions_android.h.
…n-order

# Conflicts:
#	app_check/src/desktop/debug_provider_desktop.cc
#	app_check/tests/CMakeLists.txt
#	release_build_files/readme.md
This reverts commit 64da4d3.

The guard is not needed. App holds its own util::Initialize() reference
for its whole lifetime, so util::CancelCallbacks() is safe to call from
the destructor of an instance that failed to initialize. Reverting keeps
this change to exit-time destructors.
@AustinBenoit

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a NoDestructor wrapper to prevent exit-time destructors from running on static and global SDK objects, resolving crashes at process exit when Firebase product instances are owned by static objects. It refactors various SDK components to use this wrapper for global/static mutexes, maps, and variables, and adds CMake checks and a Python script to enforce this constraint. Additionally, it fixes a crash in Installations when used after its App is destroyed. The review feedback highlights two critical issues: first, the unconditional use of std::launder in no_destructor.h will break compilation on C++11/C++14 environments and must be conditionally compiled; second, Auth::DeleteInternal() lacks mutex locking when modifying the shared Auths() map, introducing a potential data race.

Comment thread app/src/no_destructor.h Resolved
Comment thread auth/src/auth.cc Resolved
@AustinBenoit AustinBenoit removed the tests-requested: full Trigger a FULL set of integration tests (uses expanded test matrix). label Nov 25, 2026
@AustinBenoit
AustinBenoit marked this pull request as ready for review November 25, 2026 03:25
@AustinBenoit

AustinBenoit commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Full integration test run on 0ee1ef54 completed (run 45539928789) — 0 test failures across all 132 executed test apps (no flakes/retries):

  • Desktop (Linux/Windows OpenSSL + BoringSSL, macOS BoringSSL): 55/55 pass
  • Android real devices (3 host builds): 33/33 pass
  • Android emulators (3 host builds): 33/33 pass
  • iOS simulator: 11/11 pass
  • iOS real devices (ios_target): 0 started due to Firebase Test Lab rejecting the configured iOS 16.6 device models (same infra failure on main).

…n-order

# Conflicts:
#	app/tests/app_desktop_test.cc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use after free triggered on application exit

1 participant