Make RandenPool fork-safe, avoid once_flag exception deadlock, and scrub seeds. Previously, `GetEntropyFromRandenPool` initialized `shared_pools` once via `absl::call_once`. That design had three issues: 1. `fork()` stream duplication and spinlock deadlock: If any caller seeded an `absl::BitGen`, `absl::InsecureBitGen`, or `absl::MakeSeedSeq()` before `fork()`, child processes inherited `pool_once` in the done state along with up to 240 bytes per entry of buffered Randen state, causing forked children to produce identical random sequences. Furthermore, if another thread in the parent held `RandenPoolEntry::mu_` across `fork()`, the child process could deadlock forever on a spinlock owned by a dead parent thread. 2. `absl::call_once` exception deadlock: `absl::call_once` does not catch C++ exceptions, so throwing `absl::SeedGenException` inside `InitPoolURBG` when OS entropy failed left `pool_once` permanently stuck in `kOnceRunning`, deadlocking all concurrent and subsequent callers. 3. Residual stack seed material: `InitPoolURBG` left the raw unpermuted OS seed material on the stack after copying it into `RandenPoolEntry`. Replace `pool_once` and `shared_pools` with an atomic pointer to a generation-tagged `PoolArray` and an async-signal-safe `pthread_atfork` child handler that increments an atomic generation counter: - Fast-path calls perform only a relaxed generation load and an acquire pointer load with no extra synchronization. - Slow-path initialization is serialized via a `(generation, pid)`-tagged `InitGate` so concurrent cold-start or post-fork callers perform a single OS entropy read, a single `pthread_atfork()` registration, and a single `PoolArray` allocation without ever touching a parent's inherited spinlock. - `pthread_atfork()` errors fail initialization (leaving `atfork_registered` unset and throwing `SeedGenException`) rather than silently disabling fork detection. - After `fork()`, children observe a generation mismatch and lazily allocate and OS-seed a fresh `PoolArray` without touching inherited parent spinlocks; prior `PoolArray` and `InitGate` generations remain linked via `prev` so leak checkers continue to see them as reachable. - `SeedScrubber` zeroes stack `seed_material` via `volatile` stores on scope exit, and `InitGate::mu` is unlocked before invoking `ThrowSeedGenException()` so OS entropy failures never wedge concurrent or subsequent callers. PiperOrigin-RevId: 1022234714
diff --git a/absl/random/CMakeLists.txt b/absl/random/CMakeLists.txt index b2c3fa2..089b528 100644 --- a/absl/random/CMakeLists.txt +++ b/absl/random/CMakeLists.txt
@@ -1101,8 +1101,10 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS - absl::flat_hash_map + absl::config + absl::flat_hash_set absl::random_internal_entropy_pool + absl::random_seed_gen_exception absl::synchronization GTest::gtest_main )
diff --git a/absl/random/internal/BUILD.bazel b/absl/random/internal/BUILD.bazel index 04f9a27..766bc91 100644 --- a/absl/random/internal/BUILD.bazel +++ b/absl/random/internal/BUILD.bazel
@@ -672,7 +672,9 @@ linkopts = ABSL_DEFAULT_LINKOPTS, deps = [ ":entropy_pool", + "//absl/base:config", "//absl/container:flat_hash_set", + "//absl/random:seed_gen_exception", "//absl/synchronization", "@googletest//:gtest", "@googletest//:gtest_main",
diff --git a/absl/random/internal/entropy_pool.cc b/absl/random/internal/entropy_pool.cc index 21f8305..6488ae6 100644 --- a/absl/random/internal/entropy_pool.cc +++ b/absl/random/internal/entropy_pool.cc
@@ -16,13 +16,14 @@ #include <algorithm> #include <atomic> +#include <cstddef> #include <cstdint> #include <cstring> #include <iterator> +#include <memory> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" -#include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/base/internal/spinlock.h" #include "absl/base/optimization.h" @@ -33,6 +34,23 @@ #include "absl/random/seed_gen_exception.h" #include "absl/types/span.h" +#if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || \ + defined(_AIX)) && \ + !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__wasi__) && \ + !defined(__Fuchsia__) && !defined(__VXWORKS__) && !defined(__hexagon__) && \ + !defined(__XTENSA__) && !defined(__native_client__) && !defined(__rtems__) +#define ABSL_RANDOM_HAVE_PTHREAD_ATFORK 1 +#endif + +#if defined(ABSL_RANDOM_HAVE_PTHREAD_ATFORK) || !defined(ABSL_HAVE_THREAD_LOCAL) +#include <pthread.h> +#endif + +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK +#include <sys/types.h> +#include <unistd.h> +#endif + using absl::base_internal::SpinLock; using absl::base_internal::SpinLockHolder; @@ -100,9 +118,124 @@ // Number of pooled urbg entries. static constexpr size_t kPoolSize = 8; -// Shared pool entries. -static absl::once_flag pool_once; -ABSL_CACHELINE_ALIGNED static RandenPoolEntry* shared_pools[kPoolSize]; +// A generation-tagged array of pool entries. Old generations remain linked via +// `prev` so they stay reachable to leak checkers without ever destroying or +// locking spinlocks inherited across fork(). +struct PoolArray { + PoolArray* prev = nullptr; + uint32_t generation = 0; + RandenPoolEntry entries[kPoolSize]; +}; + +// Active pool entries for the current process generation. +ABSL_CONST_INIT static std::atomic<PoolArray*> shared_pools_ptr{nullptr}; + +// Monotonically incremented generation counter; bumped in forked children via +// OnForkChild() (and by ResetRandenPoolForTesting()). +ABSL_CONST_INIT static std::atomic<uint32_t> pool_generation{0}; + +// Per-generation serialization gate for slow-path pool initialization. +// On fork-capable platforms, gates are additionally tagged with the owning +// process ID so a child forked before pthread_atfork() completes never +// acquires a parent's SpinLock. Prior gates remain linked via `prev` so leak +// checkers continue to see them as reachable without touching inherited locks. +struct InitGate { + InitGate* prev = nullptr; + uint32_t generation = 0; +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK + pid_t pid = 0; +#endif + SpinLock mu; +}; + +ABSL_CONST_INIT static std::atomic<InitGate*> init_gate_ptr{nullptr}; + +// Test-only fault injection and observation counters (touched only on the +// slow initialization path). +ABSL_CONST_INIT static std::atomic<size_t> seed_failure_count_for_testing{0}; +ABSL_CONST_INIT static std::atomic<size_t> os_entropy_read_count_for_testing{0}; + +bool ReadSeedMaterialForPool(absl::Span<uint32_t> values) { + os_entropy_read_count_for_testing.fetch_add(1, std::memory_order_acq_rel); + size_t failures = + seed_failure_count_for_testing.load(std::memory_order_acquire); + while (failures > 0) { + if (seed_failure_count_for_testing.compare_exchange_weak( + failures, failures - 1, std::memory_order_acq_rel, + std::memory_order_acquire)) { + return false; + } + } + return ReadSeedMaterialFromOSEntropy(values); +} + +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK +static_assert(std::atomic<uint32_t>::is_always_lock_free, + "OnForkChild requires lock-free atomic uint32_t operations"); + +ABSL_CONST_INIT static std::atomic<uint32_t> atfork_registered{0}; + +// Async-signal-safe child fork handler: increments the generation counter so +// the child process lazily allocates and OS-seeds a fresh PoolArray on next +// use without touching parent spinlocks or buffered PRNG state. +void OnForkChild() { + atfork_registered.store(1, std::memory_order_relaxed); + pool_generation.fetch_add(1, std::memory_order_relaxed); +} + +// Registers OnForkChild once. Called while holding the current InitGate lock +// so concurrent cold-start callers do not register duplicate permanent atfork +// handlers. Leaves `atfork_registered` unset if pthread_atfork() fails (e.g. +// ENOMEM) so fork detection is never silently disabled. +bool EnsureAtForkRegistered() { + if (atfork_registered.load(std::memory_order_acquire) != 0) { + return true; + } + if (pthread_atfork(nullptr, nullptr, OnForkChild) != 0) { + return false; + } + atfork_registered.store(1, std::memory_order_release); + return true; +} +#endif // ABSL_RANDOM_HAVE_PTHREAD_ATFORK + +InitGate* GetOrCreateInitGate(uint32_t generation +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK + , + pid_t pid +#endif +) { + auto matches = [=](const InitGate* g) { + if (g == nullptr || g->generation != generation) return false; +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK + if (g->pid != pid) return false; +#endif + return true; + }; + + InitGate* expected = init_gate_ptr.load(std::memory_order_acquire); + if (matches(expected)) { + return expected; + } + + auto new_gate = std::make_unique<InitGate>(); + new_gate->generation = generation; +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK + new_gate->pid = pid; +#endif + + while (true) { + if (matches(expected)) { + return expected; + } + new_gate->prev = expected; + if (init_gate_ptr.compare_exchange_weak(expected, new_gate.get(), + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return new_gate.release(); + } + } +} // Returns an id in the range [0 ... kPoolSize), which indexes into the // pool of random engines. @@ -152,26 +285,88 @@ #endif } -// Allocate and initialize kPoolSize objects of type RandenPoolEntry. -void InitPoolURBG() { - static constexpr size_t kSeedSize = - RandenTraits::kStateBytes / sizeof(uint32_t); - // Read OS entropy once, and use it to initialize each pool entry. - uint32_t seed_material[kPoolSize * kSeedSize]; - if (!ReadSeedMaterialFromOSEntropy(absl::MakeSpan(seed_material))) { +// Allocate and initialize a fresh PoolArray for `current_gen` using OS entropy. +// Serialized per generation via a generation-tagged InitGate so concurrent +// cold-start or post-fork callers perform a single OS entropy read and a single +// pthread_atfork() registration without ever inheriting a parent's locked +// SpinLock across fork() or wedging on SeedGenException. +ABSL_ATTRIBUTE_NOINLINE PoolArray* InitPoolsForGeneration( + uint32_t current_gen) { +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK + InitGate* gate = GetOrCreateInitGate(current_gen, getpid()); +#else + InitGate* gate = GetOrCreateInitGate(current_gen); +#endif + + PoolArray* result = nullptr; + { + SpinLockHolder l(gate->mu); + + PoolArray* existing = shared_pools_ptr.load(std::memory_order_acquire); + if (existing != nullptr && existing->generation == current_gen) { + return existing; + } + +#ifdef ABSL_RANDOM_HAVE_PTHREAD_ATFORK + const bool atfork_ok = EnsureAtForkRegistered(); +#else + constexpr bool atfork_ok = true; +#endif + + if (atfork_ok) { + static constexpr size_t kSeedSize = + RandenTraits::kStateBytes / sizeof(uint32_t); + uint32_t seed_material[kPoolSize * kSeedSize]; + struct SeedScrubber { + absl::Span<uint32_t> values; + ~SeedScrubber() { + volatile uint32_t* p = values.data(); + for (size_t i = 0; i < values.size(); ++i) { + p[i] = 0; + } + } + } scrubber{absl::MakeSpan(seed_material)}; + + if (ReadSeedMaterialForPool(absl::MakeSpan(seed_material))) { + auto new_pools = std::make_unique<PoolArray>(); + new_pools->generation = current_gen; + for (size_t i = 0; i < kPoolSize; ++i) { + new_pools->entries[i].Init( + absl::MakeSpan(&seed_material[i * kSeedSize], kSeedSize)); + } + + while (true) { + if (existing != nullptr && existing->generation == current_gen) { + result = existing; + break; + } + new_pools->prev = existing; + if (shared_pools_ptr.compare_exchange_weak( + existing, new_pools.get(), std::memory_order_acq_rel, + std::memory_order_acquire)) { + result = new_pools.release(); + break; + } + } + } + } + } + + if (result == nullptr) { ThrowSeedGenException(); } - for (size_t i = 0; i < kPoolSize; i++) { - shared_pools[i] = new RandenPoolEntry(); - shared_pools[i]->Init( - absl::MakeSpan(&seed_material[i * kSeedSize], kSeedSize)); - } + return result; } // Returns the pool entry for the current thread. RandenPoolEntry* GetPoolForCurrentThread() { - absl::call_once(pool_once, InitPoolURBG); - return shared_pools[GetPoolID()]; + const uint32_t current_gen = pool_generation.load(std::memory_order_relaxed); + PoolArray* pools = shared_pools_ptr.load(std::memory_order_acquire); + if (ABSL_PREDICT_FALSE(pools == nullptr || + pools->generation != current_gen)) { + pools = InitPoolsForGeneration(current_gen); + } + return &pools->entries[GetPoolID()]; } } // namespace @@ -181,6 +376,18 @@ pool->Fill(reinterpret_cast<uint8_t*>(dest), bytes); } +void ResetRandenPoolForTesting() { + pool_generation.fetch_add(1, std::memory_order_acq_rel); +} + +void SetRandenPoolOSEntropyFailureCountForTesting(size_t count) { + seed_failure_count_for_testing.store(count, std::memory_order_release); +} + +size_t GetRandenPoolOSEntropyReadCountForTesting() { + return os_entropy_read_count_for_testing.load(std::memory_order_acquire); +} + } // namespace random_internal ABSL_NAMESPACE_END } // namespace absl
diff --git a/absl/random/internal/entropy_pool.h b/absl/random/internal/entropy_pool.h index 970ef87..204ec89 100644 --- a/absl/random/internal/entropy_pool.h +++ b/absl/random/internal/entropy_pool.h
@@ -28,6 +28,12 @@ // implementation to fill the internal buffer. void GetEntropyFromRandenPool(void* dest, size_t bytes); +// Internal test-only hooks for exercising RandenPool re-initialization, +// cold-start serialization, and OS entropy failure recovery. +void ResetRandenPoolForTesting(); +void SetRandenPoolOSEntropyFailureCountForTesting(size_t count); +size_t GetRandenPoolOSEntropyReadCountForTesting(); + } // namespace random_internal ABSL_NAMESPACE_END } // namespace absl
diff --git a/absl/random/internal/entropy_pool_test.cc b/absl/random/internal/entropy_pool_test.cc index 7739f19..28d47aa 100644 --- a/absl/random/internal/entropy_pool_test.cc +++ b/absl/random/internal/entropy_pool_test.cc
@@ -14,21 +14,49 @@ #include "absl/random/internal/entropy_pool.h" +#include <atomic> #include <bitset> +#include <cerrno> #include <cmath> #include <cstddef> #include <cstdint> +#include <cstdio> +#include <cstring> #include <thread> // NOLINT #include <utility> #include <vector> +#ifdef __APPLE__ +#include <TargetConditionals.h> +#endif + +#if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__) && \ + defined(TARGET_OS_OSX) && TARGET_OS_OSX)) && \ + !defined(_WIN32) && !defined(__EMSCRIPTEN__) && !defined(__wasi__) && \ + !defined(__Fuchsia__) && !defined(__VXWORKS__) && !defined(__hexagon__) && \ + !defined(__XTENSA__) && !defined(__native_client__) && !defined(__rtems__) +#define ABSL_RANDOM_TEST_HAVE_FORK 1 +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> +#endif + #include "gtest/gtest.h" +#include "absl/base/config.h" // IWYU pragma: keep #include "absl/container/flat_hash_set.h" +#include "absl/random/seed_gen_exception.h" // IWYU pragma: keep +#include "absl/synchronization/blocking_counter.h" #include "absl/synchronization/mutex.h" +#include "absl/synchronization/notification.h" namespace { using ::absl::random_internal::GetEntropyFromRandenPool; +using ::absl::random_internal::GetRandenPoolOSEntropyReadCountForTesting; +using ::absl::random_internal::ResetRandenPoolForTesting; +#ifdef ABSL_HAVE_EXCEPTIONS +using ::absl::random_internal::SetRandenPoolOSEntropyFailureCountForTesting; +#endif TEST(EntropyPoolTest, DistinctSequencesPerThread) { using result_type = uint32_t; @@ -116,4 +144,387 @@ // Zeros values must be rare; 32 / 2^32 is certainly less than 1. EXPECT_LE(zero_count, 1); } + +TEST(EntropyPoolTest, ConcurrentInitSerializesEntropyReads) { + constexpr int kNumThreads = 12; + ResetRandenPoolForTesting(); + const size_t reads_before = GetRandenPoolOSEntropyReadCountForTesting(); + + absl::BlockingCounter ready(kNumThreads); + absl::Notification go; + std::atomic<int> non_zero_threads{0}; + std::vector<std::thread> threads; + threads.reserve(kNumThreads); + for (int i = 0; i < kNumThreads; ++i) { + threads.emplace_back([&]() { + ready.DecrementCount(); + go.WaitForNotification(); + uint64_t buf[16] = {}; + GetEntropyFromRandenPool(buf, sizeof(buf)); + bool any_non_zero = false; + for (uint64_t v : buf) { + any_non_zero |= (v != 0); + } + if (any_non_zero) { + non_zero_threads.fetch_add(1, std::memory_order_relaxed); + } + }); + } + + ready.Wait(); + go.Notify(); + for (auto& t : threads) t.join(); + + EXPECT_EQ(non_zero_threads.load(std::memory_order_relaxed), kNumThreads); + EXPECT_EQ(GetRandenPoolOSEntropyReadCountForTesting() - reads_before, 1u); +} + +#ifdef ABSL_HAVE_EXCEPTIONS + +class ScopedOSEntropyFailureCount { + public: + explicit ScopedOSEntropyFailureCount(size_t count) { + SetRandenPoolOSEntropyFailureCountForTesting(count); + } + ~ScopedOSEntropyFailureCount() { + SetRandenPoolOSEntropyFailureCountForTesting(0); + } + ScopedOSEntropyFailureCount(const ScopedOSEntropyFailureCount&) = delete; + ScopedOSEntropyFailureCount& operator=(const ScopedOSEntropyFailureCount&) = + delete; +}; + +TEST(EntropyPoolTest, SeedGenExceptionDoesNotDeadlock) { + ResetRandenPoolForTesting(); + ScopedOSEntropyFailureCount inject_failures(2); + + uint64_t value = 0; + EXPECT_THROW(GetEntropyFromRandenPool(&value, sizeof(value)), + absl::SeedGenException); + EXPECT_THROW(GetEntropyFromRandenPool(&value, sizeof(value)), + absl::SeedGenException); + + // Subsequent initialization must succeed cleanly without deadlocking. + uint64_t buf[16] = {}; + EXPECT_NO_THROW(GetEntropyFromRandenPool(buf, sizeof(buf))); + bool any_non_zero = false; + for (uint64_t v : buf) { + any_non_zero |= (v != 0); + } + EXPECT_TRUE(any_non_zero); +} + +TEST(EntropyPoolTest, ConcurrentSeedGenExceptionRecovery) { + constexpr int kNumThreads = 8; + ResetRandenPoolForTesting(); + ScopedOSEntropyFailureCount inject_failures(1); + + absl::BlockingCounter ready(kNumThreads); + absl::Notification go; + std::atomic<int> caught_exceptions{0}; + std::atomic<int> succeeded{0}; + std::vector<std::thread> threads; + threads.reserve(kNumThreads); + + for (int i = 0; i < kNumThreads; ++i) { + threads.emplace_back([&]() { + ready.DecrementCount(); + go.WaitForNotification(); + uint64_t buf[16] = {}; + try { + GetEntropyFromRandenPool(buf, sizeof(buf)); + } catch (const absl::SeedGenException&) { + caught_exceptions.fetch_add(1, std::memory_order_relaxed); + GetEntropyFromRandenPool(buf, sizeof(buf)); + } + bool any_non_zero = false; + for (uint64_t v : buf) { + any_non_zero |= (v != 0); + } + if (any_non_zero) { + succeeded.fetch_add(1, std::memory_order_relaxed); + } + }); + } + + ready.Wait(); + go.Notify(); + for (auto& t : threads) t.join(); + + EXPECT_EQ(caught_exceptions.load(std::memory_order_relaxed), 1); + EXPECT_EQ(succeeded.load(std::memory_order_relaxed), kNumThreads); +} + +#endif // ABSL_HAVE_EXCEPTIONS + +#ifdef ABSL_RANDOM_TEST_HAVE_FORK + +bool WriteAll(int fd, const void* data, size_t size) { + const auto* ptr = static_cast<const uint8_t*>(data); + while (size > 0) { + const ssize_t n = write(fd, ptr, size); + if (n < 0) { + if (errno == EINTR) continue; + return false; + } + ptr += n; + size -= static_cast<size_t>(n); + } + return true; +} + +bool ReadAll(int fd, void* data, size_t size) { + auto* ptr = static_cast<uint8_t*>(data); + while (size > 0) { + const ssize_t n = read(fd, ptr, size); + if (n < 0) { + if (errno == EINTR) continue; + return false; + } + if (n == 0) return false; + ptr += n; + size -= static_cast<size_t>(n); + } + return true; +} + +int WaitForChildExit(pid_t pid) { + int status = 0; + pid_t ret; + do { + ret = waitpid(pid, &status, 0); + } while (ret < 0 && errno == EINTR); + if (ret != pid || !WIFEXITED(status)) return -1; + return WEXITSTATUS(status); +} + +TEST(EntropyPoolTest, DistinctSequencesAcrossFork) { + // Warm up the pool in the parent before fork() so buffered Randen state is + // already populated and ready to be cloned into child address spaces. + uint64_t warmup = 0; + GetEntropyFromRandenPool(&warmup, sizeof(warmup)); + + constexpr size_t kNumValues = 16; + int pipe1[2]; + ASSERT_EQ(pipe(pipe1), 0); + + std::fflush(nullptr); + const pid_t pid1 = fork(); + if (pid1 < 0) { + const int fork1_errno = errno; + close(pipe1[0]); + close(pipe1[1]); + if (fork1_errno == ENOSYS || fork1_errno == EPERM) { + GTEST_SKIP() << "fork() is not permitted in this environment."; + } + FAIL() << "First fork() failed: " << std::strerror(fork1_errno); + } + + if (pid1 == 0) { + close(pipe1[0]); + std::vector<uint64_t> seq(kNumValues); + GetEntropyFromRandenPool(seq.data(), sizeof(uint64_t) * seq.size()); + + // Also verify nested fork() reseeds a grandchild relative to this child. + int gc_pipe[2]; + if (pipe(gc_pipe) != 0) _exit(2); + const pid_t gc_pid = fork(); + if (gc_pid < 0) _exit(3); + if (gc_pid == 0) { + close(gc_pipe[0]); + close(pipe1[1]); + std::vector<uint64_t> gc_seq(kNumValues); + GetEntropyFromRandenPool(gc_seq.data(), sizeof(uint64_t) * gc_seq.size()); + const bool ok = + WriteAll(gc_pipe[1], gc_seq.data(), sizeof(uint64_t) * gc_seq.size()); + close(gc_pipe[1]); + _exit(ok ? 0 : 4); + } + close(gc_pipe[1]); + std::vector<uint64_t> child_after_gc(kNumValues); + GetEntropyFromRandenPool(child_after_gc.data(), + sizeof(uint64_t) * child_after_gc.size()); + std::vector<uint64_t> gc_seq(kNumValues); + const bool gc_read_ok = + ReadAll(gc_pipe[0], gc_seq.data(), sizeof(uint64_t) * gc_seq.size()); + close(gc_pipe[0]); + const int gc_exit = WaitForChildExit(gc_pid); + + const bool write_ok = + WriteAll(pipe1[1], seq.data(), sizeof(uint64_t) * seq.size()); + close(pipe1[1]); + if (!gc_read_ok || gc_exit != 0 || !write_ok || gc_seq == child_after_gc || + gc_seq == seq) { + _exit(5); + } + _exit(0); + } + close(pipe1[1]); + + int pipe2[2]; + if (pipe(pipe2) != 0) { + const int pipe_errno = errno; + close(pipe1[0]); + WaitForChildExit(pid1); + FAIL() << "Second pipe() failed: " << std::strerror(pipe_errno); + } + std::fflush(nullptr); + const pid_t pid2 = fork(); + if (pid2 < 0) { + const int fork2_errno = errno; + close(pipe1[0]); + close(pipe2[0]); + close(pipe2[1]); + WaitForChildExit(pid1); + FAIL() << "Second fork() failed: " << std::strerror(fork2_errno); + } + if (pid2 == 0) { + close(pipe1[0]); + close(pipe2[0]); + std::vector<uint64_t> seq(kNumValues); + GetEntropyFromRandenPool(seq.data(), sizeof(uint64_t) * seq.size()); + const bool ok = + WriteAll(pipe2[1], seq.data(), sizeof(uint64_t) * seq.size()); + close(pipe2[1]); + _exit(ok ? 0 : 1); + } + close(pipe2[1]); + + std::vector<uint64_t> parent_seq(kNumValues); + GetEntropyFromRandenPool(parent_seq.data(), + sizeof(uint64_t) * parent_seq.size()); + + std::vector<uint64_t> child1_seq(kNumValues); + std::vector<uint64_t> child2_seq(kNumValues); + const bool read1_ok = ReadAll(pipe1[0], child1_seq.data(), + sizeof(uint64_t) * child1_seq.size()); + const bool read2_ok = ReadAll(pipe2[0], child2_seq.data(), + sizeof(uint64_t) * child2_seq.size()); + close(pipe1[0]); + close(pipe2[0]); + + EXPECT_EQ(WaitForChildExit(pid1), 0); + EXPECT_EQ(WaitForChildExit(pid2), 0); + ASSERT_TRUE(read1_ok); + ASSERT_TRUE(read2_ok); + + EXPECT_NE(parent_seq, child1_seq); + EXPECT_NE(parent_seq, child2_seq); + EXPECT_NE(child1_seq, child2_seq); +} + +TEST(EntropyPoolTest, ForkDuringConcurrentPoolAccess) { + uint64_t warmup = 0; + GetEntropyFromRandenPool(&warmup, sizeof(warmup)); + + // Verify fork() works in this environment before spawning background threads. + std::fflush(nullptr); + const pid_t probe = fork(); + const int probe_errno = errno; + if (probe < 0 && (probe_errno == ENOSYS || probe_errno == EPERM)) { + GTEST_SKIP() << "fork() is not permitted in this environment."; + } + ASSERT_GE(probe, 0) << std::strerror(probe_errno); + if (probe == 0) _exit(0); + ASSERT_EQ(WaitForChildExit(probe), 0); + + // Spawn 8 threads (matching kPoolSize) so every RandenPoolEntry spinlock, + // including the slot assigned to this thread, is contended during fork(). + constexpr int kNumThreads = 8; + std::atomic<bool> stop{false}; + std::atomic<int> ready{0}; + std::vector<std::thread> threads; + threads.reserve(kNumThreads); + + struct ThreadJoiner { + std::atomic<bool>& stop_flag; + std::vector<std::thread>& pool; + ~ThreadJoiner() { + stop_flag.store(true, std::memory_order_relaxed); + for (auto& t : pool) { + if (t.joinable()) t.join(); + } + } + } joiner{stop, threads}; + + for (int i = 0; i < kNumThreads; ++i) { + threads.emplace_back([&]() { + uint64_t buf[32]; + GetEntropyFromRandenPool(buf, sizeof(buf)); + ready.fetch_add(1, std::memory_order_release); + while (!stop.load(std::memory_order_relaxed)) { + GetEntropyFromRandenPool(buf, sizeof(buf)); + } + }); + } + while (ready.load(std::memory_order_acquire) < kNumThreads) { + std::this_thread::yield(); + } + + constexpr int kNumForks = 16; + for (int i = 0; i < kNumForks; ++i) { + const pid_t pid = fork(); + ASSERT_GE(pid, 0) << std::strerror(errno); + if (pid == 0) { + alarm(10); + uint64_t child_buf[32] = {}; + GetEntropyFromRandenPool(child_buf, sizeof(child_buf)); + bool any_non_zero = false; + for (uint64_t v : child_buf) { + any_non_zero |= (v != 0); + } + _exit(any_non_zero ? 0 : 2); + } + EXPECT_EQ(WaitForChildExit(pid), 0) << "iteration " << i; + } +} + +#ifdef ABSL_HAVE_EXCEPTIONS +TEST(EntropyPoolTest, SeedGenExceptionRecoveryAfterFork) { + uint64_t warmup = 0; + GetEntropyFromRandenPool(&warmup, sizeof(warmup)); + + std::fflush(nullptr); + const pid_t pid = fork(); + const int fork_errno = errno; + if (pid < 0 && (fork_errno == ENOSYS || fork_errno == EPERM)) { + GTEST_SKIP() << "fork() is not permitted in this environment."; + } + ASSERT_GE(pid, 0) << std::strerror(fork_errno); + + if (pid == 0) { + alarm(10); + // Inject an OS entropy failure in the child without resetting the pool + // explicitly, verifying that OnForkChild() triggers re-initialization, + // SeedGenException is thrown cleanly, and the retry succeeds. + SetRandenPoolOSEntropyFailureCountForTesting(1); + uint64_t buf[16] = {}; + bool caught = false; + try { + GetEntropyFromRandenPool(buf, sizeof(buf)); + } catch (const absl::SeedGenException&) { + caught = true; + } + if (!caught) _exit(2); + + try { + GetEntropyFromRandenPool(buf, sizeof(buf)); + } catch (...) { + _exit(3); + } + bool any_non_zero = false; + for (uint64_t v : buf) { + any_non_zero |= (v != 0); + } + _exit(any_non_zero ? 0 : 4); + } + + EXPECT_EQ(WaitForChildExit(pid), 0); + uint64_t parent_buf[16] = {}; + EXPECT_NO_THROW(GetEntropyFromRandenPool(parent_buf, sizeof(parent_buf))); +} +#endif // ABSL_HAVE_EXCEPTIONS + +#endif // ABSL_RANDOM_TEST_HAVE_FORK + } // namespace