From a779362144eaa812e6098dc4acc83d3fe108a75a Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 23 Nov 2026 20:48:45 +0000 Subject: [PATCH 1/3] ci(linux): probe ASan/UBSan, TSan, -Wthread-safety, and multi-App stress tests --- .github/workflows/desktop.yml | 277 ++++++++++++++++- CMakeLists.txt | 30 ++ app/src/cleanup_notifier.h | 38 +-- app/src/include/firebase/internal/mutex.h | 41 ++- app/src/reference_counted_future_impl.h | 19 +- auth/src/data.h | 11 +- cmake/thread_safety.cmake | 33 ++ .../src/main/credentials_provider_desktop.cc | 8 +- .../src/main/credentials_provider_desktop.h | 14 +- scripts/gha/run_sanitizer_suite.py | 218 +++++++++++++ testing/stress/CMakeLists.txt | 81 +++++ testing/stress/firebase.json | 29 ++ testing/stress/firestore.rules | 8 + .../stress/multi_app_emulator_stress_test.cc | 260 ++++++++++++++++ .../stress/multi_app_lifecycle_unit_test.cc | 288 ++++++++++++++++++ testing/stress/storage.rules | 8 + 16 files changed, 1314 insertions(+), 49 deletions(-) create mode 100644 cmake/thread_safety.cmake create mode 100755 scripts/gha/run_sanitizer_suite.py create mode 100644 testing/stress/CMakeLists.txt create mode 100644 testing/stress/firebase.json create mode 100644 testing/stress/firestore.rules create mode 100644 testing/stress/multi_app_emulator_stress_test.cc create mode 100644 testing/stress/multi_app_lifecycle_unit_test.cc create mode 100644 testing/stress/storage.rules diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 05b5e4ef14..fd2af4e402 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -256,7 +256,7 @@ jobs: LANG: en_US run: | cd build - ctest --repeat until-pass:3 --output-on-failure -E firestore_util_test + ctest --repeat until-pass:3 --output-on-failure -LE multi_app_stress -E firestore_util_test - name: Run unit tests (linux) # Linux exists as its own standalone execution step in order to invoke @@ -269,7 +269,7 @@ jobs: run: | ulimit -c unlimited cd build - sudo ctest --repeat until-pass:3 --output-on-failure + sudo ctest --repeat until-pass:3 --output-on-failure -LE multi_app_stress - name: Prep bins for achive (linux) # Copies all of the binary files into one directory for ease in @@ -414,3 +414,276 @@ jobs: fi env: JOB_STATUS: ${{ job.status }} + + linux_clang_thread_safety: + name: linux-clang-thread-safety + runs-on: ubuntu-22.04 + timeout-minutes: 90 + steps: + - uses: lukka/get-cmake@591817e96fcad43505fb4eae36172462abb3a42e # ratchet:lukka/get-cmake@latest + with: + cmakeVersion: "~3.31.0" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # ratchet:actions/checkout@v7 + with: + persist-credentials: true # zizmor: ignore[artipacked] + submodules: false + - name: Cache ccache files + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # ratchet:actions/cache@v6 + with: + path: ccache_dir + key: linux-clang-tsa-ccache-${{ hashFiles('CMakeLists.txt', 'cmake/external/*.cmake') }} + restore-keys: | + linux-clang-tsa-ccache- + - name: Setup python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # ratchet:actions/setup-python@v7 + with: + python-version: "3.10" + - name: Install Clang and build prerequisites + run: | + sudo apt-get update + sudo apt-get install -y clang llvm ccache ninja-build libssl-dev libsecret-1-dev libglib2.0-dev zlib1g-dev protobuf-compiler pkg-config python3-venv + python3 -m pip install -r external/pip_requirements.txt + clang++ --version + - name: Configure with Clang -Wthread-safety + run: | + CC=clang CXX=clang++ cmake -G Ninja -S . -B build \ + -DCMAKE_BUILD_TYPE=Debug \ + -DFIREBASE_CPP_BUILD_TESTS=ON \ + -DFIREBASE_FORCE_FAKE_SECURE_STORAGE=ON \ + -DFIREBASE_USE_BORINGSSL=OFF \ + -DFIREBASE_LINUX_USE_CXX11_ABI=ON \ + -DFIREBASE_CPP_ENABLE_THREAD_SAFETY_ANALYSIS=ON \ + -DFIREBASE_GITHUB_ACTION_BUILD=ON \ + -DCMAKE_C_FLAGS="-Wno-unknown-warning-option" \ + -DCMAKE_CXX_FLAGS="-Wno-unknown-warning-option" + - name: Build SDK libraries and collect -Wthread-safety diagnostics + run: | + set -o pipefail + cmake --build build -j "$(nproc)" --target \ + firebase_app firebase_rest_lib firebase_analytics firebase_app_check \ + firebase_auth firebase_database firebase_firestore firebase_functions \ + firebase_installations firebase_messaging firebase_remote_config \ + firebase_storage firebase_ump \ + firebase_multi_app_lifecycle_unit_test \ + firebase_multi_app_emulator_stress_test \ + 2>&1 | tee tsa_build.log + echo "=== UNIQUE -Wthread-safety DIAGNOSTICS ===" + grep -E "\[-Wthread-safety" tsa_build.log | sed "s|${GITHUB_WORKSPACE}/||g" | sort -u | tee tsa_unique_warnings.txt || true + COUNT=$(wc -l < tsa_unique_warnings.txt) + echo "Total unique -Wthread-safety warnings: ${COUNT}" + if [[ "${COUNT}" -gt 0 ]]; then + echo "::warning::Found ${COUNT} unique -Wthread-safety diagnostics (see tsa_unique_warnings.txt)" + fi + - name: Upload thread-safety logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # ratchet:actions/upload-artifact@v7 + with: + name: linux-clang-thread-safety-logs + path: | + tsa_build.log + tsa_unique_warnings.txt + + linux_asan_ubsan: + name: linux-asan-ubsan + runs-on: ubuntu-22.04 + timeout-minutes: 90 + steps: + - uses: lukka/get-cmake@591817e96fcad43505fb4eae36172462abb3a42e # ratchet:lukka/get-cmake@latest + with: + cmakeVersion: "~3.31.0" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # ratchet:actions/checkout@v7 + with: + persist-credentials: true # zizmor: ignore[artipacked] + submodules: false + - name: Cache ccache files + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # ratchet:actions/cache@v6 + with: + path: ccache_dir + key: linux-asan-ubsan-ccache-${{ hashFiles('CMakeLists.txt', 'cmake/external/*.cmake') }} + restore-keys: | + linux-asan-ubsan-ccache- + - name: Setup python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # ratchet:actions/setup-python@v7 + with: + python-version: "3.10" + - name: Install Clang, sanitizers, and build prerequisites + run: | + sudo apt-get update + sudo apt-get install -y clang llvm gdb ccache ninja-build libssl-dev libsecret-1-dev libglib2.0-dev zlib1g-dev protobuf-compiler pkg-config python3-venv + python3 -m pip install -r external/pip_requirements.txt + - name: Configure with ASan + UBSan + run: | + SAN_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g -Wno-unknown-warning-option" + CC=clang CXX=clang++ cmake -G Ninja -S . -B build \ + -DCMAKE_BUILD_TYPE=Debug \ + -DFIREBASE_CPP_BUILD_TESTS=ON \ + -DFIREBASE_FORCE_FAKE_SECURE_STORAGE=ON \ + -DFIREBASE_USE_BORINGSSL=OFF \ + -DFIREBASE_LINUX_USE_CXX11_ABI=ON \ + -DFIREBASE_GITHUB_ACTION_BUILD=ON \ + -DCMAKE_C_FLAGS="${SAN_FLAGS}" \ + -DCMAKE_CXX_FLAGS="${SAN_FLAGS}" \ + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \ + -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" + - name: Build unit and stress tests (ASan + UBSan) + run: cmake --build build -j "$(nproc)" + - name: Run unit suite and offline multi-App stress tests (ASan + UBSan) + id: asan_unit + continue-on-error: true + env: + ASAN_OPTIONS: "detect_leaks=0:symbolize=1:print_stacktrace=1" + UBSAN_OPTIONS: "print_stacktrace=1:halt_on_error=0" + run: | + export ASAN_SYMBOLIZER_PATH="$(which llvm-symbolizer)" + set -o pipefail + python3 scripts/gha/run_sanitizer_suite.py \ + --build_dir build --mode asan --run_unit_ctest --run_unit_stress \ + --case_timeout 90 2>&1 | tee asan_unit_and_stress.log + - name: Set up Node (18) + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # ratchet:actions/setup-node@v7 + with: + node-version: 18.x + - name: Install firebase-tools + uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 # ratchet:nick-fields/retry@v4 + with: + shell: bash + timeout_minutes: 5 + max_attempts: 3 + command: npm install -g firebase-tools + - name: Setup java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # ratchet:actions/setup-java@v6 + with: + distribution: 'temurin' + java-version: '17' + - name: Run emulator multi-App stress tests (ASan + UBSan) + id: asan_emulator + continue-on-error: true + env: + ASAN_OPTIONS: "detect_leaks=0:symbolize=1:print_stacktrace=1" + UBSAN_OPTIONS: "print_stacktrace=1:halt_on_error=0" + run: | + export ASAN_SYMBOLIZER_PATH="$(which llvm-symbolizer)" + set -o pipefail + firebase emulators:exec \ + --config testing/stress/firebase.json \ + --only auth,firestore,database,storage \ + --project demo-example \ + 'python3 scripts/gha/run_sanitizer_suite.py --build_dir build --mode asan --run_emulator_stress --case_timeout 90' \ + 2>&1 | tee asan_emulator_stress.log + - name: Upload ASan/UBSan logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # ratchet:actions/upload-artifact@v7 + with: + name: linux-asan-ubsan-logs + path: | + asan_unit_and_stress.log + asan_emulator_stress.log + - name: Final ASan/UBSan status + run: | + echo "unit+offline_stress: ${{ steps.asan_unit.outcome }}" + echo "emulator_stress: ${{ steps.asan_emulator.outcome }}" + if [[ "${{ steps.asan_unit.outcome }}" != "success" || "${{ steps.asan_emulator.outcome }}" != "success" ]]; then + exit 1 + fi + + linux_tsan: + name: linux-tsan + runs-on: ubuntu-22.04 + timeout-minutes: 90 + steps: + - uses: lukka/get-cmake@591817e96fcad43505fb4eae36172462abb3a42e # ratchet:lukka/get-cmake@latest + with: + cmakeVersion: "~3.31.0" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # ratchet:actions/checkout@v7 + with: + persist-credentials: true # zizmor: ignore[artipacked] + submodules: false + - name: Cache ccache files + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # ratchet:actions/cache@v6 + with: + path: ccache_dir + key: linux-tsan-ccache-${{ hashFiles('CMakeLists.txt', 'cmake/external/*.cmake') }} + restore-keys: | + linux-tsan-ccache- + - name: Setup python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # ratchet:actions/setup-python@v7 + with: + python-version: "3.10" + - name: Install Clang, TSan, and build prerequisites + run: | + sudo apt-get update + sudo apt-get install -y clang llvm gdb ccache ninja-build libssl-dev libsecret-1-dev libglib2.0-dev zlib1g-dev protobuf-compiler pkg-config python3-venv + python3 -m pip install -r external/pip_requirements.txt + sudo sysctl -w vm.mmap_rnd_bits=28 || true + - name: Configure with TSan + run: | + TSAN_FLAGS="-fsanitize=thread -fno-omit-frame-pointer -g -Wno-unknown-warning-option" + CC=clang CXX=clang++ cmake -G Ninja -S . -B build \ + -DCMAKE_BUILD_TYPE=Debug \ + -DFIREBASE_CPP_BUILD_TESTS=ON \ + -DFIREBASE_FORCE_FAKE_SECURE_STORAGE=ON \ + -DFIREBASE_USE_BORINGSSL=OFF \ + -DFIREBASE_LINUX_USE_CXX11_ABI=ON \ + -DFIREBASE_GITHUB_ACTION_BUILD=ON \ + -DCMAKE_C_FLAGS="${TSAN_FLAGS}" \ + -DCMAKE_CXX_FLAGS="${TSAN_FLAGS}" \ + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread" \ + -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=thread" + - name: Build unit and stress tests (TSan) + run: cmake --build build -j "$(nproc)" + - name: Run unit suite and offline multi-App stress tests (TSan) + id: tsan_unit + continue-on-error: true + env: + TSAN_OPTIONS: "halt_on_error=0:second_deadlock_stack=1:history_size=7:symbolize=1" + run: | + export TSAN_SYMBOLIZER_PATH="$(which llvm-symbolizer)" + set -o pipefail + python3 scripts/gha/run_sanitizer_suite.py \ + --build_dir build --mode tsan --run_unit_ctest --run_unit_stress \ + --case_timeout 120 2>&1 | tee tsan_unit_and_stress.log + - name: Set up Node (18) + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # ratchet:actions/setup-node@v7 + with: + node-version: 18.x + - name: Install firebase-tools + uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 # ratchet:nick-fields/retry@v4 + with: + shell: bash + timeout_minutes: 5 + max_attempts: 3 + command: npm install -g firebase-tools + - name: Setup java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # ratchet:actions/setup-java@v6 + with: + distribution: 'temurin' + java-version: '17' + - name: Run emulator multi-App stress tests (TSan) + id: tsan_emulator + continue-on-error: true + env: + TSAN_OPTIONS: "halt_on_error=0:second_deadlock_stack=1:history_size=7:symbolize=1" + run: | + export TSAN_SYMBOLIZER_PATH="$(which llvm-symbolizer)" + set -o pipefail + firebase emulators:exec \ + --config testing/stress/firebase.json \ + --only auth,firestore,database,storage \ + --project demo-example \ + 'python3 scripts/gha/run_sanitizer_suite.py --build_dir build --mode tsan --run_emulator_stress --case_timeout 120' \ + 2>&1 | tee tsan_emulator_stress.log + - name: Upload TSan logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # ratchet:actions/upload-artifact@v7 + with: + name: linux-tsan-logs + path: | + tsan_unit_and_stress.log + tsan_emulator_stress.log + - name: Final TSan status + run: | + echo "unit+offline_stress: ${{ steps.tsan_unit.outcome }}" + echo "emulator_stress: ${{ steps.tsan_emulator.outcome }}" + if [[ "${{ steps.tsan_unit.outcome }}" != "success" || "${{ steps.tsan_emulator.outcome }}" != "success" ]]; then + exit 1 + fi diff --git a/CMakeLists.txt b/CMakeLists.txt index 36dae1d520..ec4de32569 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -79,6 +79,14 @@ option(FIREBASE_USE_LINUX_CXX11_ABI option(FIREBASE_GITHUB_ACTION_BUILD "Indicates that this build was created from a GitHub Action" OFF) +set(firebase_thread_safety_analysis_default OFF) +if("$ENV{FIREBASE_CPP_ENABLE_THREAD_SAFETY_ANALYSIS}") + set(firebase_thread_safety_analysis_default ON) +endif() +option(FIREBASE_CPP_ENABLE_THREAD_SAFETY_ANALYSIS + "Enable Clang -Wthread-safety on Firebase SDK libraries." + ${firebase_thread_safety_analysis_default}) + option(FIREBASE_QUICK_TEST "Enable quick tests will skip tests which requires access to the SECRET" OFF) @@ -116,6 +124,7 @@ endif() list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_LIST_DIR}/cmake) include(external_rules) include(cpp_pack) +include(thread_safety) if(FIREBASE_CPP_BUILD_TESTS OR FIREBASE_CPP_BUILD_STUB_TESTS) enable_testing() @@ -688,6 +697,27 @@ if (FIREBASE_INCLUDE_STORAGE) add_subdirectory(storage) endif() +foreach(firebase_sdk_target + firebase_app + firebase_rest_lib + firebase_analytics + firebase_app_check + firebase_auth + firebase_database + firebase_firestore + firebase_functions + firebase_installations + firebase_messaging + firebase_remote_config + firebase_storage + firebase_ump) + firebase_cpp_enable_thread_safety_analysis(${firebase_sdk_target}) +endforeach() + +if(DESKTOP AND FIREBASE_CPP_BUILD_TESTS) + add_subdirectory(testing/stress) +endif() + # Place the CMake and gradle build files provided to easily link against the # prebuilt libraries at the root of the package. cpp_pack_dir( diff --git a/app/src/cleanup_notifier.h b/app/src/cleanup_notifier.h index 45846c47b1..256c3a6fa2 100644 --- a/app/src/cleanup_notifier.h +++ b/app/src/cleanup_notifier.h @@ -41,7 +41,7 @@ namespace firebase { // owner (which is about to be deleted). class CleanupNotifier { public: - typedef void (*CleanupCallback)(void *object); + typedef void (*CleanupCallback)(void* object); // Default constructor. CleanupNotifier(); @@ -52,11 +52,11 @@ class CleanupNotifier { // Register a callback to be called on a given object when it's time for // cleanup. If this object already has a callback registered, the previous // callback will be overwritten. - void RegisterObject(void *object, CleanupCallback callback); + void RegisterObject(void* object, CleanupCallback callback); // Unregister an object. This will remove it from the cleanup list without // calling the cleanup callback. - void UnregisterObject(void *object); + void UnregisterObject(void* object); // Call all cleanup callbacks, clearing the list. You can call this manually // rather than using the destructor if you want more control over when it @@ -64,43 +64,45 @@ class CleanupNotifier { void CleanupAll(); // Register an owner with the notifier. - void RegisterOwner(void *owner) { RegisterOwner(this, owner); } + void RegisterOwner(void* owner) { RegisterOwner(this, owner); } // Unregister an owner from the notifier. - void UnregisterOwner(void *owner) { UnregisterOwner(this, owner); } + void UnregisterOwner(void* owner) { UnregisterOwner(this, owner); } // Find a cleanup notifier by owner object. // If a cleanup notifier was registered with an owner object using // RegisterOwner(). - static CleanupNotifier *FindByOwner(void *owner); + static CleanupNotifier* FindByOwner(void* owner); private: // Register the notifier's association with the owner object. // Notifiers can be register to multiple owner objects. - static void RegisterOwner(CleanupNotifier *notifier, void *owner); + static void RegisterOwner(CleanupNotifier* notifier, void* owner); // Unregister a notifier from an owner object. - static void UnregisterOwner(CleanupNotifier *notifier, void *owner); + static void UnregisterOwner(CleanupNotifier* notifier, void* owner); // Unregister this notifier with all owner objects. void UnregisterAllOwners(); // Unregister a notifier from an owner object. - static void UnregisterOwner(std::map::iterator it); + static void UnregisterOwner(std::map::iterator it); private: // Guards callbacks_ and cleaned_up_. Mutex mutex_; - std::map callbacks_; - bool cleaned_up_; + std::map callbacks_ FIREBASE_GUARDED_BY(mutex_); + bool cleaned_up_ FIREBASE_GUARDED_BY(mutex_); // List of owners of this notifier. // This is the inverse of cleanup_notifiers_by_owner_ for a notifier. - std::vector owners_; + std::vector owners_ + FIREBASE_GUARDED_BY(*cleanup_notifiers_by_owner_mutex_); // Guards owners_ and cleanup_notifiers_by_owner_. - static Mutex *cleanup_notifiers_by_owner_mutex_; + static Mutex* cleanup_notifiers_by_owner_mutex_; // Global map of cleanup notifiers bucketed by owner object. - static std::map *cleanup_notifiers_by_owner_; + static std::map* cleanup_notifiers_by_owner_ + FIREBASE_GUARDED_BY(*cleanup_notifiers_by_owner_mutex_); }; // Typed wrapper for CleanupNotifier. Helpful if you only need to clean @@ -108,19 +110,19 @@ class CleanupNotifier { template class TypedCleanupNotifier { public: - typedef void (*CleanupCallback)(T *object); + typedef void (*CleanupCallback)(T* object); - void RegisterObject(T *object, CleanupCallback callback) { + void RegisterObject(T* object, CleanupCallback callback) { notifier_.RegisterObject( object, reinterpret_cast(callback)); } - void UnregisterObject(T *object) { notifier_.UnregisterObject(object); } + void UnregisterObject(T* object) { notifier_.UnregisterObject(object); } void CleanupAll() { notifier_.CleanupAll(); } // Get the underlying notifier. - CleanupNotifier &cleanup_notifier() { return notifier_; } + CleanupNotifier& cleanup_notifier() { return notifier_; } private: CleanupNotifier notifier_; diff --git a/app/src/include/firebase/internal/mutex.h b/app/src/include/firebase/internal/mutex.h index 86f6a45d1b..d60f9a2e4b 100644 --- a/app/src/include/firebase/internal/mutex.h +++ b/app/src/include/firebase/internal/mutex.h @@ -29,8 +29,35 @@ namespace firebase { #if !defined(DOXYGEN) +// Clang Thread Safety Analysis annotations. No-ops on non-Clang compilers and +// SWIG. See https://clang.llvm.org/docs/ThreadSafetyAnalysis.html. +#if defined(__clang__) && !defined(SWIG) +#define FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#else +#define FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(x) +#endif + +#define FIREBASE_CAPABILITY(x) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) +#define FIREBASE_SCOPED_CAPABILITY \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) +#define FIREBASE_GUARDED_BY(x) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) +#define FIREBASE_PT_GUARDED_BY(x) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) +#define FIREBASE_ACQUIRE(...) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) +#define FIREBASE_RELEASE(...) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) +#define FIREBASE_REQUIRES(...) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) +#define FIREBASE_EXCLUDES(...) \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) +#define FIREBASE_NO_THREAD_SAFETY_ANALYSIS \ + FIREBASE_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) + /// @brief A simple synchronization lock. Only one thread at a time can Acquire. -class Mutex { +class FIREBASE_CAPABILITY("mutex") Mutex { public: // Bitfield that describes the mutex configuration. enum Mode { @@ -45,10 +72,10 @@ class Mutex { ~Mutex(); // Acquires the lock for this mutex, blocking until it is available. - void Acquire(); + void Acquire() FIREBASE_ACQUIRE(); // Releases the lock for this mutex acquired by a previous `Acquire()` call. - void Release(); + void Release() FIREBASE_RELEASE(); // Returns the implementation-defined native mutex handle. // Used by firebase::Thread implementation. @@ -80,10 +107,12 @@ class Mutex { /// // ... logic ... /// } /// \endcode -class MutexLock { +class FIREBASE_SCOPED_CAPABILITY MutexLock { public: - explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } - ~MutexLock() { mutex_->Release(); } + explicit MutexLock(Mutex& mutex) FIREBASE_ACQUIRE(mutex) : mutex_(&mutex) { + mutex_->Acquire(); + } + ~MutexLock() FIREBASE_RELEASE() { mutex_->Release(); } private: // Copy is disallowed. diff --git a/app/src/reference_counted_future_impl.h b/app/src/reference_counted_future_impl.h index 0ca87712d7..42aae2ca86 100644 --- a/app/src/reference_counted_future_impl.h +++ b/app/src/reference_counted_future_impl.h @@ -432,7 +432,7 @@ class ReferenceCountedFutureImpl : public detail::FutureApiInterface { /// Allocate a new handle. It's unlikely that we'll ever allocate four /// billion of these to loop back to the start, but just in case, skip over /// the one marked as kInvalidFutureHandle. - FutureHandleId AllocHandleId() { + FutureHandleId AllocHandleId() FIREBASE_REQUIRES(mutex_) { const FutureHandleId id = next_future_handle_++; if (next_future_handle_ == kInvalidFutureHandle) next_future_handle_++; return id; @@ -548,10 +548,12 @@ class ReferenceCountedFutureImpl : public detail::FutureApiInterface { /// Releases the mutex, calling the Future's completion callbacks, if any. /// (The mutex is released before calling the callbacks.) - void ReleaseMutexAndRunCallbacks(const FutureHandle& handle); + void ReleaseMutexAndRunCallbacks(const FutureHandle& handle) + FIREBASE_RELEASE(mutex_); void RunCallback(FutureBase* future_base, - FutureBase::CompletionCallback callback, void* user_data); + FutureBase::CompletionCallback callback, void* user_data) + FIREBASE_REQUIRES(mutex_); bool is_orphaned() const; @@ -564,14 +566,15 @@ class ReferenceCountedFutureImpl : public detail::FutureApiInterface { /// Future to access the backing data. The backing data is deleted once no /// more Futures reference it. // TODO(jsanmiya): Use unordered_map when available (i.e. when not stlport). - std::map backings_; + std::map backings_ + FIREBASE_GUARDED_BY(mutex_); /// A unique int that is incremented by one after every call to @ref Alloc. - FutureHandleId next_future_handle_; + FutureHandleId next_future_handle_ FIREBASE_GUARDED_BY(mutex_); /// Optionally keep a future around for the most recent call to a function. /// The functions are specified in `fn_idx` of @ref Alloc. - std::vector last_results_; + std::vector last_results_ FIREBASE_GUARDED_BY(mutex_); /// Clean up any stale Future instances. TypedCleanupNotifier cleanup_; @@ -583,9 +586,9 @@ class ReferenceCountedFutureImpl : public detail::FutureApiInterface { /// This flag prevents this instance from being considered safe to delete /// before the callback is finished, which would be unsafe because it would /// clean up the future that is passed to the callback. - bool is_running_callback_ = false; + bool is_running_callback_ FIREBASE_GUARDED_BY(mutex_) = false; - bool is_orphaned_ = false; + bool is_orphaned_ FIREBASE_GUARDED_BY(mutex_) = false; }; /// Specialize the case where the data is void since we don't need to diff --git a/auth/src/data.h b/auth/src/data.h index 58098bb421..536aa2f70d 100644 --- a/auth/src/data.h +++ b/auth/src/data.h @@ -148,11 +148,13 @@ struct AuthData { /// User-supplied listener classes. All of these are updated when Auth's /// sign in state changes. - std::vector listeners; + std::vector listeners + FIREBASE_GUARDED_BY(listeners_mutex); /// User-supplied ID token listeners. All of these are updated when Auth's /// ID token changes. - std::vector id_token_listeners; + std::vector id_token_listeners + FIREBASE_GUARDED_BY(listeners_mutex); /// Unique phone provider for this Auth. Initialized the first time /// PhoneAuthProvider::GetInstance() is called. @@ -168,10 +170,11 @@ struct AuthData { Mutex token_listener_mutex; // Tracks if the Id Token listener is expecting a callback to occur. - bool expect_id_token_listener_callback; + bool expect_id_token_listener_callback + FIREBASE_GUARDED_BY(expect_id_token_mutex); // Tracks if the persistent cache load is pending. - bool persistent_cache_load_pending; + bool persistent_cache_load_pending FIREBASE_GUARDED_BY(listeners_mutex); // Mutex protecting `expect_id_token_listener_callback` Mutex expect_id_token_mutex; diff --git a/cmake/thread_safety.cmake b/cmake/thread_safety.cmake new file mode 100644 index 0000000000..88d457b3b8 --- /dev/null +++ b/cmake/thread_safety.cmake @@ -0,0 +1,33 @@ +# 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. + +# Opt-in Clang Thread Safety Analysis (-Wthread-safety) for SDK targets. +# No-op on GCC, MSVC, or when FIREBASE_CPP_ENABLE_THREAD_SAFETY_ANALYSIS is OFF. + +function(firebase_cpp_enable_thread_safety_analysis target) + if(NOT FIREBASE_CPP_ENABLE_THREAD_SAFETY_ANALYSIS) + return() + endif() + if(NOT TARGET ${target}) + return() + endif() + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + target_compile_options(${target} PRIVATE + $<$:-Wthread-safety> + $<$:-Wno-error=thread-safety> + $<$:-Wthread-safety> + $<$:-Wno-error=thread-safety> + ) + endif() +endfunction() diff --git a/firestore/src/main/credentials_provider_desktop.cc b/firestore/src/main/credentials_provider_desktop.cc index 8182c34497..983382d6bc 100644 --- a/firestore/src/main/credentials_provider_desktop.cc +++ b/firestore/src/main/credentials_provider_desktop.cc @@ -154,7 +154,7 @@ FirebaseCppCredentialsProvider::~FirebaseCppCredentialsProvider() { void FirebaseCppCredentialsProvider::SetCredentialChangeListener( CredentialChangeListener listener) { { - std::lock_guard lock(contents_->mutex); + MutexLock lock(contents_->mutex); if (!listener) { SIMPLE_HARD_ASSERT(change_listener_, @@ -179,7 +179,7 @@ void FirebaseCppCredentialsProvider::SetCredentialChangeListener( void FirebaseCppCredentialsProvider::GetToken( TokenListener listener) { - std::lock_guard lock(contents_->mutex); + MutexLock lock(contents_->mutex); if (IsSignedIn()) { RequestToken(std::move(listener)); @@ -207,7 +207,7 @@ void FirebaseCppCredentialsProvider::OnAuthStateChanged(void* context) { auto provider = static_cast(context); Contents* contents = provider->contents_.get(); - std::lock_guard lock(contents->mutex); + MutexLock lock(contents->mutex); // The currently signed-in user may have changed, increase the token // generation to reflect that. @@ -251,7 +251,7 @@ void FirebaseCppCredentialsProvider::RequestToken( return; } - std::lock_guard lock(contents->mutex); + MutexLock lock(contents->mutex); OnToken(future_token, contents->app, contents->token_generation, std::move(listener), expected_generation); }); diff --git a/firestore/src/main/credentials_provider_desktop.h b/firestore/src/main/credentials_provider_desktop.h index aed23b3c81..d6bb1aab36 100644 --- a/firestore/src/main/credentials_provider_desktop.h +++ b/firestore/src/main/credentials_provider_desktop.h @@ -18,7 +18,6 @@ #define FIREBASE_FIRESTORE_SRC_MAIN_CREDENTIALS_PROVIDER_DESKTOP_H_ #include -#include // NOLINT(build/c++11) #include #include "Firestore/core/src/credentials/auth_token.h" @@ -28,6 +27,7 @@ #include "Firestore/core/src/util/statusor.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/future.h" +#include "app/src/include/firebase/internal/mutex.h" #if defined(__ANDROID__) #error "This header should not be used on Android." @@ -61,8 +61,8 @@ class FirebaseCppCredentialsProvider listener) override; private: - void AddAuthStateListener(); - void RemoveAuthStateListener(); + void AddAuthStateListener() FIREBASE_EXCLUDES(contents_->mutex); + void RemoveAuthStateListener() FIREBASE_EXCLUDES(contents_->mutex); // Callback for the function registry-based pseudo-AuthStateListener // interface. @@ -74,9 +74,9 @@ class FirebaseCppCredentialsProvider // `AuthToken::Unauthenticated()`. void RequestToken( firestore::credentials::TokenListener - listener); + listener) FIREBASE_REQUIRES(contents_->mutex); - bool IsSignedIn() const; + bool IsSignedIn() const FIREBASE_REQUIRES(contents_->mutex); // Wraps the data that is used by `auth::User::GetToken` callback. This // credentials provider holds a shared pointer to `Contents`, while the @@ -97,7 +97,7 @@ class FirebaseCppCredentialsProvider // // TODO(b/148688333): make sure not to hold the mutex while calling methods // on `app`. - std::recursive_mutex mutex; + Mutex mutex; App& app; @@ -105,7 +105,7 @@ class FirebaseCppCredentialsProvider // Credentials commonly change when a different user signs in; comparing // generations at the point where a token is requested and the point where // the token is retrieved allows identifying obsolete requests. - int token_generation = 0; + int token_generation FIREBASE_GUARDED_BY(mutex) = 0; }; std::shared_ptr contents_; }; diff --git a/scripts/gha/run_sanitizer_suite.py b/scripts/gha/run_sanitizer_suite.py new file mode 100755 index 0000000000..ed2a49fff9 --- /dev/null +++ b/scripts/gha/run_sanitizer_suite.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +# 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. +"""Runs unit and multi-App stress tests under ASan/UBSan or TSan. + +Runs each stress test case in an isolated subprocess with a deadlock watchdog +that captures a GDB thread backtrace before terminating hung processes, so a +single crash or deadlock does not prevent subsequent tests from reporting. +""" + +import argparse +import os +import platform +import shutil +import signal +import subprocess +import sys +import time + + +def maybe_wrap_setarch(cmd, disable_aslr): + if disable_aslr and shutil.which("setarch"): + return ["setarch", platform.machine(), "-R"] + cmd + return cmd + + +def list_gtest_cases(binary, disable_aslr): + cmd = maybe_wrap_setarch([binary, "--gtest_list_tests"], disable_aslr) + proc = subprocess.run( + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + check=False, timeout=30 + ) + cases = [] + suite = None + for raw_line in proc.stdout.splitlines(): + line = raw_line.split("#", 1)[0].rstrip() + if not line: + continue + if not line[0].isspace() and line.endswith("."): + suite = line + elif suite and line[0].isspace(): + cases.append(suite + line.strip()) + return cases + + +def capture_gdb_backtrace(pid): + if not shutil.which("gdb"): + return "(gdb not installed)" + try: + res = subprocess.run( + ["gdb", "-batch", "-ex", "thread apply all bt", "-p", str(pid)], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=20, + check=False, + ) + return res.stdout + except Exception as exc: # pylint: disable=broad-except + return f"(gdb failed: {exc})" + + +def run_single_case(binary, test_filter, timeout_sec, disable_aslr, env): + cmd = maybe_wrap_setarch( + [ + binary, + f"--gtest_filter={test_filter}", + "--gtest_catch_exceptions=0", + ], + disable_aslr, + ) + print(f"\n>>> RUNNING {os.path.basename(binary)} :: {test_filter}", + flush=True) + start = time.monotonic() + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + errors="replace", + env=env, + start_new_session=True, + ) + try: + output, _ = proc.communicate(timeout=timeout_sec) + elapsed = time.monotonic() - start + status = "PASS" if proc.returncode == 0 else f"FAIL (rc={proc.returncode})" + print(output, flush=True) + return (test_filter, status, elapsed) + except subprocess.TimeoutExpired: + elapsed = time.monotonic() - start + print(f"\n!!! TIMEOUT after {elapsed:.1f}s — capturing GDB backtrace " + f"for pid {proc.pid} !!!", flush=True) + bt = capture_gdb_backtrace(proc.pid) + print(bt, flush=True) + try: + os.killpg(proc.pid, signal.SIGABRT) + output, _ = proc.communicate(timeout=10) + except Exception: # pylint: disable=broad-except + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + pass + output, _ = proc.communicate() + print(output, flush=True) + return (test_filter, f"TIMEOUT/DEADLOCK ({elapsed:.0f}s)", elapsed) + + +def run_gtest_binary_isolated(binary, timeout_sec, disable_aslr, env): + if not os.path.exists(binary): + print(f"ERROR: test binary not found: {binary}", flush=True) + return [(binary, "MISSING", 0.0)] + cases = list_gtest_cases(binary, disable_aslr) + if not cases: + print(f"ERROR: no gtest cases discovered in {binary}", flush=True) + return [(binary, "NO_TESTS", 0.0)] + results = [] + for case in cases: + results.append( + run_single_case(binary, case, timeout_sec, disable_aslr, env) + ) + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--build_dir", default="build") + parser.add_argument("--mode", choices=["asan", "tsan"], required=True) + parser.add_argument("--run_unit_ctest", action="store_true") + parser.add_argument("--run_unit_stress", action="store_true") + parser.add_argument("--run_emulator_stress", action="store_true") + parser.add_argument("--case_timeout", type=int, default=120) + args = parser.parse_args() + + disable_aslr = args.mode == "tsan" + env = os.environ.copy() + env.setdefault("LANG", "en_US.UTF-8") + + any_failed = False + summary_rows = [] + + if args.run_unit_ctest: + print("\n================ PHASE 1: EXISTING UNIT SUITE ================", + flush=True) + cmd = maybe_wrap_setarch( + [ + "ctest", + "--test-dir", + args.build_dir, + "-LE", + "multi_app_stress", + "--output-on-failure", + "--timeout", + str(args.case_timeout), + "-j", + str(max(1, min(4, os.cpu_count() or 2))), + ], + disable_aslr, + ) + proc = subprocess.run(cmd, env=env, check=False) + status = "PASS" if proc.returncode == 0 else f"FAIL (rc={proc.returncode})" + summary_rows.append(("existing_unit_ctest", status, 0.0)) + if proc.returncode != 0: + any_failed = True + + if args.run_unit_stress: + print("\n================ PHASE 2: OFFLINE MULTI-APP STRESS ================", + flush=True) + binary = os.path.join( + args.build_dir, + "testing", + "stress", + "firebase_multi_app_lifecycle_unit_test", + ) + rows = run_gtest_binary_isolated( + binary, args.case_timeout, disable_aslr, env + ) + summary_rows.extend(rows) + if any(r[1] != "PASS" for r in rows): + any_failed = True + + if args.run_emulator_stress: + print("\n================ PHASE 3: EMULATOR MULTI-APP STRESS ================", + flush=True) + binary = os.path.join( + args.build_dir, + "testing", + "stress", + "firebase_multi_app_emulator_stress_test", + ) + rows = run_gtest_binary_isolated( + binary, args.case_timeout, disable_aslr, env + ) + summary_rows.extend(rows) + if any(r[1] != "PASS" for r in rows): + any_failed = True + + print("\n================ SANITIZER SUMMARY ================", flush=True) + for name, status, elapsed in summary_rows: + suffix = f" ({elapsed:.1f}s)" if elapsed > 0 else "" + print(f" {status:24s} {name}{suffix}", flush=True) + + sys.exit(1 if any_failed else 0) + + +if __name__ == "__main__": + main() diff --git a/testing/stress/CMakeLists.txt b/testing/stress/CMakeLists.txt new file mode 100644 index 0000000000..263e2e2eaa --- /dev/null +++ b/testing/stress/CMakeLists.txt @@ -0,0 +1,81 @@ +# 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. + +if(NOT DESKTOP OR NOT FIREBASE_CPP_BUILD_TESTS) + return() +endif() + +if(FIREBASE_INCLUDE_AUTH AND FIREBASE_INCLUDE_APP_CHECK AND + FIREBASE_INCLUDE_STORAGE AND FIREBASE_INCLUDE_DATABASE AND + FIREBASE_INCLUDE_FUNCTIONS AND FIREBASE_INCLUDE_INSTALLATIONS AND + FIREBASE_INCLUDE_REMOTE_CONFIG) + set(stress_unit_DEPS + firebase_app + firebase_app_check + firebase_auth + firebase_database + firebase_functions + firebase_installations + firebase_remote_config + firebase_storage + firebase_testing + ) + set(stress_unit_DEFS "") + if(FIREBASE_INCLUDE_FIRESTORE) + list(APPEND stress_unit_DEPS firebase_firestore) + list(APPEND stress_unit_DEFS -DFIREBASE_STRESS_WITH_FIRESTORE=1) + endif() + + firebase_cpp_cc_test( + firebase_multi_app_lifecycle_unit_test + SOURCES + multi_app_lifecycle_unit_test.cc + DEPENDS + ${stress_unit_DEPS} + DEFINES + ${stress_unit_DEFS} + ) + set_tests_properties(firebase_multi_app_lifecycle_unit_test PROPERTIES + LABELS "multi_app_stress" + ) +endif() + +if(FIREBASE_INCLUDE_AUTH AND FIREBASE_INCLUDE_APP_CHECK AND + FIREBASE_INCLUDE_DATABASE AND FIREBASE_INCLUDE_FIRESTORE AND + FIREBASE_INCLUDE_STORAGE) + add_executable(firebase_multi_app_emulator_stress_test + multi_app_emulator_stress_test.cc + ) + target_include_directories(firebase_multi_app_emulator_stress_test + PRIVATE + ${FIREBASE_SOURCE_DIR} + ) + target_link_libraries(firebase_multi_app_emulator_stress_test + PRIVATE + firebase_app + firebase_app_check + firebase_auth + firebase_database + firebase_firestore + firebase_storage + firebase_testing + gmock + gtest + gtest_main + ) + target_compile_definitions(firebase_multi_app_emulator_stress_test + PRIVATE + -DINTERNAL_EXPERIMENTAL=1 + ) +endif() diff --git a/testing/stress/firebase.json b/testing/stress/firebase.json new file mode 100644 index 0000000000..cf449b45a4 --- /dev/null +++ b/testing/stress/firebase.json @@ -0,0 +1,29 @@ +{ + "firestore": { + "rules": "firestore.rules" + }, + "storage": { + "rules": "storage.rules" + }, + "emulators": { + "auth": { + "host": "127.0.0.1", + "port": 9099 + }, + "firestore": { + "host": "127.0.0.1", + "port": 8080 + }, + "database": { + "host": "127.0.0.1", + "port": 9000 + }, + "storage": { + "host": "127.0.0.1", + "port": 9199 + }, + "ui": { + "enabled": false + } + } +} diff --git a/testing/stress/firestore.rules b/testing/stress/firestore.rules new file mode 100644 index 0000000000..c3c1733dcd --- /dev/null +++ b/testing/stress/firestore.rules @@ -0,0 +1,8 @@ +rules_version = '2'; +service cloud.firestore { + match /databases/{database}/documents { + match /{document=**} { + allow read, write: if true; + } + } +} diff --git a/testing/stress/multi_app_emulator_stress_test.cc b/testing/stress/multi_app_emulator_stress_test.cc new file mode 100644 index 0000000000..d3996e0601 --- /dev/null +++ b/testing/stress/multi_app_emulator_stress_test.cc @@ -0,0 +1,260 @@ +/* + * 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. + */ + +// Emulator-backed desktop multi-App lifecycle stress tests reproducing +// jwinarske's November 2026 desktop reports (#1969, #1970, #1971, #1972, +// #1973, #1974) under ASan/UBSan and TSan. +// +// Intended to be invoked under: +// firebase emulators:exec --only auth,firestore,database,storage \ +// --project demo-example + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/src/include/firebase/app.h" +#include "app/src/include/firebase/future.h" +#include "app_check/src/include/firebase/app_check.h" +#include "auth/src/include/firebase/auth.h" +#include "database/src/include/firebase/database.h" +#include "firestore/src/include/firebase/firestore.h" +#include "gtest/gtest.h" +#include "storage/src/include/firebase/storage.h" + +namespace firebase { +namespace { + +std::pair ParseHostPort(const char* env_var, + const std::string& default_host, + int default_port) { + const char* raw = std::getenv(env_var); + if (!raw || raw[0] == '\0') { + return {default_host, default_port}; + } + std::string value(raw); + auto colon = value.rfind(':'); + if (colon == std::string::npos) { + return {value, default_port}; + } + return {value.substr(0, colon), std::atoi(value.substr(colon + 1).c_str())}; +} + +int GetStressRounds(int default_rounds) { + const char* raw = std::getenv("FIREBASE_STRESS_ROUNDS"); + if (!raw || raw[0] == '\0') return default_rounds; + int parsed = std::atoi(raw); + return parsed > 0 ? parsed : default_rounds; +} + +AppOptions MakeEmulatorAppOptions() { + auto [db_host, db_port] = + ParseHostPort("FIREBASE_DATABASE_EMULATOR_HOST", "127.0.0.1", 9000); + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("fake-api-key-for-emulator"); + options.set_project_id("demo-example"); + options.set_storage_bucket("demo-example.appspot.com"); + options.set_database_url("http://" + db_host + ":" + std::to_string(db_port) + + "/?ns=demo-example"); + return options; +} + +void ConfigureAuthEmulator(auth::Auth* auth) { + auto [host, port] = + ParseHostPort("FIREBASE_AUTH_EMULATOR_HOST", "127.0.0.1", 9099); + auth->UseEmulator(host, static_cast(port)); +} + +void ConfigureFirestoreEmulator(firestore::Firestore* fs) { + auto [host, port] = + ParseHostPort("FIRESTORE_EMULATOR_HOST", "127.0.0.1", 8080); + auto settings = fs->settings(); + settings.set_host(host + ":" + std::to_string(port)); + settings.set_ssl_enabled(false); + fs->set_settings(settings); +} + +void ConfigureStorageEmulator(storage::Storage* store) { + auto [host, port] = + ParseHostPort("FIREBASE_STORAGE_EMULATOR_HOST", "127.0.0.1", 9199); + store->UseEmulator(host, port); +} + +// Reproduces #1972 (Auth::SignOut <-> Firestore GetToken deadlock), +// #1973 (deleting Firestore with pending write frees CleanupNotifier before +// Promise), and #1974 (Firestore aborts in RequestToken on concurrent SignOut). +TEST(MultiAppEmulatorStressTest, AuthSignOutRacesFirestoreGetSetAndTeardown) { + const int rounds = GetStressRounds(50); + for (int i = 0; i < rounds; ++i) { + std::string app_name = "fs_race_" + std::to_string(i); + std::unique_ptr app( + App::Create(MakeEmulatorAppOptions(), app_name.c_str())); + ASSERT_NE(app, nullptr); + + std::unique_ptr auth(auth::Auth::GetAuth(app.get())); + ASSERT_NE(auth, nullptr); + ConfigureAuthEmulator(auth.get()); + + std::unique_ptr fs( + firestore::Firestore::GetInstance(app.get())); + ASSERT_NE(fs, nullptr); + ConfigureFirestoreEmulator(fs.get()); + + auto sign_in = auth->SignInAnonymously(); + ASSERT_TRUE(sign_in.Wait(15000)) + << "SignInAnonymously timed out on round " << i; + ASSERT_EQ(sign_in.error(), auth::kAuthErrorNone) + << "SignInAnonymously failed on round " << i << ": " + << sign_in.error_message(); + + auto doc = fs->Document("stress/doc_" + std::to_string(i)); + auto get_future = doc.Get(); + auto set_future = + doc.Set({{"round", firestore::FieldValue::Integer(i)}, + {"tag", firestore::FieldValue::String("stress")}}); + + // Do not wait for get_future / set_future; immediately sign out and tear + // down Firestore, Auth, and App. + auth->SignOut(); + fs.reset(); + auth.reset(); + app.reset(); + } +} + +// Reproduces #1969 with live Auth + emulator: keep default App + Auth alive, +// sign in/out on a second App, and immediately destroy the second Auth + App. +TEST(MultiAppEmulatorStressTest, TwoAppAuthSignOutAndDeleteRace) { + std::unique_ptr app_a(App::Create(MakeEmulatorAppOptions())); + ASSERT_NE(app_a, nullptr); + std::unique_ptr auth_a(auth::Auth::GetAuth(app_a.get())); + ASSERT_NE(auth_a, nullptr); + ConfigureAuthEmulator(auth_a.get()); + + const int rounds = GetStressRounds(25); + for (int i = 0; i < rounds; ++i) { + std::string app_name = "auth_second_" + std::to_string(i); + std::unique_ptr app_b( + App::Create(MakeEmulatorAppOptions(), app_name.c_str())); + ASSERT_NE(app_b, nullptr); + std::unique_ptr auth_b(auth::Auth::GetAuth(app_b.get())); + ASSERT_NE(auth_b, nullptr); + ConfigureAuthEmulator(auth_b.get()); + + auto sign_in = auth_b->SignInAnonymously(); + ASSERT_TRUE(sign_in.Wait(15000)) + << "SignInAnonymously timed out on round " << i; + ASSERT_EQ(sign_in.error(), auth::kAuthErrorNone) + << "SignInAnonymously failed on round " << i << ": " + << sign_in.error_message(); + + auth_b->SignOut(); + auth_b.reset(); + app_b.reset(); + } +} + +// Exercises 2 concurrent Apps with Auth + Storage + Firestore pointed at the +// emulators, verifying clean teardown and surfacing cross-module data races. +TEST(MultiAppEmulatorStressTest, TwoAppMultiProductEmulatorTeardown) { + std::unique_ptr app_a(App::Create(MakeEmulatorAppOptions())); + ASSERT_NE(app_a, nullptr); + std::unique_ptr auth_a(auth::Auth::GetAuth(app_a.get())); + ASSERT_NE(auth_a, nullptr); + ConfigureAuthEmulator(auth_a.get()); + std::unique_ptr store_a( + storage::Storage::GetInstance(app_a.get())); + ASSERT_NE(store_a, nullptr); + ConfigureStorageEmulator(store_a.get()); + + const int rounds = GetStressRounds(10); + for (int i = 0; i < rounds; ++i) { + std::string app_name = "multi_emu_" + std::to_string(i); + std::unique_ptr app_b( + App::Create(MakeEmulatorAppOptions(), app_name.c_str())); + ASSERT_NE(app_b, nullptr); + + std::unique_ptr auth_b(auth::Auth::GetAuth(app_b.get())); + ConfigureAuthEmulator(auth_b.get()); + std::unique_ptr store_b( + storage::Storage::GetInstance(app_b.get())); + ConfigureStorageEmulator(store_b.get()); + std::unique_ptr fs_b( + firestore::Firestore::GetInstance(app_b.get())); + ConfigureFirestoreEmulator(fs_b.get()); + + auto sign_in = auth_b->SignInAnonymously(); + ASSERT_TRUE(sign_in.Wait(15000)); + ASSERT_EQ(sign_in.error(), auth::kAuthErrorNone); + + const char payload[] = "hello-stress"; + auto upload = store_b->GetReference("stress/blob_" + std::to_string(i)) + .PutBytes(payload, sizeof(payload) - 1); + auto write = fs_b->Document("multi/doc_" + std::to_string(i)) + .Set({{"i", firestore::FieldValue::Integer(i)}}); + EXPECT_TRUE(upload.Wait(15000)); + EXPECT_TRUE(write.Wait(15000)); + + auth_b->SignOut(); + fs_b.reset(); + store_b.reset(); + auth_b.reset(); + app_b.reset(); + } +} + +// Reproduces #1971 (Database desktop zero-delay reconnect spin loop) briefly +// and checks teardown safety under ASan/TSan. +TEST(MultiAppEmulatorStressTest, DatabaseUnreachableReconnectSpinAndTeardown) { + std::unique_ptr app( + App::Create(MakeEmulatorAppOptions(), "rtdb_unreachable")); + ASSERT_NE(app, nullptr); + + // Port with nothing listening; reproduces #1971 reconnect tight loop. + std::unique_ptr db(database::Database::GetInstance( + app.get(), "http://127.0.0.1:19999/?ns=demo-example")); + ASSERT_NE(db, nullptr); + +#if defined(__linux__) + struct timespec cpu_start{}; + struct timespec cpu_end{}; + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &cpu_start); +#endif + + auto set_future = db->GetReference("probe/x").SetValue(1); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + +#if defined(__linux__) + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &cpu_end); + double cpu_ms = (cpu_end.tv_sec - cpu_start.tv_sec) * 1000.0 + + (cpu_end.tv_nsec - cpu_start.tv_nsec) / 1e6; + std::cout << "[PROBE #1971] 1000ms wall-clock unreachable RTDB consumed " + << cpu_ms << " ms process CPU time" << std::endl; +#endif + + // Tear down while reconnect loop is active. + db.reset(); + app.reset(); +} + +} // namespace +} // namespace firebase diff --git a/testing/stress/multi_app_lifecycle_unit_test.cc b/testing/stress/multi_app_lifecycle_unit_test.cc new file mode 100644 index 0000000000..09acad0a25 --- /dev/null +++ b/testing/stress/multi_app_lifecycle_unit_test.cc @@ -0,0 +1,288 @@ +/* + * 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. + */ + +// Offline desktop multi-App lifecycle stress tests targeting sanitizer and +// concurrency regressions across App, Auth/UserSecureManager, AppCheck, +// Storage, Database, and Firestore. + +#include +#include +#include +#include +#include +#include +#include + +#include "app/src/function_registry.h" +#include "app/src/include/firebase/app.h" +#include "app/src/include/firebase/future.h" +#include "app/src/secure/user_secure_internal.h" +#include "app/src/secure/user_secure_manager.h" +#include "app_check/src/include/firebase/app_check.h" +#include "auth/src/include/firebase/auth.h" +#include "database/src/include/firebase/database.h" +#include "functions/src/include/firebase/functions.h" +#include "gtest/gtest.h" +#include "installations/src/include/firebase/installations.h" +#include "remote_config/src/include/firebase/remote_config.h" +#include "storage/src/include/firebase/storage.h" +#include "storage/src/include/firebase/storage/listener.h" + +#if defined(FIREBASE_STRESS_WITH_FIRESTORE) +#include "firestore/src/include/firebase/firestore.h" +#endif + +namespace firebase { +namespace { + +AppOptions MakeTestAppOptions() { + AppOptions options; + options.set_app_id("1:1234567890:android:0123456789abcdef"); + options.set_api_key("not_a_real_api_key"); + options.set_project_id("multi-app-stress-test"); + options.set_storage_bucket("multi-app-stress-test.appspot.com"); + options.set_database_url("http://127.0.0.1:19999/?ns=multi-app-stress-test"); + return options; +} + +class NoOpStorageListener : public storage::Listener { + public: + void OnPaused(storage::Controller*) override {} + void OnProgress(storage::Controller*) override {} +}; + +class FakeAppCheckProvider : public app_check::AppCheckProvider { + public: + explicit FakeAppCheckProvider(std::atomic* calls) : calls_(calls) {} + ~FakeAppCheckProvider() override = default; + + void GetToken( + std::function + completion_callback) override { + calls_->fetch_add(1); + app_check::AppCheckToken token; + token.token = "fake-app-check-token"; + token.expire_time_millis = 4102444800000LL; // 2100-01-01 + completion_callback(token, app_check::kAppCheckErrorNone, ""); + } + + private: + std::atomic* calls_; +}; + +class FakeAppCheckProviderFactory : public app_check::AppCheckProviderFactory { + public: + ~FakeAppCheckProviderFactory() override = default; + + app_check::AppCheckProvider* CreateProvider(App* /*app*/) override { + auto provider = std::make_unique(&calls_); + auto* raw = provider.get(); + providers_.push_back(std::move(provider)); + return raw; + } + + int call_count() const { return calls_.load(); } + + private: + std::atomic calls_{0}; + std::vector> providers_; +}; + +// Slow fake secure storage that mimics macOS Keychain latency so +// UserSecureManager::~UserSecureManager() overlaps with an active scheduler +// task even on fast Linux runners (reproduces #1969). +class DelayedFakeUserSecure : public app::secure::UserSecureInternal { + public: + explicit DelayedFakeUserSecure(std::atomic* task_started) + : task_started_(task_started) {} + + std::string LoadUserData(const std::string& /*app_name*/) override { + return ""; + } + + void SaveUserData(const std::string& /*app_name*/, + const std::string& /*user_data*/) override { + if (task_started_) task_started_->store(true); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + + void DeleteUserData(const std::string& /*app_name*/) override { + if (task_started_) task_started_->store(true); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + + void DeleteAllData() override {} + + private: + std::atomic* task_started_; +}; + +// Reproduces #1966: Storage ListenerInternal never initializes rest_operation_. +// Scrambling heap reuse before allocation makes uninitialized reads reliably +// crash or trigger ASan/UBSan on Linux too. +TEST(MultiAppLifecycleUnitTest, StorageListenerUnattachedDestroy) { + std::unique_ptr app(App::Create(MakeTestAppOptions())); + ASSERT_NE(app, nullptr); + std::unique_ptr store( + storage::Storage::GetInstance(app.get())); + ASSERT_NE(store, nullptr); + + // Poison heap memory of matching sizes to expose uninitialized pointers on + // Linux where fresh allocator pages are often zeroed. + { + std::vector> poison; + for (int i = 0; i < 64; ++i) { + auto buf = std::make_unique(128); + std::memset(buf.get(), 0xA5, 128); + poison.push_back(std::move(buf)); + } + } + + auto listener = std::make_unique(); + auto future = + store->GetReference("probe/missing") + .PutFile("/no/such/firebase_cpp_sdk_stress_file", listener.get()); + ASSERT_TRUE(future.Wait(5000)); + EXPECT_NE(future.error(), storage::kErrorNone); + + // Destroying a Listener whose operation failed before creating RestOperation + // dereferences uninitialized ListenerInternal::rest_operation_ (#1966). + listener.reset(); +} + +// Reproduces #1970 (App Check only registers on first App) and secondary bug +// BUG-2085 (FunctionRegistry::UnregisterFunction calls erase(itr, itr)). +TEST(MultiAppLifecycleUnitTest, AppCheckSecondAppRegistersTokenFunction) { + FakeAppCheckProviderFactory factory; + app_check::AppCheck::SetAppCheckProviderFactory(&factory); + + std::unique_ptr app_a(App::Create(MakeTestAppOptions())); + std::unique_ptr app_b(App::Create(MakeTestAppOptions(), "second")); + ASSERT_NE(app_a, nullptr); + ASSERT_NE(app_b, nullptr); + + std::unique_ptr ac_a( + app_check::AppCheck::GetInstance(app_a.get())); + std::unique_ptr ac_b( + app_check::AppCheck::GetInstance(app_b.get())); + ASSERT_NE(ac_a, nullptr); + ASSERT_NE(ac_b, nullptr); + + EXPECT_TRUE(app_a->function_registry()->FunctionExists( + internal::FnAppCheckGetTokenAsync)); + // Fails on main due to process-global g_app_check_registry_count (#1970). + EXPECT_TRUE(app_b->function_registry()->FunctionExists( + internal::FnAppCheckGetTokenAsync)); + + Future token_a; + EXPECT_TRUE(app_a->function_registry()->CallFunction( + internal::FnAppCheckGetTokenAsync, app_a.get(), nullptr, &token_a)); + if (token_a.status() != kFutureStatusInvalid) { + EXPECT_TRUE(token_a.Wait(5000)); + } + + Future token_b; + EXPECT_TRUE(app_b->function_registry()->CallFunction( + internal::FnAppCheckGetTokenAsync, app_b.get(), nullptr, &token_b)); + if (token_b.status() != kFutureStatusInvalid) { + EXPECT_TRUE(token_b.Wait(5000)); + } + + ac_b.reset(); + ac_a.reset(); + + // Fails on main because FunctionRegistry::UnregisterFunction calls + // erase(itr, itr) (BUG-2085). + EXPECT_FALSE(app_a->function_registry()->FunctionExists( + internal::FnAppCheckGetTokenAsync)); + EXPECT_FALSE(app_b->function_registry()->FunctionExists( + internal::FnAppCheckGetTokenAsync)); + + app_check::AppCheck::SetAppCheckProviderFactory(nullptr); +} + +// Reproduces #1969: UserSecureManager::~UserSecureManager() races the shared +// static s_scheduler_ destroying the callback's SafeFutureHandle when a second +// UserSecureManager keeps s_scheduler_ alive. +TEST(MultiAppLifecycleUnitTest, TwoAppUserSecureManagerConcurrentTeardown) { + // Keep one manager alive so DestroyScheduler() does not join s_scheduler_. + app::secure::UserSecureManager keeper( + std::make_unique(nullptr)); + + for (int i = 0; i < 40; ++i) { + std::atomic started{false}; + auto transient = std::make_unique( + std::make_unique(&started)); + transient->DeleteUserData("second_" + std::to_string(i)); + + // Wait until the worker thread enters DeleteUserData() so ClearReference() + // blocks in the destructor and exits right before WorkerThreadRoutine + // destroys the CallbackVariadic holding UserSecureDataHandle. + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(200); + while (!started.load() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + transient.reset(); + } +} + +// Repeatedly creates and tears down a second named App with multiple products +// while a default App remains alive. +TEST(MultiAppLifecycleUnitTest, TwoAppMultiProductCreateDestroyLoop) { + std::unique_ptr default_app(App::Create(MakeTestAppOptions())); + ASSERT_NE(default_app, nullptr); + std::unique_ptr default_auth( + auth::Auth::GetAuth(default_app.get())); + std::unique_ptr default_ac( + app_check::AppCheck::GetInstance(default_app.get())); + + for (int i = 0; i < 10; ++i) { + std::string name = "ephemeral_" + std::to_string(i); + std::unique_ptr app(App::Create(MakeTestAppOptions(), name.c_str())); + ASSERT_NE(app, nullptr); + + std::unique_ptr auth(auth::Auth::GetAuth(app.get())); + std::unique_ptr ac( + app_check::AppCheck::GetInstance(app.get())); + std::unique_ptr store( + storage::Storage::GetInstance(app.get())); + std::unique_ptr fn( + functions::Functions::GetInstance(app.get())); + std::unique_ptr fis( + installations::Installations::GetInstance(app.get())); + std::unique_ptr rc( + remote_config::RemoteConfig::GetInstance(app.get())); +#if defined(FIREBASE_STRESS_WITH_FIRESTORE) + std::unique_ptr fs( + firestore::Firestore::GetInstance(app.get())); +#endif + // Destroy in documented reverse order before app. +#if defined(FIREBASE_STRESS_WITH_FIRESTORE) + fs.reset(); +#endif + rc.reset(); + fis.reset(); + fn.reset(); + store.reset(); + ac.reset(); + auth.reset(); + app.reset(); + } +} + +} // namespace +} // namespace firebase diff --git a/testing/stress/storage.rules b/testing/stress/storage.rules new file mode 100644 index 0000000000..a7db6961ca --- /dev/null +++ b/testing/stress/storage.rules @@ -0,0 +1,8 @@ +rules_version = '2'; +service firebase.storage { + match /b/{bucket}/o { + match /{allPaths=**} { + allow read, write: if true; + } + } +} From 1beaa332570feffb26f360865d5ae5215205d3f5 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 23 Nov 2026 21:19:06 +0000 Subject: [PATCH 2/3] fix(ci): fix set_database_url arg, non-fatal -Wthread-safety, zizmor, and Node 22/Java 21 --- .github/workflows/desktop.yml | 30 +++++++++++-------- CMakeLists.txt | 11 +++++++ .../stress/multi_app_emulator_stress_test.cc | 9 +++--- 3 files changed, 34 insertions(+), 16 deletions(-) diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index fd2af4e402..e3a012d67c 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -539,10 +539,10 @@ jobs: python3 scripts/gha/run_sanitizer_suite.py \ --build_dir build --mode asan --run_unit_ctest --run_unit_stress \ --case_timeout 90 2>&1 | tee asan_unit_and_stress.log - - name: Set up Node (18) + - name: Set up Node (22) uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # ratchet:actions/setup-node@v7 with: - node-version: 18.x + node-version: 22.x - name: Install firebase-tools uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 # ratchet:nick-fields/retry@v4 with: @@ -554,7 +554,7 @@ jobs: uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # ratchet:actions/setup-java@v6 with: distribution: 'temurin' - java-version: '17' + java-version: '21' - name: Run emulator multi-App stress tests (ASan + UBSan) id: asan_emulator continue-on-error: true @@ -579,10 +579,13 @@ jobs: asan_unit_and_stress.log asan_emulator_stress.log - name: Final ASan/UBSan status + env: + UNIT_OUTCOME: ${{ steps.asan_unit.outcome }} + EMULATOR_OUTCOME: ${{ steps.asan_emulator.outcome }} run: | - echo "unit+offline_stress: ${{ steps.asan_unit.outcome }}" - echo "emulator_stress: ${{ steps.asan_emulator.outcome }}" - if [[ "${{ steps.asan_unit.outcome }}" != "success" || "${{ steps.asan_emulator.outcome }}" != "success" ]]; then + echo "unit+offline_stress: ${UNIT_OUTCOME}" + echo "emulator_stress: ${EMULATOR_OUTCOME}" + if [[ "${UNIT_OUTCOME}" != "success" || "${EMULATOR_OUTCOME}" != "success" ]]; then exit 1 fi @@ -642,10 +645,10 @@ jobs: python3 scripts/gha/run_sanitizer_suite.py \ --build_dir build --mode tsan --run_unit_ctest --run_unit_stress \ --case_timeout 120 2>&1 | tee tsan_unit_and_stress.log - - name: Set up Node (18) + - name: Set up Node (22) uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # ratchet:actions/setup-node@v7 with: - node-version: 18.x + node-version: 22.x - name: Install firebase-tools uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 # ratchet:nick-fields/retry@v4 with: @@ -657,7 +660,7 @@ jobs: uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # ratchet:actions/setup-java@v6 with: distribution: 'temurin' - java-version: '17' + java-version: '21' - name: Run emulator multi-App stress tests (TSan) id: tsan_emulator continue-on-error: true @@ -681,9 +684,12 @@ jobs: tsan_unit_and_stress.log tsan_emulator_stress.log - name: Final TSan status + env: + UNIT_OUTCOME: ${{ steps.tsan_unit.outcome }} + EMULATOR_OUTCOME: ${{ steps.tsan_emulator.outcome }} run: | - echo "unit+offline_stress: ${{ steps.tsan_unit.outcome }}" - echo "emulator_stress: ${{ steps.tsan_emulator.outcome }}" - if [[ "${{ steps.tsan_unit.outcome }}" != "success" || "${{ steps.tsan_emulator.outcome }}" != "success" ]]; then + echo "unit+offline_stress: ${UNIT_OUTCOME}" + echo "emulator_stress: ${EMULATOR_OUTCOME}" + if [[ "${UNIT_OUTCOME}" != "success" || "${EMULATOR_OUTCOME}" != "success" ]]; then exit 1 fi diff --git a/CMakeLists.txt b/CMakeLists.txt index ec4de32569..e150f58ccf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -714,6 +714,17 @@ foreach(firebase_sdk_target firebase_cpp_enable_thread_safety_analysis(${firebase_sdk_target}) endforeach() +# Firestore Core exports -Werror -Wthread-safety via its PUBLIC interface on +# Clang, which would turn pre-existing SDK header warnings (e.g. +# ReferenceCountedFutureImpl::GetLastResultCount) into hard build errors in +# probe/macOS builds. Keep them as warnings for this diagnostic probe. +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND TARGET firebase_app) + target_compile_options(firebase_app PUBLIC + $<$:-Wno-error=thread-safety> + $<$:-Wno-error=thread-safety> + ) +endif() + if(DESKTOP AND FIREBASE_CPP_BUILD_TESTS) add_subdirectory(testing/stress) endif() diff --git a/testing/stress/multi_app_emulator_stress_test.cc b/testing/stress/multi_app_emulator_stress_test.cc index d3996e0601..9324e3e6d0 100644 --- a/testing/stress/multi_app_emulator_stress_test.cc +++ b/testing/stress/multi_app_emulator_stress_test.cc @@ -73,8 +73,9 @@ AppOptions MakeEmulatorAppOptions() { options.set_api_key("fake-api-key-for-emulator"); options.set_project_id("demo-example"); options.set_storage_bucket("demo-example.appspot.com"); - options.set_database_url("http://" + db_host + ":" + std::to_string(db_port) + - "/?ns=demo-example"); + std::string db_url = "http://" + db_host + ":" + std::to_string(db_port) + + "/?ns=demo-example"; + options.set_database_url(db_url.c_str()); return options; } @@ -235,8 +236,8 @@ TEST(MultiAppEmulatorStressTest, DatabaseUnreachableReconnectSpinAndTeardown) { ASSERT_NE(db, nullptr); #if defined(__linux__) - struct timespec cpu_start{}; - struct timespec cpu_end{}; + struct timespec cpu_start {}; + struct timespec cpu_end {}; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &cpu_start); #endif From c43ce9543e5fe00b9e96429537660a4b8147aaae Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 23 Nov 2026 22:02:13 +0000 Subject: [PATCH 3/3] fix(ci): disable UBSan vptr check for -fno-rtti leveldb, set LANG=en_US, suppress uninstrumented libglib in TSan --- .github/workflows/desktop.yml | 20 ++++++++++++++----- .../stress/multi_app_emulator_stress_test.cc | 4 ++-- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index e3a012d67c..b262337c48 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -513,7 +513,8 @@ jobs: python3 -m pip install -r external/pip_requirements.txt - name: Configure with ASan + UBSan run: | - SAN_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g -Wno-unknown-warning-option" + SAN_C_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g -Wno-unknown-warning-option" + SAN_CXX_FLAGS="${SAN_C_FLAGS} -fno-sanitize=vptr" CC=clang CXX=clang++ cmake -G Ninja -S . -B build \ -DCMAKE_BUILD_TYPE=Debug \ -DFIREBASE_CPP_BUILD_TESTS=ON \ @@ -521,8 +522,8 @@ jobs: -DFIREBASE_USE_BORINGSSL=OFF \ -DFIREBASE_LINUX_USE_CXX11_ABI=ON \ -DFIREBASE_GITHUB_ACTION_BUILD=ON \ - -DCMAKE_C_FLAGS="${SAN_FLAGS}" \ - -DCMAKE_CXX_FLAGS="${SAN_FLAGS}" \ + -DCMAKE_C_FLAGS="${SAN_C_FLAGS}" \ + -DCMAKE_CXX_FLAGS="${SAN_CXX_FLAGS}" \ -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \ -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" - name: Build unit and stress tests (ASan + UBSan) @@ -531,6 +532,7 @@ jobs: id: asan_unit continue-on-error: true env: + LANG: en_US ASAN_OPTIONS: "detect_leaks=0:symbolize=1:print_stacktrace=1" UBSAN_OPTIONS: "print_stacktrace=1:halt_on_error=0" run: | @@ -638,8 +640,16 @@ jobs: id: tsan_unit continue-on-error: true env: - TSAN_OPTIONS: "halt_on_error=0:second_deadlock_stack=1:history_size=7:symbolize=1" + LANG: en_US run: | + cat > /tmp/tsan.supp <<'EOF' + # Uninstrumented system GLib/GIO/libsecret libraries used by UserSecureLinuxInternal. + called_from_lib:libglib-2.0.so + called_from_lib:libgio-2.0.so + called_from_lib:libgobject-2.0.so + called_from_lib:libsecret-1.so + EOF + export TSAN_OPTIONS="halt_on_error=0:second_deadlock_stack=1:history_size=7:symbolize=1:suppressions=/tmp/tsan.supp" export TSAN_SYMBOLIZER_PATH="$(which llvm-symbolizer)" set -o pipefail python3 scripts/gha/run_sanitizer_suite.py \ @@ -665,7 +675,7 @@ jobs: id: tsan_emulator continue-on-error: true env: - TSAN_OPTIONS: "halt_on_error=0:second_deadlock_stack=1:history_size=7:symbolize=1" + TSAN_OPTIONS: "halt_on_error=0:second_deadlock_stack=1:history_size=7:symbolize=1:suppressions=/tmp/tsan.supp" run: | export TSAN_SYMBOLIZER_PATH="$(which llvm-symbolizer)" set -o pipefail diff --git a/testing/stress/multi_app_emulator_stress_test.cc b/testing/stress/multi_app_emulator_stress_test.cc index 9324e3e6d0..bfa53f0e84 100644 --- a/testing/stress/multi_app_emulator_stress_test.cc +++ b/testing/stress/multi_app_emulator_stress_test.cc @@ -73,8 +73,8 @@ AppOptions MakeEmulatorAppOptions() { options.set_api_key("fake-api-key-for-emulator"); options.set_project_id("demo-example"); options.set_storage_bucket("demo-example.appspot.com"); - std::string db_url = "http://" + db_host + ":" + std::to_string(db_port) + - "/?ns=demo-example"; + std::string db_url = + "http://" + db_host + ":" + std::to_string(db_port) + "/?ns=demo-example"; options.set_database_url(db_url.c_str()); return options; }