Fix `absl/random` `SeedSequence` handling, salting, and engine seeding. Addresses several correctness and seed-quality issues in `absl/random`: * Seed sequence wrapping and overloads: Passing an lvalue or `const` `absl::SeedSeq` to `absl::BitGen` or `absl::InsecureBitGen` previously copied or re-wrapped it, causing double-salting or losing state from zero-size seeders. Brace-moving `absl::SeedSeq` also selected the `initializer_list` overload instead of moving. Wrapping by reference where possible and constraining `SaltedSeedSeq` constructors fixes these cases without extra copies. * Salted seed mixing: Widens process salt material to 128 bits and switches `SaltedSeedSeq` mixing to SipHash-2-4-128 so `std::seed_seq` inputs preserve full seed entropy across narrow and wide draws without altering `size()` or `param()`. * SFINAE and iterator correctness: Enforces consistent `[rand.req.seedseq]` constraints across `randen_engine`, `pcg_engine`, `SaltedSeedSeq`, and `NonsecureURBGBase`, fixes 64-bit `result_type` sizing in `randen_engine`, and avoids raw byte writes into `bool` or non-integral iterators in `RandenPoolSeedSeq::generate()`. * Engine seeding and buffer hygiene: Fills the full `randen_engine` rate for salted seeds (keeping unsalted `randen_engine` streams unchanged), ensures `randen_engine::reseed()` mixes existing state before absorbing new seed material, and clears temporary seed buffers after use. PiperOrigin-RevId: 1022538016
diff --git a/absl/random/CMakeLists.txt b/absl/random/CMakeLists.txt index cef4ab5..8bc4f11 100644 --- a/absl/random/CMakeLists.txt +++ b/absl/random/CMakeLists.txt
@@ -613,6 +613,8 @@ ${ABSL_DEFAULT_LINKOPTS} $<$<BOOL:${MINGW}>:-lbcrypt> DEPS + absl::algorithm_container + absl::bits absl::config absl::optional absl::random_internal_fast_uniform_bits @@ -688,9 +690,11 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::config absl::inlined_vector absl::optional absl::random_internal_seed_material + absl::random_internal_traits absl::span absl::type_traits ) @@ -774,6 +778,7 @@ absl::random_internal_entropy_pool absl::random_internal_salted_seed_seq absl::random_internal_seed_material + absl::random_internal_traits absl::type_traits ) @@ -788,10 +793,12 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::bits absl::config absl::int128 absl::random_internal_fastmath absl::random_internal_iostream_state_saver + absl::random_internal_traits absl::type_traits ) @@ -806,9 +813,11 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::config absl::endian absl::random_internal_iostream_state_saver absl::random_internal_randen + absl::random_internal_traits absl::raw_logging_internal absl::type_traits ) @@ -1019,7 +1028,11 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::config + absl::core_headers absl::random_internal_salted_seed_seq + absl::random_internal_seed_material + absl::random_internal_traits GTest::gmock GTest::gtest_main ) @@ -1067,12 +1080,16 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS - absl::flat_hash_map + absl::algorithm_container + absl::flat_hash_set absl::random_distributions absl::random_internal_nonsecure_base + absl::random_internal_pcg_engine + absl::random_internal_seed_material absl::random_random absl::synchronization absl::type_traits + GTest::gmock GTest::gtest_main ) @@ -1087,6 +1104,7 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::flat_hash_set absl::random_internal_seed_material absl::span GTest::gmock @@ -1104,7 +1122,7 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS - absl::flat_hash_map + absl::flat_hash_set absl::random_internal_entropy_pool absl::synchronization GTest::gtest_main @@ -1121,6 +1139,7 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::config absl::random_internal_explicit_seed_seq absl::random_internal_pcg_engine absl::time @@ -1139,9 +1158,12 @@ LINKOPTS ${ABSL_DEFAULT_LINKOPTS} DEPS + absl::config absl::log absl::random_internal_explicit_seed_seq + absl::random_internal_randen absl::random_internal_randen_engine + absl::random_internal_traits absl::strings absl::time GTest::gmock
diff --git a/absl/random/internal/BUILD.bazel b/absl/random/internal/BUILD.bazel index 04f9a27..ab772b6 100644 --- a/absl/random/internal/BUILD.bazel +++ b/absl/random/internal/BUILD.bazel
@@ -170,9 +170,11 @@ }), deps = [ ":fast_uniform_bits", + "//absl/algorithm:container", "//absl/base:config", "//absl/base:dynamic_annotations", "//absl/base:raw_logging_internal", + "//absl/numeric:bits", "//absl/strings", "//absl/strings:string_view", "//absl/types:optional", @@ -239,6 +241,7 @@ linkopts = ABSL_DEFAULT_LINKOPTS, deps = [ ":seed_material", + ":traits", "//absl/base:config", "//absl/container:inlined_vector", "//absl/meta:type_traits", @@ -310,6 +313,7 @@ ":entropy_pool", ":salted_seed_seq", ":seed_material", + ":traits", "//absl/base:config", "//absl/container:inlined_vector", "//absl/meta:type_traits", @@ -324,6 +328,7 @@ deps = [ ":fastmath", ":iostream_state_saver", + ":traits", "//absl/base:config", "//absl/meta:type_traits", "//absl/numeric:bits", @@ -341,6 +346,7 @@ deps = [ ":iostream_state_saver", ":randen", + ":traits", "//absl/base:config", "//absl/base:endian", "//absl/meta:type_traits", @@ -565,6 +571,8 @@ deps = [ ":salted_seed_seq", ":seed_material", + ":traits", + "//absl/base:config", "//absl/base:core_headers", "@googletest//:gtest", "@googletest//:gtest_main", @@ -638,6 +646,8 @@ linkopts = ABSL_DEFAULT_LINKOPTS, deps = [ ":nonsecure_base", + ":pcg_engine", + ":seed_material", "//absl/algorithm:container", "//absl/container:flat_hash_set", "//absl/random", @@ -656,6 +666,7 @@ linkopts = ABSL_DEFAULT_LINKOPTS, deps = [ ":seed_material", + "//absl/container:flat_hash_set", "//absl/types:span", "@googletest//:gtest", "@googletest//:gtest_main", @@ -689,6 +700,7 @@ deps = [ ":explicit_seed_seq", ":pcg_engine", + "//absl/base:config", "@googletest//:gtest", "@googletest//:gtest_main", ], @@ -704,7 +716,10 @@ linkopts = ABSL_DEFAULT_LINKOPTS, deps = [ ":explicit_seed_seq", + ":randen", ":randen_engine", + ":traits", + "//absl/base:config", "//absl/log", "//absl/time", "@googletest//:gtest",
diff --git a/absl/random/internal/entropy_pool.cc b/absl/random/internal/entropy_pool.cc index 21f8305..bf36a2e 100644 --- a/absl/random/internal/entropy_pool.cc +++ b/absl/random/internal/entropy_pool.cc
@@ -91,9 +91,11 @@ size_t remaining = available() * sizeof(state_[0]); size_t to_copy = std::min(bytes, remaining); std::memcpy(out, &state_[next_], to_copy); + const size_t words_consumed = + (to_copy + sizeof(state_[0]) - 1) / sizeof(state_[0]); out += to_copy; bytes -= to_copy; - next_ += (to_copy + sizeof(state_[0]) - 1) / sizeof(state_[0]); + next_ += words_consumed; } } @@ -158,6 +160,7 @@ RandenTraits::kStateBytes / sizeof(uint32_t); // Read OS entropy once, and use it to initialize each pool entry. uint32_t seed_material[kPoolSize * kSeedSize]; + ScopedCleanse cleaner(seed_material, sizeof(seed_material)); if (!ReadSeedMaterialFromOSEntropy(absl::MakeSpan(seed_material))) { ThrowSeedGenException(); }
diff --git a/absl/random/internal/entropy_pool_test.cc b/absl/random/internal/entropy_pool_test.cc index 7739f19..2d97560 100644 --- a/absl/random/internal/entropy_pool_test.cc +++ b/absl/random/internal/entropy_pool_test.cc
@@ -116,4 +116,37 @@ // Zeros values must be rare; 32 / 2^32 is certainly less than 1. EXPECT_LE(zero_count, 1); } + +TEST(EntropyPoolTest, PartialWordDrawsAndMultiRefillsProduceDistinctBlocks) { + // Zero-byte draw must not modify the buffer. + uint8_t zero_canary[4] = {0xaa, 0xbb, 0xcc, 0xdd}; + GetEntropyFromRandenPool(zero_canary, 0); + EXPECT_EQ(zero_canary[0], 0xaa); + EXPECT_EQ(zero_canary[3], 0xdd); + + // Unaligned and cross-refill byte counts must fill exactly `bytes` without + // overwriting trailing sentinel bytes. + constexpr uint8_t kSentinel = 0xa5; + for (size_t bytes : {size_t{1}, size_t{2}, size_t{3}, size_t{5}, size_t{7}, + size_t{239}, size_t{241}}) { + std::vector<uint8_t> buf(bytes + 8, kSentinel); + GetEntropyFromRandenPool(buf.data(), bytes); + for (size_t i = bytes; i < buf.size(); ++i) { + EXPECT_EQ(buf[i], kSentinel) << "bytes=" << bytes << " i=" << i; + } + } + + // Draw across multiple 240-byte Randen refills on a single thread to exercise + // rate-word erasure across refill boundaries. + constexpr size_t kBlockBytes = 240; + constexpr size_t kNumBlocks = 8; + absl::flat_hash_set<std::vector<uint8_t>> blocks; + const std::vector<uint8_t> all_zero(kBlockBytes, 0); + for (size_t i = 0; i < kNumBlocks; ++i) { + std::vector<uint8_t> block(kBlockBytes, 0); + GetEntropyFromRandenPool(block.data(), block.size()); + EXPECT_NE(block, all_zero); + EXPECT_TRUE(blocks.insert(std::move(block)).second); + } +} } // namespace
diff --git a/absl/random/internal/nonsecure_base.h b/absl/random/internal/nonsecure_base.h index d1442f8..40b302b 100644 --- a/absl/random/internal/nonsecure_base.h +++ b/absl/random/internal/nonsecure_base.h
@@ -29,6 +29,7 @@ #include "absl/random/internal/entropy_pool.h" #include "absl/random/internal/salted_seed_seq.h" #include "absl/random/internal/seed_material.h" +#include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN @@ -37,54 +38,45 @@ // RandenPoolSeedSeq is a custom seed sequence type where generate() fills the // provided buffer via the RandenPool entropy source. class RandenPoolSeedSeq { - private: - struct ContiguousTag {}; - struct BufferTag {}; - - // Generate random unsigned values directly into the buffer. - template <typename Contiguous> - void generate_impl(ContiguousTag, Contiguous begin, Contiguous end) { - const size_t n = static_cast<size_t>(std::distance(begin, end)); - auto* a = &(*begin); - GetEntropyFromRandenPool(a, sizeof(*a) * n); - } - - // Construct a buffer of size n and fill it with values, then copy - // those values into the seed iterators. - template <typename RandomAccessIterator> - void generate_impl(BufferTag, RandomAccessIterator begin, - RandomAccessIterator end) { - const size_t n = std::distance(begin, end); - absl::InlinedVector<uint32_t, 8> data(n, 0); - GetEntropyFromRandenPool(data.begin(), sizeof(data[0]) * n); - std::copy(std::begin(data), std::end(data), begin); - } - public: using result_type = uint32_t; - size_t size() { return 0; } + size_t size() const { return 0; } template <typename OutIterator> void param(OutIterator) const {} template <typename RandomAccessIterator> void generate(RandomAccessIterator begin, RandomAccessIterator end) { - // RandomAccessIterator must be assignable from uint32_t - if (begin != end) { - using U = typename std::iterator_traits<RandomAccessIterator>::value_type; - // ContiguousTag indicates the common case of a known contiguous buffer, - // which allows directly filling the buffer. In C++20, - // std::contiguous_iterator_tag provides a mechanism for testing this - // capability, however until Abseil's support requirements allow us to - // assume C++20, limit checks to a few common cases. - using TagType = std::conditional_t< - (std::is_pointer_v<RandomAccessIterator> || - std::is_same_v<RandomAccessIterator, - typename std::vector<U>::iterator>), - ContiguousTag, BufferTag>; + if (begin == end) { + return; + } + const size_t n = static_cast<size_t>(std::distance(begin, end)); + if constexpr (CanFillDirectly<RandomAccessIterator>()) { + auto* a = &(*begin); + GetEntropyFromRandenPool(a, sizeof(*a) * n); + } else { + absl::InlinedVector<uint32_t, 8> data(n, 0); + ScopedCleanse cleaner(data.data(), data.size() * sizeof(uint32_t)); + GetEntropyFromRandenPool(data.data(), sizeof(data[0]) * n); + std::copy(std::begin(data), std::end(data), begin); + } + } - generate_impl(TagType{}, begin, end); + private: + // Fast path only for contiguous buffers of mutable, unqualified, non-bool + // integral values (`V*` or `std::vector<V>::iterator`). + template <typename Iter> + static constexpr bool CanFillDirectly() { + using V = typename std::iterator_traits<Iter>::value_type; + using Ref = typename std::iterator_traits<Iter>::reference; + if constexpr (std::is_same_v<V, absl::remove_cvref_t<V>> && + std::is_integral_v<V> && !std::is_same_v<V, bool> && + std::is_same_v<Ref, V&>) { + return std::is_pointer_v<Iter> || + std::is_same_v<Iter, typename std::vector<V>::iterator>; + } else { + return false; } } }; @@ -93,6 +85,41 @@ // by a thread-unique URBG-instance. template <typename URBG, typename Seeder = RandenPoolSeedSeq> class NonsecureURBGBase { + private: + static URBG ConstructURBG() { + Seeder seeder; + return URBG(seeder); + } + + // Direct path: seeds `URBG` directly from an already-salted sequence, or + // from a stack-scoped non-owning `SaltedSeedSeq<Raw&>` without copying. + template < + typename SSeq, typename Raw = std::remove_reference_t<SSeq>, + typename Direct = + std::conditional_t<IsSaltedSeedSeq<absl::remove_cvref_t<Raw>>::value, + Raw, SaltedSeedSeq<Raw&>>, + typename = std::enable_if_t<std::conjunction_v< + HasSeedSeqGenerate<SSeq>, std::is_constructible<URBG, Direct&>>>> + static URBG ConstructURBG(SSeq&& seq, int) { // NOLINT(runtime/references) + if constexpr (IsSaltedSeedSeq<absl::remove_cvref_t<Raw>>::value) { + return URBG(seq); + } else { + SaltedSeedSeq<Raw&> salted_seq(seq); + return URBG(salted_seq); + } + } + + // Fallback path for `const` seed sequences whose `generate()` is non-const: + // clones parameters via `MakeSaltedSeedSeq(seq)` into a mutable wrapper. + template <typename SSeq, + typename Salted = decltype(random_internal::MakeSaltedSeedSeq( + std::declval<SSeq&>())), + typename = std::enable_if_t<std::is_constructible_v<URBG, Salted&>>> + static URBG ConstructURBG(SSeq&& seq, char) { // NOLINT(runtime/references) + auto salted_seq = random_internal::MakeSaltedSeedSeq(seq); + return URBG(salted_seq); + } + public: using result_type = typename URBG::result_type; @@ -106,10 +133,14 @@ NonsecureURBGBase& operator=(NonsecureURBGBase&&) = default; // Constructor using a seed - template <class SSeq, typename = typename std::enable_if_t< - !std::is_same_v<SSeq, NonsecureURBGBase>>> + template < + class SSeq, + typename = std::enable_if_t< + !std::is_base_of_v<NonsecureURBGBase, absl::remove_cvref_t<SSeq>> && + !std::is_convertible_v<SSeq, result_type>>, + typename = decltype(ConstructURBG(std::declval<SSeq>(), 0))> explicit NonsecureURBGBase(SSeq&& seq) - : urbg_(ConstructURBG(std::forward<SSeq>(seq))) {} + : urbg_(ConstructURBG(std::forward<SSeq>(seq), 0)) {} // Note: on MSVC, min() or max() can be interpreted as MIN() or MAX(), so we // enclose min() or max() in parens as (min)() and (max)(). @@ -138,18 +169,6 @@ } private: - static URBG ConstructURBG() { - Seeder seeder; - return URBG(seeder); - } - - template <typename SSeq> - static URBG ConstructURBG(SSeq&& seq) { // NOLINT(runtime/references) - auto salted_seq = - random_internal::MakeSaltedSeedSeq(std::forward<SSeq>(seq)); - return URBG(salted_seq); - } - URBG urbg_; };
diff --git a/absl/random/internal/nonsecure_base_test.cc b/absl/random/internal/nonsecure_base_test.cc index 61f49cd..9da3877 100644 --- a/absl/random/internal/nonsecure_base_test.cc +++ b/absl/random/internal/nonsecure_base_test.cc
@@ -15,19 +15,30 @@ #include "absl/random/internal/nonsecure_base.h" #include <algorithm> +#include <array> +#include <cmath> #include <cstddef> #include <cstdint> +#include <cstring> +#include <deque> +#include <functional> +#include <ios> #include <iterator> +#include <ostream> #include <random> +#include <set> #include <thread> // NOLINT #include <type_traits> #include <utility> #include <vector> +#include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/random/distributions.h" +#include "absl/random/internal/pcg_engine.h" +#include "absl/random/internal/seed_material.h" #include "absl/random/random.h" #include "absl/synchronization/mutex.h" @@ -76,6 +87,18 @@ static_assert(!std::is_copy_constructible_v<E>, "NonsecureURBGBase should not be copy constructible"); + static_assert(!std::is_constructible_v<E, E&>, + "NonsecureURBGBase should not be constructible from non-const " + "lvalue reference"); + static_assert(!std::is_constructible_v<E, int>, + "NonsecureURBGBase should not be constructible from int"); + static_assert(!std::is_constructible_v<E, T>, + "NonsecureURBGBase should not be constructible from " + "result_type"); + static_assert(!std::is_constructible_v<absl::BitGen, int>, + "BitGen should not be constructible from int"); + static_assert(!std::is_constructible_v<absl::BitGen, absl::BitGen&>, + "BitGen should not be constructible from BitGen&"); static_assert(!std::is_copy_assignable_v<E>, "NonsecureURBGBase should not be copy assignable"); @@ -265,3 +288,524 @@ seeder.generate(std::begin(state), std::end(state)); EXPECT_FALSE(state[0] == 0 && state[1] == 0); } + +TEST(RandenPoolSeedSeqTest, SizeIsConstAndZero) { + const absl::random_internal::RandenPoolSeedSeq const_seeder; + EXPECT_EQ(const_seeder.size(), 0u); +} + +namespace { +// Arbitrary nothing-up-my-sleeve test seed constants. +constexpr std::array<uint32_t, 4> kTestSeedWords = {1, 2, 3, 4}; +constexpr std::array<uint32_t, 3> kParamSeedWords = {10, 20, 30}; +constexpr uint32_t kTestSeedStart = 0xdeadbeefu; + +struct AssignableSeedSink { + static constexpr uint64_t kHeadCanary = 0x1122334455667788ull; + static constexpr uint64_t kTailCanary = 0x99aabbccddeeff00ull; + + uint64_t head_canary = kHeadCanary; + uint32_t value = 0; + int assignments = 0; + uint64_t tail_canary = kTailCanary; + + AssignableSeedSink& operator=(uint32_t v) { + value = v; + ++assignments; + return *this; + } +}; + +void PrintTo(const AssignableSeedSink& s, std::ostream* os) { + *os << "{head_canary=" << std::hex << s.head_canary + << ", tail_canary=" << s.tail_canary << std::dec + << ", assignments=" << s.assignments << ", value=" << s.value << "}"; +} + +MATCHER(HasValidBoolRepresentation, "has raw byte representation 0 or 1") { + unsigned char raw = 0xff; + static_assert(sizeof(bool) == sizeof(unsigned char)); + std::memcpy(&raw, &arg, sizeof(raw)); + return raw <= 1u; +} + +MATCHER(IsAssignedOnceKeepingCanaries, + "is assigned once without overwriting surrounding canary fields") { + return arg.head_canary == AssignableSeedSink::kHeadCanary && + arg.tail_canary == AssignableSeedSink::kTailCanary && + arg.assignments == 1; +} + +MATCHER(IsFiniteInUint32Range, "is finite and in [0, UINT32_MAX]") { + return std::isfinite(arg) && arg >= 0.0 && + arg <= static_cast<double>(UINT32_MAX); +} +} // namespace + +TEST(RandenPoolSeedSeqTest, BoolArrayGenerateWritesValidZeroOrOneBytes) { + absl::random_internal::RandenPoolSeedSeq seeder; + + bool bool_array[64] = {}; + seeder.generate(std::begin(bool_array), std::end(bool_array)); + EXPECT_THAT(bool_array, testing::Each(HasValidBoolRepresentation())); + EXPECT_THAT(bool_array, testing::Contains(true)); +} + +TEST(RandenPoolSeedSeqTest, VectorBoolGeneratePopulatesElements) { + absl::random_internal::RandenPoolSeedSeq seeder; + + std::vector<bool> bool_vec(16, false); + seeder.generate(bool_vec.begin(), bool_vec.end()); + EXPECT_THAT(bool_vec, testing::Contains(true)); +} + +TEST(RandenPoolSeedSeqTest, NarrowIntegralArraysAndDequeGenerate) { + absl::random_internal::RandenPoolSeedSeq seeder; + + uint8_t bytes[16] = {}; + seeder.generate(std::begin(bytes), std::end(bytes)); + EXPECT_THAT(bytes, testing::Contains(testing::Ne(uint8_t{0}))); + + uint16_t shorts[16] = {}; + seeder.generate(std::begin(shorts), std::end(shorts)); + EXPECT_THAT(shorts, testing::Contains(testing::Ne(uint16_t{0}))); + + std::deque<uint32_t> dq(16, 0u); + seeder.generate(dq.begin(), dq.end()); + EXPECT_THAT(dq, testing::Contains(testing::Ne(uint32_t{0}))); +} + +namespace { +class VolatileValueTypeIterator { + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = volatile uint32_t; + using difference_type = ptrdiff_t; + using pointer = volatile uint32_t*; + using reference = volatile uint32_t&; + + explicit VolatileValueTypeIterator(volatile uint32_t* p) : p_(p) {} + + reference operator*() const { return *p_; } + VolatileValueTypeIterator& operator++() { + ++p_; + return *this; + } + VolatileValueTypeIterator& operator+=(difference_type n) { + p_ += n; + return *this; + } + friend difference_type operator-(VolatileValueTypeIterator a, + VolatileValueTypeIterator b) { + return a.p_ - b.p_; + } + friend bool operator==(VolatileValueTypeIterator a, + VolatileValueTypeIterator b) { + return a.p_ == b.p_; + } + friend bool operator!=(VolatileValueTypeIterator a, + VolatileValueTypeIterator b) { + return a.p_ != b.p_; + } + + private: + volatile uint32_t* p_; +}; +} // namespace + +TEST(RandenPoolSeedSeqTest, VolatileValueTypeCustomIteratorGenerate) { + absl::random_internal::RandenPoolSeedSeq seeder; + volatile uint32_t buf[8] = {}; + seeder.generate(VolatileValueTypeIterator(buf), + VolatileValueTypeIterator(buf + 8)); + std::array<uint32_t, 8> copy{}; + for (size_t i = 0; i < copy.size(); ++i) { + copy[i] = buf[i]; + } + EXPECT_THAT(copy, testing::Contains(testing::Ne(uint32_t{0}))); +} + +TEST(RandenPoolSeedSeqTest, + GenerateAssignsCustomSinkWithoutOverwritingAdjacentFields) { + absl::random_internal::RandenPoolSeedSeq seeder; + + // Size 12 exceeds InlinedVector<uint32_t, 8>'s inline capacity to exercise + // heap-backed BufferTag generation and scrubbing as well. + AssignableSeedSink sink_array[12]; + seeder.generate(std::begin(sink_array), std::end(sink_array)); + EXPECT_THAT(sink_array, testing::Each(IsAssignedOnceKeepingCanaries())); + EXPECT_THAT(sink_array, testing::Contains(testing::Field( + &AssignableSeedSink::value, testing::Ne(0u)))); + + std::vector<AssignableSeedSink> sink_vec(6); + seeder.generate(sink_vec.begin(), sink_vec.end()); + EXPECT_THAT(sink_vec, testing::Each(IsAssignedOnceKeepingCanaries())); +} + +TEST(RandenPoolSeedSeqTest, + GeneratePopulatesFloatingPointElementsInUint32Range) { + absl::random_internal::RandenPoolSeedSeq seeder; + + double fp_array[8] = {}; + seeder.generate(std::begin(fp_array), std::end(fp_array)); + EXPECT_THAT(fp_array, testing::Each(IsFiniteInUint32Range())); +} + +TEST(RandenPoolSeedSeqTest, GeneratePopulatesVolatileUint32Array) { + absl::random_internal::RandenPoolSeedSeq seeder; + + volatile uint32_t vol_array[4] = {}; + seeder.generate(std::begin(vol_array), std::end(vol_array)); + uint32_t snapshot[4] = {}; + std::copy(std::begin(vol_array), std::end(vol_array), std::begin(snapshot)); + EXPECT_THAT(snapshot, testing::Contains(testing::Ne(0u))); +} + +namespace { +template <typename URBG> +std::array<typename URBG::result_type, 16> GenerateSequence(URBG& gen) { + std::array<typename URBG::result_type, 16> out; + std::generate(out.begin(), out.end(), std::ref(gen)); + return out; +} + +template <typename ResultT, bool kConstGenerate = true, uint32_t kStart = 1, + bool kConstSize = true, bool kHasSize = true> +struct TestSeedSeq { + using result_type = ResultT; + size_t count = 4; + uint32_t start = kStart; + + explicit TestSeedSeq(size_t n = 4) : count(n) {} + + template <bool H = kHasSize, bool C = kConstSize, + std::enable_if_t<H && C, int> = 0> + size_t size() const { + return count; + } + template <bool H = kHasSize, bool C = kConstSize, + std::enable_if_t<H && !C, int> = 0> + size_t size() { + return count; + } + + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<C, int> = 0> + void generate(OutIt begin, OutIt end) const { + uint32_t v = start; + for (OutIt it = begin; it != end; ++it) *it = v++; + } + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<!C, int> = 0> + void generate(OutIt begin, OutIt end) { + uint32_t v = start; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; + +struct NoResultTypeSeedSeq { + size_t size() const { return 2; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + uint32_t v = 1; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; + +template <bool kConstGenerate> +struct ZeroSizeCounterSeedSeq { + using result_type = uint32_t; + mutable uint32_t counter = 1; + size_t size() const { return 0; } + template <typename OutIt> + void param(OutIt) const {} + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<C, int> = 0> + void generate(OutIt begin, OutIt end) const { + for (OutIt it = begin; it != end; ++it) *it = counter++; + } + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<!C, int> = 0> + void generate(OutIt begin, OutIt end) { + for (OutIt it = begin; it != end; ++it) *it = counter++; + } +}; + +template <bool kConstGenerate, bool kHasSize> +struct TestParamSeedSeq + : TestSeedSeq<uint32_t, kConstGenerate, 1, /*kConstSize=*/false, kHasSize> { + std::vector<uint32_t> values; + TestParamSeedSeq() = default; + template <typename It> + TestParamSeedSeq(It begin, It end) : values(begin, end) { + this->count = values.size(); + this->start = values.empty() ? 1u : values[0]; + } + template <typename OutIt> + void param(OutIt out) const { + std::copy(values.begin(), values.end(), out); + } +}; + +using StatefulZeroSizeSeedSeq = ZeroSizeCounterSeedSeq<false>; +using ConstGenerateZeroSizeSeedSeq = ZeroSizeCounterSeedSeq<true>; +using SeedSeq64 = + TestSeedSeq<uint64_t, /*kConstGenerate=*/false, kTestSeedStart>; +using SeedSeq32 = + TestSeedSeq<uint32_t, /*kConstGenerate=*/false, kTestSeedStart>; +using SignedResultTypeSeedSeq = TestSeedSeq<int32_t>; +using NarrowResultTypeSeedSeq = TestSeedSeq<uint16_t>; +using VoidResultTypeSeedSeq = TestSeedSeq<void>; +using ConstGenerateNonConstSizeSeedSeq = + TestSeedSeq<uint32_t, /*kConstGenerate=*/true, 1, /*kConstSize=*/false>; +using ConstGenerateNoSizeSeedSeq = + TestSeedSeq<uint32_t, /*kConstGenerate=*/true, 1, /*kConstSize=*/true, + /*kHasSize=*/false>; +using ConstGenerateNonConstSizeWithParamSeedSeq = TestParamSeedSeq<true, true>; +using ConstParamNoSizeSeedSeq = TestParamSeedSeq<false, false>; +// SeedSequence constructibility traits for NonsecureURBGBase engines. +static_assert(std::is_constructible_v<absl::BitGen, absl::SeedSeq&>); +static_assert(std::is_constructible_v<absl::BitGen, absl::SeedSeq&&>); +static_assert(std::is_constructible_v<absl::BitGen, const absl::SeedSeq&>); +static_assert(std::is_constructible_v<absl::BitGen, const absl::SeedSeq&&>); +static_assert(std::is_constructible_v<absl::BitGen, std::seed_seq&>); +static_assert(std::is_constructible_v<absl::BitGen, std::seed_seq&&>); +static_assert(std::is_constructible_v<absl::BitGen, const std::seed_seq&>); +static_assert(std::is_constructible_v<absl::BitGen, const std::seed_seq&&>); +static_assert( + std::is_constructible_v<absl::BitGen, StatefulZeroSizeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, const StatefulZeroSizeSeedSeq&>); +static_assert( + std::is_constructible_v<absl::BitGen, const ConstGenerateZeroSizeSeedSeq&>); +static_assert(std::is_constructible_v<absl::BitGen, SeedSeq64&>); +static_assert(std::is_constructible_v<absl::BitGen, SeedSeq64&&>); +static_assert(!std::is_constructible_v<absl::BitGen, NoResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, const NoResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, SignedResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, NarrowResultTypeSeedSeq&>); +static_assert(!std::is_constructible_v<absl::BitGen, VoidResultTypeSeedSeq&>); +static_assert( + std::is_constructible_v<absl::BitGen, ConstGenerateNonConstSizeSeedSeq&>); +static_assert(!std::is_constructible_v< + absl::BitGen, const ConstGenerateNonConstSizeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, ConstGenerateNoSizeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, const ConstGenerateNoSizeSeedSeq&>); +static_assert( + std::is_constructible_v<absl::BitGen, + const ConstGenerateNonConstSizeWithParamSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::BitGen, const ConstParamNoSizeSeedSeq&>); + +static_assert( + std::is_constructible_v<absl::InsecureBitGen, const absl::SeedSeq&>); +static_assert( + std::is_constructible_v<absl::InsecureBitGen, const std::seed_seq&>); +static_assert(!std::is_constructible_v<absl::InsecureBitGen, + const StatefulZeroSizeSeedSeq&>); +static_assert(std::is_constructible_v<absl::InsecureBitGen, + const ConstGenerateZeroSizeSeedSeq&>); +static_assert(std::is_constructible_v<absl::InsecureBitGen, SeedSeq64&>); +static_assert( + !std::is_constructible_v<absl::InsecureBitGen, NoResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::InsecureBitGen, SignedResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::InsecureBitGen, NarrowResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<absl::InsecureBitGen, VoidResultTypeSeedSeq&>); +static_assert( + std::is_constructible_v<absl::InsecureBitGen, + const ConstGenerateNonConstSizeSeedSeq&>); +static_assert(std::is_constructible_v<absl::InsecureBitGen, + const ConstGenerateNoSizeSeedSeq&>); +static_assert( + std::is_constructible_v<absl::InsecureBitGen, + const ConstGenerateNonConstSizeWithParamSeedSeq&>); +static_assert(std::is_constructible_v<absl::InsecureBitGen, + const ConstParamNoSizeSeedSeq&>); + +static_assert(std::is_constructible_v<ExampleNonsecureURBG, SeedSeq64&>); +static_assert( + !std::is_constructible_v<ExampleNonsecureURBG, NoResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<ExampleNonsecureURBG, SignedResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<ExampleNonsecureURBG, NarrowResultTypeSeedSeq&>); +static_assert( + !std::is_constructible_v<ExampleNonsecureURBG, VoidResultTypeSeedSeq&>); +static_assert( + std::is_constructible_v<ExampleNonsecureURBG, + const ConstGenerateNonConstSizeSeedSeq&>); +static_assert(std::is_constructible_v<ExampleNonsecureURBG, + const ConstGenerateNoSizeSeedSeq&>); +} // namespace + +TEST(NonsecureURBGBase, ConstSaltedSeedSeqMatchesMutable) { + absl::SeedSeq mutable_lvalue(kTestSeedWords.begin(), kTestSeedWords.end()); + absl::SeedSeq mutable_rvalue(kTestSeedWords.begin(), kTestSeedWords.end()); + const absl::SeedSeq const_lvalue(kTestSeedWords.begin(), + kTestSeedWords.end()); + const absl::SeedSeq const_rvalue(kTestSeedWords.begin(), + kTestSeedWords.end()); + + absl::BitGen bitgen_mutable_lvalue(mutable_lvalue); + absl::BitGen bitgen_mutable_rvalue(std::move(mutable_rvalue)); + absl::BitGen bitgen_const_lvalue(const_lvalue); + absl::BitGen bitgen_const_rvalue(std::move(const_rvalue)); + const auto expected_bitgen = GenerateSequence(bitgen_mutable_lvalue); + EXPECT_THAT(GenerateSequence(bitgen_mutable_rvalue), + testing::Eq(expected_bitgen)); + EXPECT_THAT(GenerateSequence(bitgen_const_lvalue), + testing::Eq(expected_bitgen)); + EXPECT_THAT(GenerateSequence(bitgen_const_rvalue), + testing::Eq(expected_bitgen)); + + absl::InsecureBitGen insecure_mutable(mutable_lvalue); + absl::InsecureBitGen insecure_const(const_lvalue); + EXPECT_THAT(GenerateSequence(insecure_const), + testing::Eq(GenerateSequence(insecure_mutable))); +} + +TEST(NonsecureURBGBase, StatefulZeroSizeSeedSeqPreservesEntropy) { + StatefulZeroSizeSeedSeq seeder; + absl::BitGen gen1(seeder); + absl::BitGen gen2(seeder); + EXPECT_THAT(GenerateSequence(gen1), testing::Ne(GenerateSequence(gen2))); +} + +TEST(NonsecureURBGBase, ConstGenerateZeroSizeSeedSeqPreservesEntropy) { + const ConstGenerateZeroSizeSeedSeq seeder; + absl::BitGen gen1(seeder); + absl::BitGen gen2(seeder); + EXPECT_THAT(GenerateSequence(gen1), testing::Ne(GenerateSequence(gen2))); +} + +TEST(NonsecureURBGBase, SeedSequenceWith64BitResultTypeMatches32Bit) { + SeedSeq64 seq64; + SeedSeq32 seq32; + + absl::BitGen bitgen64(seq64); + absl::BitGen bitgen32(seq32); + EXPECT_THAT(GenerateSequence(bitgen64), + testing::Eq(GenerateSequence(bitgen32))); + + absl::InsecureBitGen insecure64(seq64); + absl::InsecureBitGen insecure32(seq32); + EXPECT_THAT(GenerateSequence(insecure64), + testing::Eq(GenerateSequence(insecure32))); + + ExampleNonsecureURBG example64(seq64); + ExampleNonsecureURBG example32(seq32); + EXPECT_THAT(GenerateSequence(example64), + testing::Eq(GenerateSequence(example32))); +} + +TEST(NonsecureURBGBase, BitGenAcceptsMutableNonConstSizeSeedSeq) { + ConstGenerateNonConstSizeSeedSeq mutable_non_const_size; + absl::BitGen bitgen_mutable(mutable_non_const_size); + EXPECT_THAT(GenerateSequence(bitgen_mutable), + testing::Ne(std::array<absl::BitGen::result_type, 16>{})); +} + +TEST(NonsecureURBGBase, InsecureAndExampleAcceptConstNonConstSizeSeedSeq) { + const ConstGenerateNonConstSizeSeedSeq const_non_const_size; + absl::InsecureBitGen insecure_non_const_size(const_non_const_size); + ExampleNonsecureURBG example_non_const_size(const_non_const_size); + EXPECT_THAT(GenerateSequence(insecure_non_const_size), + testing::Ne(std::array<absl::InsecureBitGen::result_type, 16>{})); + EXPECT_THAT(GenerateSequence(example_non_const_size), + testing::Ne(std::array<ExampleNonsecureURBG::result_type, 16>{})); +} + +TEST(NonsecureURBGBase, InsecureAndExampleAcceptNoSizeSeedSeq) { + const ConstGenerateNoSizeSeedSeq const_no_size; + absl::InsecureBitGen insecure_no_size(const_no_size); + ExampleNonsecureURBG example_no_size(const_no_size); + EXPECT_THAT(GenerateSequence(insecure_no_size), + testing::Ne(std::array<absl::InsecureBitGen::result_type, 16>{})); + EXPECT_THAT(GenerateSequence(example_no_size), + testing::Ne(std::array<ExampleNonsecureURBG::result_type, 16>{})); +} + +TEST(NonsecureURBGBase, InsecureBitGenAcceptsConstParamNoSizeSeedSeq) { + const ConstParamNoSizeSeedSeq const_param_no_size(kParamSeedWords.begin(), + kParamSeedWords.end()); + absl::InsecureBitGen insecure_param_no_size(const_param_no_size); + EXPECT_THAT(GenerateSequence(insecure_param_no_size), + testing::Ne(std::array<absl::InsecureBitGen::result_type, 16>{})); +} + +namespace { +// Known differential collision pairs for the C++ [rand.util.seedseq] mixing +// algorithm: each pair (A, B) of distinct s-word seeds produces bit-for-bit +// identical n-word outputs from raw std::seed_seq::generate(). +constexpr std::array<std::array<uint32_t, 2>, 4> kFourWayTwoWordCollision = {{ + {0x7ad2099du, 0x20261120u}, + {0x2a001490u, 0xcf541c13u}, + {0x592e1f83u, 0xfe822706u}, + {0x6f465452u, 0x149a5bd5u}, +}}; + +constexpr std::array<uint32_t, 8> kCollisionS8N4A = { + 0x00000001u, 0x00000002u, 0x00000003u, 0x00000004u, + 0x0000bf91u, 0x67c0a593u, 0x313389e7u, 0xee5c8e5cu}; +constexpr std::array<uint32_t, 8> kCollisionS8N4B = { + 0x00000001u, 0x00000002u, 0x00000003u, 0x00000004u, + 0x00011835u, 0xa5168553u, 0xcee80a7au, 0xee5ce700u}; +} // namespace + +TEST(NonsecureURBGBase, SaltedSeedingSeparatesRawSeedSeqCollisions) { + if (!absl::random_internal::GetSaltMaterial().has_value()) { + GTEST_SKIP() << "Salt material unavailable"; + } + + using Pcg32Result = absl::random_internal::pcg32_2018_engine::result_type; + std::set<std::array<absl::BitGen::result_type, 16>> bitgen_streams; + std::set<std::array<Pcg32Result, 16>> pcg32_streams; + for (const auto& seed : kFourWayTwoWordCollision) { + std::seed_seq std_seq(seed.begin(), seed.end()); + absl::BitGen bitgen(std_seq); + bitgen_streams.insert(GenerateSequence(bitgen)); + + absl::SeedSeq salted_seq(seed.begin(), seed.end()); + absl::random_internal::pcg32_2018_engine pcg32(salted_seq); + pcg32_streams.insert(GenerateSequence(pcg32)); + } + EXPECT_THAT(bitgen_streams, testing::SizeIs(4u)); + EXPECT_THAT(pcg32_streams, testing::SizeIs(4u)); + + // `s > n` XOF path on InsecureBitGen (4-word PCG64 seed from 8-word input). + absl::SeedSeq salted_a(kCollisionS8N4A.begin(), kCollisionS8N4A.end()); + absl::SeedSeq salted_b(kCollisionS8N4B.begin(), kCollisionS8N4B.end()); + absl::InsecureBitGen insecure_a(salted_a); + absl::InsecureBitGen insecure_b(salted_b); + EXPECT_THAT(GenerateSequence(insecure_a), + testing::Ne(GenerateSequence(insecure_b))); +} + +namespace { +struct RecordingSeedSeq { + using result_type = uint32_t; + size_t last_requested = 0; + size_t size() const { return 2u; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) { + last_requested = static_cast<size_t>(std::distance(begin, end)); + uint32_t v = 1u; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; +} // namespace + +TEST(NonsecureURBGBase, BitGenRequestsFull60WordRateFromCustomSeedSeq) { + RecordingSeedSeq custom_seq; + absl::BitGen bitgen(custom_seq); + EXPECT_EQ(custom_seq.last_requested, 60u); + EXPECT_NE(bitgen(), 0u); +}
diff --git a/absl/random/internal/pcg_engine.h b/absl/random/internal/pcg_engine.h index e785392..cdeba53 100644 --- a/absl/random/internal/pcg_engine.h +++ b/absl/random/internal/pcg_engine.h
@@ -19,6 +19,7 @@ #include <cstdint> #include <ios> #include <istream> +#include <iterator> #include <limits> #include <ostream> #include <type_traits> @@ -29,6 +30,7 @@ #include "absl/numeric/int128.h" #include "absl/random/internal/fastmath.h" #include "absl/random/internal/iostream_state_saver.h" +#include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN @@ -58,6 +60,13 @@ using mix_type = Mix; using state_type = typename Mix::state_type; + template <class SeedSequence> + using EnableIfSeedSeq = std::conjunction< + std::negation< + std::is_base_of<pcg_engine, absl::remove_cvref_t<SeedSequence>>>, + std::negation<std::is_convertible<SeedSequence, uint64_t>>, + HasSeedSeqGenerate<SeedSequence>>; + public: // C++11 URBG interface: using result_type = typename Mix::result_type; @@ -72,10 +81,10 @@ explicit pcg_engine(uint64_t seed_value = 0) { seed(seed_value); } - template <class SeedSequence, typename = typename std::enable_if_t< - !std::is_same_v<SeedSequence, pcg_engine>>> + template <class SeedSequence, + typename = std::enable_if_t<EnableIfSeedSeq<SeedSequence>::value>> explicit pcg_engine(SeedSequence&& seq) { - seed(seq); + reseed(seq); } pcg_engine(const pcg_engine&) = default; @@ -94,10 +103,9 @@ state_ = lcg(tmp + Params::increment()); } - template <class SeedSequence> - typename std::enable_if_t<!std::is_convertible_v<SeedSequence, uint64_t>, - void> - seed(SeedSequence&& seq) { + template <class SeedSequence, + typename = std::enable_if_t<EnableIfSeedSeq<SeedSequence>::value>> + void seed(SeedSequence&& seq) { reseed(seq); } @@ -111,7 +119,7 @@ template <class CharT, class Traits> friend typename std::enable_if_t<(sizeof(state_type) == 16), - std::basic_ostream<CharT, Traits>&> + std::basic_ostream<CharT, Traits>&> operator<<( std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references) const pcg_engine& engine) { @@ -127,7 +135,7 @@ template <class CharT, class Traits> friend typename std::enable_if_t<(sizeof(state_type) <= 8), - std::basic_ostream<CharT, Traits>&> + std::basic_ostream<CharT, Traits>&> operator<<( std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references) const pcg_engine& engine) { @@ -140,7 +148,7 @@ template <class CharT, class Traits> friend typename std::enable_if_t<(sizeof(state_type) == 16), - std::basic_istream<CharT, Traits>&> + std::basic_istream<CharT, Traits>&> operator>>( std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references) pcg_engine& engine) { // NOLINT(runtime/references) @@ -164,7 +172,7 @@ template <class CharT, class Traits> friend typename std::enable_if_t<(sizeof(state_type) <= 8), - std::basic_istream<CharT, Traits>&> + std::basic_istream<CharT, Traits>&> operator>>( std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references) pcg_engine& engine) { // NOLINT(runtime/references) @@ -213,15 +221,23 @@ template <class SeedSequence> void reseed(SeedSequence& seq) { - using sequence_result_type = typename SeedSequence::result_type; - constexpr size_t kBufferSize = - sizeof(state_type) / sizeof(sequence_result_type); - sequence_result_type buffer[kBufferSize]; + constexpr size_t kBufferSize = sizeof(state_type) / sizeof(uint32_t); + uint32_t buffer[kBufferSize]; + struct ScopedCleanse { + uint32_t* data; + ~ScopedCleanse() { + volatile unsigned char* p = + reinterpret_cast<volatile unsigned char*>(data); + for (size_t i = 0; i < kBufferSize * sizeof(uint32_t); ++i) { + p[i] = 0; + } + } + } cleaner{buffer}; seq.generate(std::begin(buffer), std::end(buffer)); // Convert the seed output to a single state value. state_type tmp = buffer[0]; for (size_t i = 1; i < kBufferSize; i++) { - tmp <<= (sizeof(sequence_result_type) * 8); + tmp <<= (sizeof(uint32_t) * 8); tmp |= buffer[i]; } state_ = lcg(tmp + params_type::increment());
diff --git a/absl/random/internal/pcg_engine_test.cc b/absl/random/internal/pcg_engine_test.cc index 938dc85..7ee3825 100644 --- a/absl/random/internal/pcg_engine_test.cc +++ b/absl/random/internal/pcg_engine_test.cc
@@ -238,6 +238,25 @@ "return type of operator== must be bool"); } +// Arbitrary non-default test seeds. +constexpr uint64_t kTestSeed = 123u; +constexpr uint64_t kConvertibleSeed = 7u; +constexpr uint32_t kTestSeedStart = 0xdeadbeefu; + +TYPED_TEST(PCGEngineTest, NonConstCopyConstruction) { + using E = TypeParam; + E v(kTestSeed); + v(); + + E copy_paren(v); + E copy_brace{v}; + EXPECT_EQ(copy_paren, v); + EXPECT_EQ(copy_brace, v); + const auto expected = v(); + EXPECT_EQ(copy_paren(), expected); + EXPECT_EQ(copy_brace(), expected); +} + TYPED_TEST(PCGEngineTest, RandenEngineSFINAETest) { using engine_type = TypeParam; using result_type = typename engine_type::result_type; @@ -407,6 +426,184 @@ FailsLeavingUnchanged()); } +template <typename Engine, typename Arg, typename = void> +struct HasSeedMethod : std::false_type {}; + +template <typename Engine, typename Arg> +struct HasSeedMethod< + Engine, Arg, + std::void_t<decltype(std::declval<Engine&>().seed(std::declval<Arg>()))>> + : std::true_type {}; + +template <typename ResultT, bool kConstGenerate = true, uint32_t kStart = 1> +struct TestSeedSeq { + using result_type = ResultT; + size_t size() const { return 4; } + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<C, int> = 0> + void generate(OutIt begin, OutIt end) const { + uint32_t v = kStart; + for (OutIt it = begin; it != end; ++it) *it = v++; + } + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<!C, int> = 0> + void generate(OutIt begin, OutIt end) { + uint32_t v = kStart; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; + +struct NoResultTypeSeedSeq { + size_t size() const { return 4; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + for (OutIt it = begin; it != end; ++it) *it = 1u; + } +}; + +struct ConvertibleSeedSeq { + using result_type = uint32_t; + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + for (OutIt it = begin; it != end; ++it) *it = 1u; + } + operator uint64_t() const { + return kConvertibleSeed; + } // NOLINT(google-explicit-constructor) +}; + +template <typename Engine> +struct DerivedPCG : Engine { + using Engine::Engine; + void generate(uint32_t*, uint32_t*) const {} +}; + +using NonConstGenerateSeedSeq = TestSeedSeq<uint32_t, /*kConstGenerate=*/false>; +using ConstGenerateSeedSeq = TestSeedSeq<uint32_t>; +using SeedSeq64 = + TestSeedSeq<uint64_t, /*kConstGenerate=*/false, kTestSeedStart>; +using SeedSeq32 = + TestSeedSeq<uint32_t, /*kConstGenerate=*/false, kTestSeedStart>; +using SignedResultSeedSeq = TestSeedSeq<int32_t>; +using NarrowResultSeedSeq = TestSeedSeq<uint16_t>; +using BoolResultSeedSeq = TestSeedSeq<bool>; +using ConstResultSeedSeq = TestSeedSeq<const uint32_t>; +using RefResultSeedSeq = TestSeedSeq<uint32_t&>; +using VoidResultSeedSeq = TestSeedSeq<void>; + +#ifdef ABSL_HAVE_EXCEPTIONS +constexpr int kExpectedException = 9; + +struct ThrowingPCGSeedSeq { + using result_type = uint32_t; + void generate(uint32_t* begin, uint32_t*) { + *begin = kTestSeedStart; + throw kExpectedException; + } +}; +#endif + +TYPED_TEST(PCGEngineTest, ConstSeedSequenceMatchesSeedMethod) { + using engine_type = TypeParam; + const ConstGenerateSeedSeq const_seq; + engine_type engine(const_seq); + engine_type reseeded; + reseeded.seed(const_seq); + EXPECT_EQ(engine, reseeded); +} + +TYPED_TEST(PCGEngineTest, CopyConstructsFromDerivedEngineWithGenerate) { + using engine_type = TypeParam; + DerivedPCG<engine_type> derived(kTestSeed); + derived(); + engine_type from_derived(derived); + EXPECT_EQ(from_derived, static_cast<const engine_type&>(derived)); +} + +TYPED_TEST(PCGEngineTest, ConvertibleSeedSequencePrefersIntegerSeedOverload) { + using engine_type = TypeParam; + ConvertibleSeedSeq conv_seq; + EXPECT_EQ(engine_type(conv_seq), engine_type(kConvertibleSeed)); +} + +template <typename engine_type> +constexpr bool CheckPCGSeedSequenceConstraints() { + static_assert(!std::is_constructible_v<engine_type, int*>); + static_assert(!std::is_constructible_v<engine_type, void*>); + static_assert(!HasSeedMethod<engine_type, int*>::value); + static_assert(!HasSeedMethod<engine_type, void*>::value); + + static_assert(std::is_constructible_v<engine_type, std::seed_seq&>); + static_assert(std::is_constructible_v<engine_type, std::seed_seq&&>); + static_assert(HasSeedMethod<engine_type, std::seed_seq&>::value); + static_assert(HasSeedMethod<engine_type, std::seed_seq&&>::value); + + // Test non-const generate() rejection with a dedicated type because MSVC STL + // marks std::seed_seq::generate() const while libc++/libstdc++ do not. + static_assert(std::is_constructible_v<engine_type, NonConstGenerateSeedSeq&>); + static_assert( + std::is_constructible_v<engine_type, NonConstGenerateSeedSeq&&>); + static_assert( + !std::is_constructible_v<engine_type, const NonConstGenerateSeedSeq&>); + static_assert( + !std::is_constructible_v<engine_type, const NonConstGenerateSeedSeq&&>); + static_assert(HasSeedMethod<engine_type, NonConstGenerateSeedSeq&>::value); + static_assert( + !HasSeedMethod<engine_type, const NonConstGenerateSeedSeq&>::value); + + static_assert( + std::is_constructible_v<engine_type, const ConstGenerateSeedSeq&>); + static_assert(HasSeedMethod<engine_type, const ConstGenerateSeedSeq&>::value); + + // Reject missing or invalid [rand.req.seedseq] result_type across ctor and + // seed(). + static_assert(!std::is_constructible_v<engine_type, NoResultTypeSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, NoResultTypeSeedSeq&>::value); + static_assert(!std::is_constructible_v<engine_type, SignedResultSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, SignedResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<engine_type, NarrowResultSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, NarrowResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<engine_type, BoolResultSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, BoolResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<engine_type, ConstResultSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, ConstResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<engine_type, RefResultSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, RefResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<engine_type, VoidResultSeedSeq&>); + static_assert(!HasSeedMethod<engine_type, VoidResultSeedSeq&>::value); + return true; +} + +static_assert(CheckPCGSeedSequenceConstraints<pcg64_2018_engine>()); +static_assert(CheckPCGSeedSequenceConstraints<pcg32_2018_engine>()); + +#ifdef ABSL_HAVE_EXCEPTIONS +TYPED_TEST(PCGEngineTest, ThrowingSeedSequencePreservesState) { + using engine_type = TypeParam; + const ConstGenerateSeedSeq const_seq; + engine_type engine(const_seq); + const engine_type snapshot = engine; + ThrowingPCGSeedSeq throwing_seq; + EXPECT_THROW(engine.seed(throwing_seq), int); + EXPECT_EQ(engine, snapshot); +} +#endif + +TYPED_TEST(PCGEngineTest, SeedSequenceWith64BitResultTypeMatches32Bit) { + using engine_type = TypeParam; + SeedSeq64 seq64; + SeedSeq32 seq32; + engine_type e64(seq64); + engine_type e32(seq32); + EXPECT_EQ(e64, e32); + EXPECT_EQ(e64(), e32()); + + e64.seed(seq64); + e32.seed(seq32); + EXPECT_EQ(e64, e32); + EXPECT_EQ(e64(), e32()); +} + // ------------------------------------------------------------------ // Stability tests for pcg64_2018_engine // ------------------------------------------------------------------
diff --git a/absl/random/internal/randen_engine.h b/absl/random/internal/randen_engine.h index 62ce801..7099fd1 100644 --- a/absl/random/internal/randen_engine.h +++ b/absl/random/internal/randen_engine.h
@@ -17,6 +17,7 @@ #include <algorithm> #include <cinttypes> +#include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> @@ -33,6 +34,7 @@ #include "absl/meta/type_traits.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/randen.h" +#include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN @@ -49,6 +51,13 @@ // generator, faster in some benchmarks than std::mt19937_64 and pcg64_c32. template <typename T> class alignas(8) randen_engine { + template <class SeedSequence> + using EnableIfSeedSeq = std::conjunction< + std::negation< + std::is_base_of<randen_engine, absl::remove_cvref_t<SeedSequence>>>, + std::negation<std::is_convertible<SeedSequence, T>>, + HasSeedSeqGenerate<SeedSequence>, HasSeedSeqSize<SeedSequence>>; + public: // C++11 URBG interface: using result_type = T; @@ -68,10 +77,9 @@ explicit randen_engine(result_type seed_value) { seed(seed_value); } template <class SeedSequence, - typename = typename std::enable_if_t< - !std::is_same_v<SeedSequence, randen_engine>>> + typename = std::enable_if_t<EnableIfSeedSeq<SeedSequence>::value>> explicit randen_engine(SeedSequence&& seq) { - seed(seq); + AbsorbSeed</*kMixExistingState=*/false>(seq); } // alignment requirements dictate custom copy and move constructors. @@ -115,12 +123,11 @@ return little_endian::ToHost(begin[next_++]); } - template <class SeedSequence> - typename std::enable_if_t<!std::is_convertible_v<SeedSequence, result_type>> - seed(SeedSequence&& seq) { - // Zeroes the state. - seed(); - reseed(seq); + template <class SeedSequence, + typename = std::enable_if_t<EnableIfSeedSeq<SeedSequence>::value>> + void seed(SeedSequence&& seq) { + // Zeroes the state and absorbs seed material. + AbsorbSeed</*kMixExistingState=*/false>(seq); } void seed(result_type seed_value = result_type{0}) { @@ -136,57 +143,10 @@ // Inserts entropy into (part of) the state. Calling this periodically with // sufficient entropy ensures prediction resistance (attackers cannot predict // future outputs even if state is compromised). - template <class SeedSequence> + template <class SeedSequence, + typename = std::enable_if_t<EnableIfSeedSeq<SeedSequence&>::value>> void reseed(SeedSequence& seq) { - using sequence_result_type = typename SeedSequence::result_type; - static_assert(sizeof(sequence_result_type) == 4, - "SeedSequence::result_type must be 32-bit"); - constexpr size_t kBufferSize = - Randen::kSeedBytes / sizeof(sequence_result_type); - alignas(16) sequence_result_type buffer[kBufferSize]; - - // Randen::Absorb XORs the seed into state, which is then mixed by a call - // to Randen::Generate. Seeding with only the provided entropy is preferred - // to using an arbitrary generate() call, so use [rand.req.seed_seq] - // size as a proxy for the number of entropy units that can be generated - // without relying on seed sequence mixing... - const size_t entropy_size = seq.size(); - if (entropy_size < kBufferSize) { - // ... and only request that many values, or 256-bits, when unspecified. - const size_t requested_entropy = (entropy_size == 0) ? 8u : entropy_size; - std::fill(buffer + requested_entropy, buffer + kBufferSize, 0); - seq.generate(buffer, buffer + requested_entropy); - // The Randen paper suggests preferentially initializing even-numbered - // 128-bit vectors of the randen state (there are 16 such vectors). - // The seed data is merged into the state offset by 128-bits, which - // implies preferring seed bytes [16..31, ..., 208..223]. Since the - // buffer is 32-bit values, we swap the corresponding buffer positions in - // 128-bit chunks. - size_t dst = kBufferSize; - while (dst > 7) { - // leave the odd bucket as-is. - dst -= 4; - size_t src = dst >> 1; - // swap 128-bits into the even bucket - std::swap(buffer[--dst], buffer[--src]); - std::swap(buffer[--dst], buffer[--src]); - std::swap(buffer[--dst], buffer[--src]); - std::swap(buffer[--dst], buffer[--src]); - } - } else { - seq.generate(buffer, buffer + kBufferSize); - } -#ifdef ABSL_IS_BIG_ENDIAN - // Randen expects the seed buffer to be in Little Endian; reverse it on - // Big Endian platforms. - for (sequence_result_type& e : buffer) { - e = absl::little_endian::FromHost(e); - } -#endif - impl_.Absorb(buffer, state()); - - // Generate will be called when operator() is called - next_ = kStateSizeT; + AbsorbSeed</*kMixExistingState=*/true>(seq); } void discard(uint64_t count) { @@ -241,6 +201,8 @@ auto saver = random_internal::make_istream_state_saver(is); result_type state[kStateSizeT]; for (auto& elem : state) { + // It is not possible to read uint8_t from a stream, so it is necessary to + // read a wider type and then cast it to uint8_t. result_type value = 0; if (!random_internal::read_integral(is, value)) { return is; @@ -266,6 +228,97 @@ static constexpr size_t kCapacityT = Randen::kCapacityBytes / sizeof(result_type); + template <bool kMixExistingState> + void PrepareStateForSeed(result_type* begin) { + if constexpr (kMixExistingState) { + // Permute the existing sponge state before absorbing new seed material so + // repeated reseed(s) calls cannot XOR-cancel and mid-buffer reseeds do + // not XOR directly onto already-emitted rate words. Also fold a nonzero + // domain tag and the current byte offset into the inner capacity (which + // Absorb() leaves untouched) to separate reseed() from ordinary block + // refills and distinguish reseeds at different mid-buffer positions. + static_assert(Randen::kCapacityBytes >= 4, + "Randen capacity must hold domain separator bytes"); + const size_t byte_offset = next_ * sizeof(result_type); + impl_.Generate(begin); + auto* capacity = reinterpret_cast<unsigned char*>(begin); + capacity[0] ^= 0x01; + capacity[1] ^= static_cast<unsigned char>(byte_offset & 0xff); + capacity[2] ^= static_cast<unsigned char>((byte_offset >> 8) & 0xff); + } else { + seed(); + } + } + + template <bool kMixExistingState, class SeedSequence> + void AbsorbSeed(SeedSequence& seq) { + constexpr size_t kBufferSize = Randen::kSeedBytes / sizeof(uint32_t); + alignas(16) uint32_t buffer[kBufferSize]; + + struct Cleanse { + volatile uint32_t* ptr; + ~Cleanse() { + for (size_t i = 0; i < kBufferSize; ++i) { + ptr[i] = 0; + } + } + } cleanse_obj(buffer); + + if constexpr (IsSaltedSeedSeq<absl::remove_cvref_t<SeedSequence>>::value) { + // Salted seed sequences fill the full 60-word rate so short seeds do not + // leave 14 zero lanes or suffer narrow `[rand.util.seedseq]` truncation + // (even if salt is unavailable, n = 60 is injective for 1 <= s <= 33). + seq.generate(buffer, buffer + kBufferSize); + } else { + // Randen::Absorb XORs the seed into state, which is then mixed by a call + // to Randen::Generate. Seeding with only the provided entropy is + // preferred to using an arbitrary generate() call, so use + // [rand.req.seed_seq] size as a proxy for the number of entropy units + // that can be generated without relying on seed sequence mixing... + const size_t entropy_size = seq.size(); + if (entropy_size < kBufferSize) { + // ... and only request that many values, or 256-bits, when + // unspecified. + const size_t requested_entropy = + (entropy_size == 0) ? 8u : entropy_size; + std::fill(buffer + requested_entropy, buffer + kBufferSize, 0); + seq.generate(buffer, buffer + requested_entropy); + // The Randen paper suggests preferentially initializing even-numbered + // 128-bit vectors of the randen state (there are 16 such vectors). + // The seed data is merged into the state offset by 128-bits, which + // implies preferring seed bytes [16..31, ..., 208..223]. Since the + // buffer is 32-bit values, we swap the corresponding buffer positions + // in 128-bit chunks. + size_t dst = kBufferSize; + while (dst > 7) { + // leave the odd bucket as-is. + dst -= 4; + size_t src = dst >> 1; + // swap 128-bits into the even bucket + std::swap(buffer[--dst], buffer[--src]); + std::swap(buffer[--dst], buffer[--src]); + std::swap(buffer[--dst], buffer[--src]); + std::swap(buffer[--dst], buffer[--src]); + } + } else { + seq.generate(buffer, buffer + kBufferSize); + } + } +#ifdef ABSL_IS_BIG_ENDIAN + // Randen expects the seed buffer to be in Little Endian; reverse it on + // Big Endian platforms. + for (uint32_t& e : buffer) { + e = absl::little_endian::FromHost(e); + } +#endif + auto* begin = state(); + PrepareStateForSeed<kMixExistingState>(begin); + impl_.Absorb(buffer, begin); + + // Generate will be called when operator() is called. + next_ = kStateSizeT; + } + // Returns the state array pointer, which is aligned to 16 bytes. // The first kCapacityT are the `inner' sponge; the remainder are available. result_type* state() {
diff --git a/absl/random/internal/randen_engine_test.cc b/absl/random/internal/randen_engine_test.cc index d18a28d..a484e9f 100644 --- a/absl/random/internal/randen_engine_test.cc +++ b/absl/random/internal/randen_engine_test.cc
@@ -15,10 +15,12 @@ #include "absl/random/internal/randen_engine.h" #include <algorithm> +#include <array> #include <bitset> #include <cmath> #include <cstddef> #include <cstdint> +#include <functional> #include <ios> #include <ostream> #include <random> @@ -30,8 +32,11 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/base/config.h" #include "absl/log/log.h" #include "absl/random/internal/explicit_seed_seq.h" +#include "absl/random/internal/randen.h" +#include "absl/random/internal/traits.h" #include "absl/time/clock.h" #define UPDATE_GOLDEN 0 @@ -283,6 +288,27 @@ EXPECT_NE(move_constructed(), source()); // NOLINT(bugprone-use-after-move) } +// Arbitrary nothing-up-my-sleeve test seeds. +constexpr std::array<uint32_t, 3> kTestSeed3 = {12, 34, 56}; +constexpr std::array<uint32_t, 4> kTestSeed4 = {12, 34, 56, 78}; +constexpr uint32_t kTestSeedStart = 0xdeadbeefu; +constexpr uint64_t kConvertibleSeed = 7u; + +TYPED_TEST(RandenEngineTypedTest, NonConstCopyConstruction) { + using E = absl::random_internal::randen_engine<TypeParam>; + ExplicitSeedSeq seed_sequence(kTestSeed3.begin(), kTestSeed3.end()); + E v(seed_sequence); + v.discard(5); + + E copy_paren(v); + E copy_brace{v}; + EXPECT_EQ(copy_paren, v); + EXPECT_EQ(copy_brace, v); + const auto expected = v(); + EXPECT_EQ(copy_paren(), expected); + EXPECT_EQ(copy_brace(), expected); +} + TYPED_TEST(RandenEngineTypedTest, RandenEngineSFINAETest) { using randen = typename absl::random_internal::randen_engine<TypeParam>; using result_type = typename randen::result_type; @@ -480,6 +506,447 @@ FailsLeavingUnchanged()); } +template <typename Engine, typename Arg, typename = void> +struct HasSeedMethod : std::false_type {}; + +template <typename Engine, typename Arg> +struct HasSeedMethod< + Engine, Arg, + std::void_t<decltype(std::declval<Engine&>().seed(std::declval<Arg>()))>> + : std::true_type {}; + +template <typename Engine, typename Arg, typename = void> +struct HasReseedMethod : std::false_type {}; + +template <typename Engine, typename Arg> +struct HasReseedMethod< + Engine, Arg, + std::void_t<decltype(std::declval<Engine&>().reseed(std::declval<Arg>()))>> + : std::true_type {}; + +struct NoResultTypeSeedSeq { + size_t size() const { return 4; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + for (OutIt it = begin; it != end; ++it) *it = 1u; + } +}; + +struct ConvertibleSeedSeq { + using result_type = uint32_t; + size_t size() const { return 4; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + for (OutIt it = begin; it != end; ++it) *it = 1u; + } + operator uint64_t() const { + return kConvertibleSeed; + } // NOLINT(google-explicit-constructor) +}; + +template <typename Engine> +struct DerivedRanden : Engine { + using Engine::Engine; + size_t size() const { return 4; } + void generate(uint32_t*, uint32_t*) const {} +}; + +template <typename ResultT, bool kConstGenerate = true, uint32_t kStart = 1, + bool kConstSize = true, bool kHasSize = true> +struct TestSeedSeq { + using result_type = ResultT; + size_t count = 4; + + explicit TestSeedSeq(size_t n = 4) : count(n) {} + + template <bool H = kHasSize, bool C = kConstSize, + std::enable_if_t<H && C, int> = 0> + size_t size() const { + return count; + } + template <bool H = kHasSize, bool C = kConstSize, + std::enable_if_t<H && !C, int> = 0> + size_t size() { + return count; + } + + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<C, int> = 0> + void generate(OutIt begin, OutIt end) const { + uint32_t v = kStart; + for (OutIt it = begin; it != end; ++it) *it = v++; + } + template <typename OutIt, bool C = kConstGenerate, + std::enable_if_t<!C, int> = 0> + void generate(OutIt begin, OutIt end) { + uint32_t v = kStart; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; + +using NonConstGenerateSeedSeq = TestSeedSeq<uint32_t, /*kConstGenerate=*/false>; +using ConstGenerateSeedSeq = TestSeedSeq<uint32_t>; +using ConstGenerateNonConstSizeSeedSeq = + TestSeedSeq<uint32_t, /*kConstGenerate=*/true, 1, /*kConstSize=*/false>; +using NoSizeSeedSeq = + TestSeedSeq<uint32_t, /*kConstGenerate=*/true, 1, /*kConstSize=*/true, + /*kHasSize=*/false>; +using SeedSeq64 = + TestSeedSeq<uint64_t, /*kConstGenerate=*/false, kTestSeedStart>; +using SeedSeq32 = + TestSeedSeq<uint32_t, /*kConstGenerate=*/false, kTestSeedStart>; +using SignedResultSeedSeq = TestSeedSeq<int32_t>; +using NarrowResultSeedSeq = TestSeedSeq<uint16_t>; +using BoolResultSeedSeq = TestSeedSeq<bool>; +using ConstResultSeedSeq = TestSeedSeq<const uint32_t>; +using RefResultSeedSeq = TestSeedSeq<uint32_t&>; +using VoidResultSeedSeq = TestSeedSeq<void>; + +#ifdef ABSL_HAVE_EXCEPTIONS +constexpr uint32_t kThrowingWriteSentinel = 0x12345678u; +constexpr int kThrowingSeedException = 42; + +struct ThrowingRandenSeedSeq { + using result_type = uint32_t; + size_t size() const { return 8; } + void generate(uint32_t* begin, uint32_t*) { + *begin = kThrowingWriteSentinel; + throw kThrowingSeedException; + } +}; +#endif + +struct SaltedTagRecordingSeedSeq { + using result_type = uint32_t; + mutable size_t calls = 0; + mutable size_t last_words_requested = 0; + size_t size() const { return 2u; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + ++calls; + last_words_requested = static_cast<size_t>(std::distance(begin, end)); + uint32_t v = 1u; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; + +struct UnsaltedRecordingSeedSeq { + using result_type = uint32_t; + mutable size_t calls = 0; + mutable size_t last_words_requested = 0; + size_t size() const { return 2u; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) const { + ++calls; + last_words_requested = static_cast<size_t>(std::distance(begin, end)); + uint32_t v = 1u; + for (OutIt it = begin; it != end; ++it) *it = v++; + } +}; + +} // namespace + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace random_internal { +template <> +struct IsSaltedSeedSeq<SaltedTagRecordingSeedSeq> : std::true_type {}; +} // namespace random_internal +ABSL_NAMESPACE_END +} // namespace absl + +namespace { + +TYPED_TEST(RandenEngineTypedTest, ConstSeedSequenceMatchesSeedAndReseed) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + + const ConstGenerateSeedSeq const_seq; + ConstGenerateSeedSeq mutable_seq; + randen engine(const_seq); + randen seeded; + seeded.seed(const_seq); + EXPECT_EQ(engine, seeded); + + engine.reseed(const_seq); + seeded.reseed(mutable_seq); + EXPECT_EQ(engine, seeded); +} + +TYPED_TEST(RandenEngineTypedTest, + NonConstSizeSeedSequenceWorksForSeedAndReseed) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + + ConstGenerateNonConstSizeSeedSeq seq; + randen engine(seq); + randen seeded; + seeded.seed(seq); + EXPECT_EQ(engine, seeded); + + ConstGenerateNonConstSizeSeedSeq seq2; + engine.reseed(seq); + seeded.reseed(seq2); + EXPECT_EQ(engine, seeded); +} + +template <typename T> +constexpr bool CheckRandenSeedSequenceConstraints() { + using randen = absl::random_internal::randen_engine<T>; + + static_assert(!std::is_constructible_v<randen, int*>); + static_assert(!std::is_constructible_v<randen, void*>); + static_assert(!HasSeedMethod<randen, int*>::value); + static_assert(!HasSeedMethod<randen, void*>::value); + static_assert(!HasReseedMethod<randen, int&>::value); + static_assert(!HasReseedMethod<randen, T&>::value); + static_assert(!HasReseedMethod<randen, int*&>::value); + static_assert(!HasReseedMethod<randen, void*&>::value); + static_assert(!HasReseedMethod<randen, randen&>::value); + static_assert(!HasReseedMethod<randen, DerivedRanden<randen>&>::value); + static_assert(!HasReseedMethod<randen, ConvertibleSeedSeq&>::value); + + static_assert(std::is_constructible_v<randen, DerivedRanden<randen>&>); + static_assert(std::is_constructible_v<randen, std::seed_seq&>); + static_assert(std::is_constructible_v<randen, std::seed_seq&&>); + static_assert(HasSeedMethod<randen, std::seed_seq&>::value); + static_assert(HasSeedMethod<randen, std::seed_seq&&>::value); + static_assert(HasReseedMethod<randen, std::seed_seq&>::value); + static_assert(HasReseedMethod<randen, SeedSeq64&>::value); + + // Test non-const generate() rejection with a dedicated type because MSVC STL + // marks std::seed_seq::generate() const while libc++/libstdc++ do not. + static_assert(std::is_constructible_v<randen, NonConstGenerateSeedSeq&>); + static_assert(std::is_constructible_v<randen, NonConstGenerateSeedSeq&&>); + static_assert( + !std::is_constructible_v<randen, const NonConstGenerateSeedSeq&>); + static_assert( + !std::is_constructible_v<randen, const NonConstGenerateSeedSeq&&>); + static_assert(HasSeedMethod<randen, NonConstGenerateSeedSeq&>::value); + static_assert(!HasSeedMethod<randen, const NonConstGenerateSeedSeq&>::value); + static_assert(HasReseedMethod<randen, NonConstGenerateSeedSeq&>::value); + static_assert( + !HasReseedMethod<randen, const NonConstGenerateSeedSeq&>::value); + + static_assert(std::is_constructible_v<randen, const ConstGenerateSeedSeq&>); + static_assert(HasSeedMethod<randen, const ConstGenerateSeedSeq&>::value); + static_assert(HasReseedMethod<randen, const ConstGenerateSeedSeq&>::value); + + static_assert( + std::is_constructible_v<randen, ConstGenerateNonConstSizeSeedSeq&>); + static_assert( + std::is_constructible_v<randen, ConstGenerateNonConstSizeSeedSeq&&>); + static_assert( + !std::is_constructible_v<randen, + const ConstGenerateNonConstSizeSeedSeq&>); + static_assert( + !std::is_constructible_v<randen, + const ConstGenerateNonConstSizeSeedSeq&&>); + static_assert( + HasSeedMethod<randen, ConstGenerateNonConstSizeSeedSeq&>::value); + static_assert( + !HasSeedMethod<randen, const ConstGenerateNonConstSizeSeedSeq&>::value); + static_assert( + HasReseedMethod<randen, ConstGenerateNonConstSizeSeedSeq&>::value); + static_assert( + !HasReseedMethod<randen, const ConstGenerateNonConstSizeSeedSeq&>::value); + + static_assert(!std::is_constructible_v<randen, NoSizeSeedSeq&>); + static_assert(!std::is_constructible_v<randen, const NoSizeSeedSeq&>); + static_assert(!HasSeedMethod<randen, NoSizeSeedSeq&>::value); + static_assert(!HasSeedMethod<randen, const NoSizeSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, NoSizeSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, const NoSizeSeedSeq&>::value); + + // Reject missing or invalid [rand.req.seedseq] result_type across ctor, + // seed(), and reseed(). + static_assert(!std::is_constructible_v<randen, NoResultTypeSeedSeq&>); + static_assert(!HasSeedMethod<randen, NoResultTypeSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, NoResultTypeSeedSeq&>::value); + static_assert(!std::is_constructible_v<randen, SignedResultSeedSeq&>); + static_assert(!HasSeedMethod<randen, SignedResultSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, SignedResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<randen, NarrowResultSeedSeq&>); + static_assert(!HasSeedMethod<randen, NarrowResultSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, NarrowResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<randen, BoolResultSeedSeq&>); + static_assert(!HasSeedMethod<randen, BoolResultSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, BoolResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<randen, ConstResultSeedSeq&>); + static_assert(!HasSeedMethod<randen, ConstResultSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, ConstResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<randen, RefResultSeedSeq&>); + static_assert(!HasSeedMethod<randen, RefResultSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, RefResultSeedSeq&>::value); + static_assert(!std::is_constructible_v<randen, VoidResultSeedSeq&>); + static_assert(!HasSeedMethod<randen, VoidResultSeedSeq&>::value); + static_assert(!HasReseedMethod<randen, VoidResultSeedSeq&>::value); + return true; +} + +static_assert(CheckRandenSeedSequenceConstraints<uint8_t>()); +static_assert(CheckRandenSeedSequenceConstraints<uint16_t>()); +static_assert(CheckRandenSeedSequenceConstraints<uint32_t>()); +static_assert(CheckRandenSeedSequenceConstraints<uint64_t>()); + +TYPED_TEST(RandenEngineTypedTest, + SeedFollowedByReseedWithSameSequenceDoesNotCancel) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + ExplicitSeedSeq seq(kTestSeed4.begin(), kTestSeed4.end()); + + randen default_engine; + randen seeded_only(seq); + randen seed_then_reseed(seq); + seed_then_reseed.reseed(seq); + EXPECT_NE(seed_then_reseed, default_engine); + EXPECT_NE(seed_then_reseed, seeded_only); +} + +TYPED_TEST(RandenEngineTypedTest, + BackToBackReseedWithSameSequenceDoesNotCancel) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + constexpr size_t kRateT = (absl::random_internal::Randen::kStateBytes - + absl::random_internal::Randen::kCapacityBytes) / + sizeof(TypeParam); + ExplicitSeedSeq seq(kTestSeed4.begin(), kTestSeed4.end()); + + // Trigger an initial Generate() and align base to the block boundary so + // operator!= checks sponge state rather than differing only in buffer offset. + randen base(seq); + base(); + base.discard(kRateT - 1); + randen once = base; + once.reseed(seq); + randen twice = base; + twice.reseed(seq); + twice.reseed(seq); + EXPECT_NE(twice, base); + EXPECT_NE(twice, once); +} + +TYPED_TEST(RandenEngineTypedTest, FullRateReseedWithSameSequenceDoesNotCancel) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + randen default_engine; + SeedSeq32 large_seq(64); + randen large_once(large_seq); + large_once.reseed(large_seq); + EXPECT_NE(large_once, default_engine); + EXPECT_NE(large_once, randen(large_seq)); +} + +TYPED_TEST(RandenEngineTypedTest, ZeroReseedDivergesFromBlockAdvance) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + constexpr size_t kRateT = (absl::random_internal::Randen::kStateBytes - + absl::random_internal::Randen::kCapacityBytes) / + sizeof(TypeParam); + ExplicitSeedSeq seq(kTestSeed4.begin(), kTestSeed4.end()); + ExplicitSeedSeq zero_seq; + + // Force the initial Generate() before forking so `advanced` reaches the block + // boundary without a second permutation (catching unpermuted zero reseed), + // while `next_block` advances one more permutation (catching missing capacity + // domain separation). + randen advanced(seq); + advanced(); + randen zero_reseeded = advanced; + advanced.discard(kRateT - 1); + randen next_block = advanced; + next_block.discard(kRateT); + zero_reseeded.reseed(zero_seq); + EXPECT_NE(zero_reseeded, advanced); + EXPECT_NE(zero_reseeded, next_block); +} + +TYPED_TEST(RandenEngineTypedTest, ReseedAtDistinctMidBufferPositionsDiverges) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + ExplicitSeedSeq seq(kTestSeed4.begin(), kTestSeed4.end()); + + randen mid_a(seq); + randen mid_b(seq); + mid_a.discard(1); + mid_b.discard(5); + ASSERT_NE(mid_a, mid_b); + mid_a.reseed(seq); + mid_b.reseed(seq); + EXPECT_NE(mid_a, mid_b); +} + +#ifdef ABSL_HAVE_EXCEPTIONS +TYPED_TEST(RandenEngineTypedTest, ThrowingSeedAndReseedPreserveState) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + ExplicitSeedSeq seq(kTestSeed4.begin(), kTestSeed4.end()); + ThrowingRandenSeedSeq throwing_seq; + + randen survivor(seq); + survivor.discard(2); + const randen snapshot = survivor; + EXPECT_THROW(survivor.seed(throwing_seq), int); + EXPECT_EQ(survivor, snapshot); + EXPECT_THROW(survivor.reseed(throwing_seq), int); + EXPECT_EQ(survivor, snapshot); +} +#endif + +TYPED_TEST(RandenEngineTypedTest, + SaltedSeedSeqDrawsFullRateWhileUnsaltedPreservesSizeDraw) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + + SaltedTagRecordingSeedSeq salted_seq; + UnsaltedRecordingSeedSeq unsalted_seq; + + randen from_salted(salted_seq); + EXPECT_EQ(salted_seq.calls, 1u); + EXPECT_EQ(salted_seq.last_words_requested, 60u); + + randen from_unsalted(unsalted_seq); + EXPECT_EQ(unsalted_seq.calls, 1u); + EXPECT_EQ(unsalted_seq.last_words_requested, 2u); + + from_salted.reseed(salted_seq); + EXPECT_EQ(salted_seq.calls, 2u); + EXPECT_EQ(salted_seq.last_words_requested, 60u); + + from_unsalted.reseed(unsalted_seq); + EXPECT_EQ(unsalted_seq.calls, 2u); + EXPECT_EQ(unsalted_seq.last_words_requested, 2u); +} + +TYPED_TEST(RandenEngineTypedTest, + SeedSequenceWith64BitResultTypeSubRateMatches32Bit) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + static_assert(std::is_constructible_v<randen, SeedSeq64&>, + "randen_engine must be constructible from SeedSeq64&"); + static_assert(HasSeedMethod<randen, SeedSeq64&>::value, + "randen_engine::seed must accept SeedSeq64&"); + + SeedSeq64 seq64(4); + SeedSeq32 seq32(4); + randen e64(seq64); + randen e32(seq32); + EXPECT_EQ(e64, e32); + EXPECT_EQ(e64(), e32()); + + e64.seed(seq64); + e32.seed(seq32); + EXPECT_EQ(e64, e32); + EXPECT_EQ(e64(), e32()); +} + +TYPED_TEST(RandenEngineTypedTest, + SeedSequenceWith64BitResultTypeFullRateMatches32Bit) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + + SeedSeq64 seq64(64); + SeedSeq32 seq32(64); + randen e64(seq64); + randen e32(seq32); + EXPECT_EQ(e64, e32); + EXPECT_EQ(e64(), e32()); + + e64.seed(seq64); + e32.seed(seq32); + EXPECT_EQ(e64, e32); + EXPECT_EQ(e64(), e32()); +} + TEST(RandenTest, VerifyGoldenRanden64Default) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0xc3c14f134e433977, 0xdda9f47cd90410ee, 0x887bf3087fd8ca10,
diff --git a/absl/random/internal/salted_seed_seq.h b/absl/random/internal/salted_seed_seq.h index 858a90f..2c840d5 100644 --- a/absl/random/internal/salted_seed_seq.h +++ b/absl/random/internal/salted_seed_seq.h
@@ -15,12 +15,15 @@ #ifndef ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_ #define ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_ +#include <algorithm> +#include <cstddef> #include <cstdint> #include <cstdlib> #include <initializer_list> #include <iterator> #include <memory> #include <optional> +#include <random> #include <type_traits> #include <utility> #include <vector> @@ -29,6 +32,7 @@ #include "absl/container/inlined_vector.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/seed_material.h" +#include "absl/random/internal/traits.h" #include "absl/types/optional.h" #include "absl/types/span.h" @@ -36,6 +40,20 @@ ABSL_NAMESPACE_BEGIN namespace random_internal { +template <typename Iterator, bool IsPointer = std::is_pointer_v<Iterator>, + typename = void> +struct IsIntegralIterator : std::false_type {}; + +template <typename Iterator> +struct IsIntegralIterator<Iterator, true, void> + : std::is_integral<std::remove_pointer_t<Iterator>> {}; + +template <typename Iterator> +struct IsIntegralIterator< + Iterator, false, + std::void_t<typename std::iterator_traits<Iterator>::value_type>> + : std::is_integral<typename std::iterator_traits<Iterator>::value_type> {}; + // This class conforms to the C++ Standard "Seed Sequence" concept // [rand.req.seedseq]. // @@ -46,19 +64,45 @@ // not modified. template <typename SSeq> class SaltedSeedSeq { + static_assert(!std::is_rvalue_reference_v<SSeq>, + "SaltedSeedSeq cannot be instantiated with an rvalue " + "reference; use an owning type or an lvalue reference."); + using raw_sequence_type = std::remove_reference_t<SSeq>; + public: using inner_sequence_type = SSeq; - using result_type = typename SSeq::result_type; + using result_type = typename raw_sequence_type::result_type; - SaltedSeedSeq() : seq_(std::make_unique<SSeq>()) {} + template <typename U = SSeq, + typename = std::enable_if_t<std::conjunction_v< + std::negation<std::is_reference<U>>, + std::is_default_constructible<std::remove_reference_t<U>>>>> + SaltedSeedSeq() : seq_(std::make_unique<raw_sequence_type>()) {} - template <typename Iterator> + template < + typename Iterator, typename U = SSeq, + typename = std::enable_if_t<std::conjunction_v< + std::negation<std::is_reference<U>>, IsIntegralIterator<Iterator>, + std::is_constructible<std::remove_reference_t<U>, Iterator, + Iterator>>>> SaltedSeedSeq(Iterator begin, Iterator end) - : seq_(std::make_unique<SSeq>(begin, end)) {} + : seq_(std::make_unique<raw_sequence_type>(begin, end)) {} - template <typename T> + template <typename T, typename U = SSeq, + typename = std::enable_if_t<std::conjunction_v< + std::negation<std::is_reference<U>>, std::is_integral<T>, + std::is_constructible<std::remove_reference_t<U>, + std::initializer_list<T>>>>> SaltedSeedSeq(std::initializer_list<T> il) - : SaltedSeedSeq(il.begin(), il.end()) {} + : seq_(std::make_unique<raw_sequence_type>(il)) {} + + template <typename U = SSeq, + typename = std::enable_if_t<std::is_lvalue_reference_v<U>>> + explicit SaltedSeedSeq(raw_sequence_type& seq) : seq_(&seq) {} + + template <typename U = SSeq, + typename = std::enable_if_t<std::is_lvalue_reference_v<U>>> + explicit SaltedSeedSeq(const raw_sequence_type&&) = delete; SaltedSeedSeq(const SaltedSeedSeq&) = delete; SaltedSeedSeq& operator=(const SaltedSeedSeq&) = delete; @@ -66,98 +110,149 @@ SaltedSeedSeq(SaltedSeedSeq&&) = default; SaltedSeedSeq& operator=(SaltedSeedSeq&&) = default; - template <typename RandomAccessIterator> + template <typename RandomAccessIterator, typename U = raw_sequence_type, + typename = std::void_t<decltype(std::declval<U&>().generate( + std::declval<uint32_t*>(), std::declval<uint32_t*>()))>> void generate(RandomAccessIterator begin, RandomAccessIterator end) { - using U = typename std::iterator_traits<RandomAccessIterator>::value_type; - - // The common case is that generate is called with ContiguousIterators - // to uint arrays. Such contiguous memory regions may be optimized, - // which we detect here. - using TagType = std::conditional_t< - (std::is_same_v<U, uint32_t> && - (std::is_pointer_v<RandomAccessIterator> || - std::is_same_v<RandomAccessIterator, - typename std::vector<U>::iterator>)), - ContiguousAndUint32Tag, DefaultTag>; - if (begin != end) { - generate_impl(TagType{}, begin, end, std::distance(begin, end)); + if (begin == end) { + return; + } + const size_t n = static_cast<size_t>(std::distance(begin, end)); + using V = typename std::iterator_traits<RandomAccessIterator>::value_type; + using Ref = typename std::iterator_traits<RandomAccessIterator>::reference; + if constexpr (std::is_same_v<V, uint32_t> && + std::is_same_v<Ref, uint32_t&> && + (std::is_pointer_v<RandomAccessIterator> || + std::is_same_v<RandomAccessIterator, + typename std::vector<uint32_t>::iterator>)) { + generate_contiguous(&*begin, n); + } else { + absl::InlinedVector<uint32_t, 8> data(n, 0); + ScopedCleanse cleaner(absl::MakeSpan(data)); + generate_contiguous(data.data(), n); + std::copy(data.begin(), data.end(), begin); } } - template <typename OutIterator> + template <typename OutIterator, typename U = raw_sequence_type, + typename = std::void_t<decltype(std::declval<const U&>().param( + std::declval<OutIterator>()))>> void param(OutIterator out) const { - seq_->param(out); + std::as_const(*seq_).param(out); } - size_t size() const { return seq_->size(); } + template <typename U = raw_sequence_type, + typename = std::enable_if_t<std::is_convertible_v< + decltype(std::declval<const U&>().size()), size_t>>> + size_t size() const { + return std::as_const(*seq_).size(); + } + + template <typename U = raw_sequence_type, + typename = std::enable_if_t<!std::is_const_v<U>>, + typename = std::enable_if_t<std::is_convertible_v< + decltype(std::declval<U&>().size()), size_t>>> + size_t size() { + return seq_->size(); + } private: - struct ContiguousAndUint32Tag {}; - struct DefaultTag {}; - - // Generate which requires the iterators are contiguous pointers to uint32_t. - // Fills the initial seed buffer the underlying SSeq::generate() call, - // then mixes in the salt material. - template <typename Contiguous> - void generate_impl(ContiguousAndUint32Tag, Contiguous begin, Contiguous end, - size_t n) { - seq_->generate(begin, end); - const uint32_t salt = absl::random_internal::GetSaltMaterial().value_or(0); - auto span = absl::Span<uint32_t>(&*begin, n); - MixIntoSeedMaterial(absl::MakeConstSpan(&salt, 1), span); - } - - // The uncommon case for generate is that it is called with iterators over - // some other buffer type which is assignable from a 32-bit value. In this - // case we allocate a temporary 32-bit buffer and then copy-assign back - // to the initial inputs. - template <typename RandomAccessIterator> - void generate_impl(DefaultTag, RandomAccessIterator begin, - RandomAccessIterator, size_t n) { - // Allocates a seed buffer of `n` elements, generates the seed, then - // copies the result into the `out` iterator. - absl::InlinedVector<uint32_t, 8> data(n, 0); - generate_impl(ContiguousAndUint32Tag{}, data.begin(), data.end(), n); - std::copy(data.begin(), data.end(), begin); + // Generates `n` salted `uint32_t` values into `out_ptr`. + // For `std::seed_seq`, bypasses `[rand.util.seedseq]`'s narrow-output + // collisions by reading raw parameters via `param()` and applying either a + // 128-bit salt-keyed bijection (`s <= n`, strictly injective up to `n` words + // with 0 collisions) or a keyed SipHash-2-4-128 XOF (`s > n`). For custom + // `SeedSequence` types, invokes `seq_->generate()` once with the exact + // requested count `n` and applies the keyed bijection in place. + void generate_contiguous(uint32_t* out_ptr, size_t n) { + const auto salt = absl::random_internal::GetSaltMaterial(); + if (!salt.has_value()) { + seq_->generate(out_ptr, out_ptr + n); + return; + } + auto out = absl::Span<uint32_t>(out_ptr, n); + if constexpr (std::is_same_v<absl::remove_cvref_t<raw_sequence_type>, + std::seed_seq>) { + absl::InlinedVector<uint32_t, 64> raw(seq_->size()); + ScopedCleanse cleaner(absl::MakeSpan(raw)); + seq_->param(raw.begin()); + if (raw.size() <= n) { + std::copy(raw.begin(), raw.end(), out.data()); + std::fill(out.data() + raw.size(), out.data() + n, uint32_t{0}); + PermuteSeedMaterialWithSalt(*salt, /*domain_tag=*/1u, + static_cast<uint64_t>(raw.size()), out); + } else { + DeriveSeedMaterialWithSalt(*salt, /*domain_tag=*/2u, raw, out); + } + } else { + seq_->generate(out_ptr, out_ptr + n); + PermuteSeedMaterialWithSalt(*salt, /*domain_tag=*/3u, + static_cast<uint64_t>(n), out); + } } // Because [rand.req.seedseq] is not required to be copy-constructible, - // copy-assignable nor movable, we wrap it with unique pointer to be able - // to move SaltedSeedSeq. - std::unique_ptr<SSeq> seq_; + // copy-assignable nor movable, owning instances wrap it with unique_ptr to be + // movable, while SaltedSeedSeq<SSeq&> holds a non-owning pointer. + std::conditional_t<std::is_lvalue_reference_v<SSeq>, raw_sequence_type*, + std::unique_ptr<raw_sequence_type>> + seq_; }; -// is_salted_seed_seq indicates whether the type is a SaltedSeedSeq. -template <typename T, typename = void> -struct is_salted_seed_seq : public std::false_type {}; +template <typename SSeq> +struct IsSaltedSeedSeq<SaltedSeedSeq<SSeq>> : std::true_type {}; -template <typename T> -struct is_salted_seed_seq< - T, std::enable_if_t< - std::is_same_v<T, SaltedSeedSeq<typename T::inner_sequence_type>>>> - : public std::true_type {}; +// UnwrappedSeedSeq unwraps `SaltedSeedSeq<Inner>` to +// `absl::remove_cvref_t<Inner>`, or decays any other seed sequence type via +// `absl::remove_cvref_t`. +template <typename SSeq, + bool = IsSaltedSeedSeq<absl::remove_cvref_t<SSeq>>::value> +struct UnwrappedSeedSeq { + using type = absl::remove_cvref_t<SSeq>; +}; + +template <typename SSeq> +struct UnwrappedSeedSeq<SSeq, true> { + using type = absl::remove_cvref_t< + typename absl::remove_cvref_t<SSeq>::inner_sequence_type>; +}; // MakeSaltedSeedSeq returns a salted variant of the seed sequence. -// When provided with an existing SaltedSeedSeq, returns the input parameter, +// When provided with an existing SaltedSeedSeq, preserves single salting, // otherwise constructs a new SaltedSeedSeq which embodies the original // non-salted seed parameters. -template < - typename SSeq, // - typename EnableIf = std::enable_if_t<is_salted_seed_seq<SSeq>::value>> -SSeq MakeSaltedSeedSeq(SSeq&& seq) { - return SSeq(std::forward<SSeq>(seq)); +template <typename Inner, typename = std::enable_if_t<std::conjunction_v< + std::is_same<Inner, absl::remove_cvref_t<Inner>>, + HasSeedSeqGenerate<Inner>>>> +SaltedSeedSeq<Inner> MakeSaltedSeedSeq(SaltedSeedSeq<Inner>&& seq) { + return std::move(seq); } -template < - typename SSeq, // - typename EnableIf = std::enable_if_t<!is_salted_seed_seq<SSeq>::value>> -SaltedSeedSeq<std::decay_t<SSeq>> MakeSaltedSeedSeq(SSeq&& seq) { - using sseq_type = std::decay_t<SSeq>; - using result_type = typename sseq_type::result_type; - - absl::InlinedVector<result_type, 8> data; +template <typename SSeq, + typename Target = typename UnwrappedSeedSeq<SSeq>::type, + typename = std::enable_if_t<HasSeedSeqGenerate<Target>::value>, + typename Result = typename Target::result_type, + typename = std::enable_if_t<std::is_constructible_v< + SaltedSeedSeq<Target>, + typename absl::InlinedVector<Result, 8>::iterator, + typename absl::InlinedVector<Result, 8>::iterator>>, + typename = std::void_t< + decltype(std::declval<std::remove_reference_t<SSeq>&>().param( + std::back_inserter( + std::declval<absl::InlinedVector<Result, 8>&>())))>> +SaltedSeedSeq<Target> MakeSaltedSeedSeq(SSeq&& seq) { + absl::InlinedVector<Result, 8> data; + struct CleanseOnExit { + absl::InlinedVector<Result, 8>& v; + ~CleanseOnExit() { + CleanseSeedMaterial(v.data(), v.size() * sizeof(Result)); + } + } cleaner{data}; + if constexpr (HasSeedSeqSize<SSeq>::value) { + data.reserve(seq.size()); + } seq.param(std::back_inserter(data)); - return SaltedSeedSeq<sseq_type>(data.begin(), data.end()); + return SaltedSeedSeq<Target>(data.begin(), data.end()); } } // namespace random_internal
diff --git a/absl/random/internal/salted_seed_seq_test.cc b/absl/random/internal/salted_seed_seq_test.cc index 3e8dfeb..0e27b23 100644 --- a/absl/random/internal/salted_seed_seq_test.cc +++ b/absl/random/internal/salted_seed_seq_test.cc
@@ -14,17 +14,27 @@ #include "absl/random/internal/salted_seed_seq.h" +#include <algorithm> +#include <array> #include <cstddef> #include <cstdint> +#include <initializer_list> #include <iterator> +#include <limits> +#include <optional> #include <random> +#include <set> +#include <type_traits> +#include <unordered_set> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/random/internal/seed_material.h" +#include "absl/random/internal/traits.h" using absl::random_internal::GetSaltMaterial; using absl::random_internal::MakeSaltedSeedSeq; @@ -34,6 +44,9 @@ namespace { +// Arbitrary nothing-up-my-sleeve test seed words. +constexpr std::array<uint32_t, 5> kTestSeed = {1, 3, 5, 7, 9}; + template <typename Sseq> void ConformsToInterface() { // Check that the SeedSequence can be default-constructed. @@ -94,16 +107,14 @@ } TEST(SaltedSeedSeq, SaltedSaltedSeedSeqIsNotDoubleSalted) { - uint32_t init[] = {1, 3, 5, 7, 9}; - - std::seed_seq seq(std::begin(init), std::end(init)); + std::seed_seq seq(kTestSeed.begin(), kTestSeed.end()); // The first salting. SaltedSeedSeq<std::seed_seq> salted_seq = MakeSaltedSeedSeq(std::move(seq)); uint32_t a[16]; salted_seq.generate(std::begin(a), std::end(a)); - // The second salting. + // The second salting (rvalue). SaltedSeedSeq<std::seed_seq> salted_salted_seq = MakeSaltedSeedSeq(std::move(salted_seq)); uint32_t b[16]; @@ -111,8 +122,109 @@ // ... both should be equal. EXPECT_THAT(b, Pointwise(Eq(), a)) << "a[0] " << a[0]; + + // Lvalue SaltedSeedSeq must also not be double-salted. + auto lvalue_salted_seq = MakeSaltedSeedSeq(salted_salted_seq); + uint32_t c[16]; + lvalue_salted_seq.generate(std::begin(c), std::end(c)); + EXPECT_THAT(c, Pointwise(Eq(), a)); + + // Const lvalue and const rvalue SaltedSeedSeq must also not be double-salted. + const SaltedSeedSeq<std::seed_seq> const_salted_seq(kTestSeed.begin(), + kTestSeed.end()); + auto from_const_lvalue = MakeSaltedSeedSeq(const_salted_seq); + uint32_t e[16]; + from_const_lvalue.generate(std::begin(e), std::end(e)); + EXPECT_THAT(e, Pointwise(Eq(), a)); + + auto from_const_rvalue = MakeSaltedSeedSeq(std::move(const_salted_seq)); + uint32_t f[16]; + from_const_rvalue.generate(std::begin(f), std::end(f)); + EXPECT_THAT(f, Pointwise(Eq(), a)); } +TEST(SaltedSeedSeq, BraceMoveInvokesMoveConstructor) { + SaltedSeedSeq<std::seed_seq> expected_seq(kTestSeed.begin(), kTestSeed.end()); + uint32_t expected[16]; + expected_seq.generate(std::begin(expected), std::end(expected)); + + SaltedSeedSeq<std::seed_seq> source(kTestSeed.begin(), kTestSeed.end()); + SaltedSeedSeq<std::seed_seq> brace_moved{std::move(source)}; + uint32_t actual[16]; + brace_moved.generate(std::begin(actual), std::end(actual)); + EXPECT_THAT(actual, Pointwise(Eq(), expected)); +} + +TEST(SaltedSeedSeq, MakeSaltedSeedSeqReturnsOwningFromNonOwningRef) { + SaltedSeedSeq<std::seed_seq> expected_seq(kTestSeed.begin(), kTestSeed.end()); + uint32_t expected[16]; + expected_seq.generate(std::begin(expected), std::end(expected)); + + std::optional<SaltedSeedSeq<std::seed_seq>> owned_from_mutable; + std::optional<SaltedSeedSeq<std::seed_seq>> owned_from_const; + { + std::seed_seq raw(kTestSeed.begin(), kTestSeed.end()); + auto made_mutable = MakeSaltedSeedSeq(SaltedSeedSeq<std::seed_seq&>(raw)); + static_assert( + std::is_same_v<decltype(made_mutable), SaltedSeedSeq<std::seed_seq>>); + owned_from_mutable.emplace(std::move(made_mutable)); + + const std::seed_seq const_raw(kTestSeed.begin(), kTestSeed.end()); + auto made_const = + MakeSaltedSeedSeq(SaltedSeedSeq<const std::seed_seq&>(const_raw)); + static_assert( + std::is_same_v<decltype(made_const), SaltedSeedSeq<std::seed_seq>>); + owned_from_const.emplace(std::move(made_const)); + } + + uint32_t from_mutable[16]; + owned_from_mutable->generate(std::begin(from_mutable), + std::end(from_mutable)); + EXPECT_THAT(from_mutable, Pointwise(Eq(), expected)); + + uint32_t from_const[16]; + owned_from_const->generate(std::begin(from_const), std::end(from_const)); + EXPECT_THAT(from_const, Pointwise(Eq(), expected)); +} + +// SaltedSeedSeq constructor constraints. +static_assert(std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, + std::initializer_list<int>>); +static_assert(std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, + std::initializer_list<uint32_t>>); +static_assert(std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, + std::initializer_list<uint64_t>>); +static_assert(!std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, + std::initializer_list<double>>); +static_assert(!std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, + std::initializer_list<const char*>>); +static_assert(std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, uint32_t*, + uint32_t*>); +static_assert( + !std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, double*, double*>); +static_assert( + !std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, double, double>); +static_assert( + !std::is_constructible_v<SaltedSeedSeq<std::seed_seq>, void*, void*>); + +static_assert( + !std::is_default_constructible_v<SaltedSeedSeq<std::seed_seq&>>); +static_assert(!std::is_constructible_v<SaltedSeedSeq<std::seed_seq&>, + std::initializer_list<uint32_t>>); +static_assert(!std::is_constructible_v<SaltedSeedSeq<std::seed_seq&>, + uint32_t*, uint32_t*>); +static_assert( + std::is_constructible_v<SaltedSeedSeq<std::seed_seq&>, std::seed_seq&>); +static_assert(std::is_constructible_v<SaltedSeedSeq<const std::seed_seq&>, + const std::seed_seq&>); +static_assert(std::is_constructible_v<SaltedSeedSeq<const std::seed_seq&>, + std::seed_seq&>); +static_assert(!std::is_constructible_v<SaltedSeedSeq<const std::seed_seq&>, + std::seed_seq>); +static_assert(!std::is_constructible_v<SaltedSeedSeq<const std::seed_seq&>, + const std::seed_seq>); +// Note: SaltedSeedSeq<T&&> is rejected by a class-scope static_assert. + TEST(SaltedSeedSeq, SeedMaterialIsSalted) { const size_t kNumBlocks = 16; @@ -173,4 +285,309 @@ } } +TEST(SaltedSeedSeq, GenerateAcceptsVolatileUint32Outputs) { + constexpr size_t kNumBlocks = 4; + SaltedSeedSeq<std::seed_seq> seq(kTestSeed.begin(), kTestSeed.end()); + + uint32_t expected[kNumBlocks] = {}; + seq.generate(std::begin(expected), std::end(expected)); + + volatile uint32_t seed_material[kNumBlocks] = {}; + seq.generate(std::begin(seed_material), std::end(seed_material)); + uint32_t copy[kNumBlocks] = {}; + std::copy(std::begin(seed_material), std::end(seed_material), + std::begin(copy)); + EXPECT_THAT(copy, Pointwise(Eq(), expected)); +} + +struct CountingSeedSeq { + using result_type = uint32_t; + size_t reported_size = 0; + size_t calls = 0; + size_t last_requested = 0; + + explicit CountingSeedSeq(size_t s) : reported_size(s) {} + size_t size() const { return reported_size; } + template <typename OutIt> + void generate(OutIt begin, OutIt end) { + ++calls; + last_requested = static_cast<size_t>(std::distance(begin, end)); + uint32_t v = 1; + for (OutIt it = begin; it != end; ++it) { + *it = v++; + } + } +}; + +// Known salt-invariant 4-way collision quadruple for raw C++11 +// `std::seed_seq{a, b}.generate(2)`, plus an 8-word pair that collides at 4 +// outputs (exercising the `s > n` XOF path). +constexpr std::array<std::array<uint32_t, 2>, 4> kFourWayTwoWordCollision = {{ + {0x7ad2099du, 0x20261120u}, + {0x2a001490u, 0xcf541c13u}, + {0x592e1f83u, 0xfe822706u}, + {0x6f465452u, 0x149a5bd5u}, +}}; +constexpr std::array<uint32_t, 8> kCollisionS8N4A = { + 0x00000001u, 0x00000002u, 0x00000003u, 0x00000004u, + 0x0000bf91u, 0x67c0a593u, 0x313389e7u, 0xee5c8e5cu}; +constexpr std::array<uint32_t, 8> kCollisionS8N4B = { + 0x00000001u, 0x00000002u, 0x00000003u, 0x00000004u, + 0x00011835u, 0xa5168553u, 0xcee80a7au, 0xee5ce700u}; + +TEST(SaltedSeedSeq, SeparatesRawSeedSeqCollisionsPreservingParams) { + if (!GetSaltMaterial().has_value()) { + GTEST_SKIP() << "Salt material unavailable"; + } + + // `s <= n` PRP path: 4-way collision quadruple at n = 2. + std::set<std::array<uint32_t, 2>> raw_outputs; + std::set<std::array<uint32_t, 2>> salted_outputs; + for (const auto& seed : kFourWayTwoWordCollision) { + std::array<uint32_t, 2> raw{}; + std::seed_seq raw_seq(seed.begin(), seed.end()); + raw_seq.generate(raw.begin(), raw.end()); + raw_outputs.insert(raw); + + std::array<uint32_t, 2> salted{}; + SaltedSeedSeq<std::seed_seq> salted_seq(seed.begin(), seed.end()); + EXPECT_EQ(salted_seq.size(), seed.size()); + std::vector<uint32_t> params; + salted_seq.param(std::back_inserter(params)); + EXPECT_THAT(params, Pointwise(Eq(), seed)); + salted_seq.generate(salted.begin(), salted.end()); + salted_outputs.insert(salted); + } + EXPECT_THAT(raw_outputs, testing::SizeIs(1u)); + EXPECT_THAT(salted_outputs, testing::SizeIs(4u)); + + // `s > n` XOF path: 8-word pair colliding at n = 4. + std::array<uint32_t, 4> raw_a{}, raw_b{}, salted_a{}, salted_b{}; + std::seed_seq(kCollisionS8N4A.begin(), kCollisionS8N4A.end()) + .generate(raw_a.begin(), raw_a.end()); + std::seed_seq(kCollisionS8N4B.begin(), kCollisionS8N4B.end()) + .generate(raw_b.begin(), raw_b.end()); + SaltedSeedSeq<std::seed_seq>(kCollisionS8N4A.begin(), kCollisionS8N4A.end()) + .generate(salted_a.begin(), salted_a.end()); + SaltedSeedSeq<std::seed_seq>(kCollisionS8N4B.begin(), kCollisionS8N4B.end()) + .generate(salted_b.begin(), salted_b.end()); + EXPECT_EQ(raw_a, raw_b); + EXPECT_NE(salted_a, salted_b); +} + +TEST(SaltedSeedSeq, SingleWordGenerateIsBijective) { + if (!GetSaltMaterial().has_value()) { + GTEST_SKIP() << "Salt material unavailable"; + } + constexpr uint32_t kSamples = 10000; + std::unordered_set<uint32_t> outputs; + outputs.reserve(kSamples); + for (uint32_t seed = 0; seed < kSamples; ++seed) { + SaltedSeedSeq<std::seed_seq> seq({seed}); + uint32_t out = 0; + seq.generate(&out, &out + 1); + EXPECT_TRUE(outputs.insert(out).second) << "Collision at seed=" << seed; + } +} + +TEST(SaltedSeedSeq, DistinguishesZeroPaddedLengthsAndFull60WordSeeds) { + if (!GetSaltMaterial().has_value()) { + GTEST_SKIP() << "Salt material unavailable"; + } + auto gen_n = [](std::initializer_list<uint32_t> init, size_t n) { + SaltedSeedSeq<std::seed_seq> seq(init); + std::vector<uint32_t> out(n, 0); + seq.generate(out.begin(), out.end()); + return out; + }; + + EXPECT_NE(gen_n({}, 4), gen_n({0u}, 4)); + EXPECT_NE(gen_n({1u}, 4), gen_n({1u, 0u}, 4)); + EXPECT_NE(gen_n({}, 60), gen_n({0u}, 60)); + + // Seeds differing only in word 59 (bit 1919) or word 63 (past 60 words) + // must produce distinct 60-word outputs. + std::vector<uint32_t> seed60_a(60, 0u); + std::vector<uint32_t> seed60_b(60, 0u); + seed60_b[59] = 1u; + SaltedSeedSeq<std::seed_seq> seq60_a(seed60_a.begin(), seed60_a.end()); + SaltedSeedSeq<std::seed_seq> seq60_b(seed60_b.begin(), seed60_b.end()); + std::array<uint32_t, 60> out60_a{}; + std::array<uint32_t, 60> out60_b{}; + seq60_a.generate(out60_a.begin(), out60_a.end()); + seq60_b.generate(out60_b.begin(), out60_b.end()); + EXPECT_NE(out60_a, out60_b); + + std::vector<uint32_t> seed64_a(64, 0u); + std::vector<uint32_t> seed64_b(64, 0u); + seed64_b[63] = 1u; + SaltedSeedSeq<std::seed_seq> seq64_a(seed64_a.begin(), seed64_a.end()); + SaltedSeedSeq<std::seed_seq> seq64_b(seed64_b.begin(), seed64_b.end()); + std::array<uint32_t, 60> out64_a{}; + std::array<uint32_t, 60> out64_b{}; + seq64_a.generate(out64_a.begin(), out64_a.end()); + seq64_b.generate(out64_b.begin(), out64_b.end()); + EXPECT_NE(out64_a, out64_b); +} + +TEST(SaltedSeedSeq, CustomSeedSeqIsRequestedWithExactCountAndSalted) { + static_assert(absl::random_internal::IsSaltedSeedSeq< + SaltedSeedSeq<std::seed_seq>>::value); + static_assert(absl::random_internal::IsSaltedSeedSeq< + SaltedSeedSeq<CountingSeedSeq&>>::value); + static_assert( + !absl::random_internal::IsSaltedSeedSeq<CountingSeedSeq>::value); + + auto verify_exact_count = [](size_t reported_size, size_t requested) { + std::vector<uint32_t> raw(requested, 0); + CountingSeedSeq raw_seq(reported_size); + raw_seq.generate(raw.begin(), raw.end()); + + std::vector<uint32_t> salted(requested, 0); + CountingSeedSeq seq(reported_size); + SaltedSeedSeq<CountingSeedSeq&> salted_seq(seq); + salted_seq.generate(salted.begin(), salted.end()); + EXPECT_EQ(seq.calls, 1u); + EXPECT_EQ(seq.last_requested, requested); + if (GetSaltMaterial().has_value()) { + EXPECT_NE(salted, raw); + } + }; + + verify_exact_count(0u, 4u); + verify_exact_count(1u, 1u); + verify_exact_count(4u, 4u); + verify_exact_count(40u, 4u); + verify_exact_count((std::numeric_limits<size_t>::max)(), 4u); + verify_exact_count(4u, 8u); +} + +template <typename SSeq, typename = void> +struct HasParamOut : std::false_type {}; + +template <typename SSeq> +struct HasParamOut< + SSeq, + std::void_t<decltype(std::declval<SSeq&>().param( + std::declval<std::back_insert_iterator<std::vector<uint32_t>>>()))>> + : std::true_type {}; + +struct MutableOnlyParamSizeSeq { + using result_type = uint32_t; + size_t size() { return 1u; } + template <typename OutIt> + void param(OutIt out) { + *out++ = 42u; + } + template <typename OutIt> + void generate(OutIt begin, OutIt end) { + std::fill(begin, end, uint32_t{42u}); + } +}; + +struct DualConstParamSizeSeq { + using result_type = uint32_t; + size_t size() { return 1u; } + size_t size() const { return 2u; } + template <typename OutIt> + void param(OutIt out) { + *out++ = 10u; + } + template <typename OutIt> + void param(OutIt out) const { + *out++ = 20u; + *out++ = 21u; + } + template <typename OutIt> + void generate(OutIt begin, OutIt end) { + std::fill(begin, end, uint32_t{7u}); + } +}; + +struct GrowingNoSizeParamSeq { + using result_type = uint32_t; + std::vector<uint32_t> words; + GrowingNoSizeParamSeq() = default; + template <typename It> + GrowingNoSizeParamSeq(It begin, It end) : words(begin, end) {} + template <typename OutIt> + void param(OutIt out) const { + for (uint32_t w : words) *out++ = w; + } + template <typename OutIt> + void generate(OutIt begin, OutIt end) { + std::fill(begin, end, uint32_t{1u}); + } +}; + +#ifdef ABSL_HAVE_EXCEPTIONS +struct ThrowingParamSeq { + using result_type = uint32_t; + ThrowingParamSeq() = default; + template <typename It> + ThrowingParamSeq(It, It) {} + template <typename OutIt> + void param(OutIt out) const { + for (uint32_t i = 0; i < 12; ++i) *out++ = 0x5a5a0000u + i; + throw 123; + } + template <typename OutIt> + void generate(OutIt begin, OutIt end) { + std::fill(begin, end, uint32_t{1u}); + } +}; +#endif + +TEST(SaltedSeedSeq, DeepConstnessOnSizeAndParam) { + using absl::random_internal::HasSeedSeqSize; + static_assert(HasSeedSeqSize<SaltedSeedSeq<MutableOnlyParamSizeSeq>>::value); + static_assert( + !HasSeedSeqSize<const SaltedSeedSeq<MutableOnlyParamSizeSeq>>::value); + static_assert(!HasParamOut<SaltedSeedSeq<MutableOnlyParamSizeSeq>>::value); + static_assert( + !HasParamOut<const SaltedSeedSeq<MutableOnlyParamSizeSeq>>::value); + + SaltedSeedSeq<DualConstParamSizeSeq> mutable_seq; + EXPECT_EQ(mutable_seq.size(), 1u); + std::vector<uint32_t> mutable_params; + mutable_seq.param(std::back_inserter(mutable_params)); + EXPECT_THAT(mutable_params, testing::ElementsAre(20u, 21u)); + + const SaltedSeedSeq<DualConstParamSizeSeq> const_seq; + EXPECT_EQ(const_seq.size(), 2u); + std::vector<uint32_t> const_params; + const_seq.param(std::back_inserter(const_params)); + EXPECT_THAT(const_params, testing::ElementsAre(20u, 21u)); +} + +TEST(SaltedSeedSeq, MakeSaltedSeedSeqUnwrapsConstOwningAndHandlesGrowth) { + auto unwrapped = MakeSaltedSeedSeq( + SaltedSeedSeq<const std::seed_seq>(kTestSeed.begin(), kTestSeed.end())); + static_assert( + std::is_same_v<decltype(unwrapped), SaltedSeedSeq<std::seed_seq>>); + uint32_t out[4] = {}; + unwrapped.generate(std::begin(out), std::end(out)); + SaltedSeedSeq<std::seed_seq> expected_seq(kTestSeed.begin(), kTestSeed.end()); + uint32_t expected[4] = {}; + expected_seq.generate(std::begin(expected), std::end(expected)); + EXPECT_THAT(out, Pointwise(Eq(), expected)); + + // Exceed inline capacity (8) without `size()` to exercise reallocation and + // exit-time buffer cleansing. + std::vector<uint32_t> wide_seed(20); + for (size_t i = 0; i < wide_seed.size(); ++i) { + wide_seed[i] = static_cast<uint32_t>(100 + i); + } + const GrowingNoSizeParamSeq growing(wide_seed.begin(), wide_seed.end()); + auto salted_growing = MakeSaltedSeedSeq(growing); + std::vector<uint32_t> round_tripped; + salted_growing.param(std::back_inserter(round_tripped)); + EXPECT_THAT(round_tripped, Pointwise(Eq(), wide_seed)); + +#ifdef ABSL_HAVE_EXCEPTIONS + const ThrowingParamSeq throwing_seq; + EXPECT_THROW((void)MakeSaltedSeedSeq(throwing_seq), int); +#endif +} + } // namespace
diff --git a/absl/random/internal/seed_material.cc b/absl/random/internal/seed_material.cc index c09e63f..0412f1f 100644 --- a/absl/random/internal/seed_material.cc +++ b/absl/random/internal/seed_material.cc
@@ -19,6 +19,7 @@ #include <algorithm> #include <cassert> #include <cerrno> +#include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> @@ -27,9 +28,11 @@ #include <string> #include <vector> +#include "absl/algorithm/container.h" #include "absl/base/config.h" #include "absl/base/dynamic_annotations.h" #include "absl/base/internal/raw_logging.h" +#include "absl/numeric/bits.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" @@ -277,6 +280,143 @@ #endif +// Standard SipHash-2-4 with 128-bit output (Aumasson & Bernstein). +// Pure 64-bit ARX, constant-time, zero lookup tables, little-endian word order. +class SipHash24_128 { + public: + explicit SipHash24_128(const SaltMaterial& key) noexcept { + const uint64_t k0 = + uint64_t{key[0]} | (static_cast<uint64_t>(key[1]) << 32); + const uint64_t k1 = + uint64_t{key[2]} | (static_cast<uint64_t>(key[3]) << 32); + v_[0] = uint64_t{0x736f6d6570736575} ^ k0; + v_[1] = uint64_t{0x646f72616e646f6d} ^ k1 ^ uint64_t{0xee}; + v_[2] = uint64_t{0x6c7967656e657261} ^ k0; + v_[3] = uint64_t{0x7465646279746573} ^ k1; + } + + ~SipHash24_128() noexcept { Cleanse(); } + + void UpdateU64(uint64_t word) noexcept { + if (has_pending_u32_) { + CompressBlock(uint64_t{pending_u32_} | (word << 32)); + pending_u32_ = static_cast<uint32_t>(word >> 32); + } else { + CompressBlock(word); + } + total_bytes_ += 8; + } + + void UpdateWordsLe(absl::Span<const uint32_t> words) noexcept { + size_t i = 0; + if (has_pending_u32_ && !words.empty()) { + CompressBlock(uint64_t{pending_u32_} | + (static_cast<uint64_t>(words[0]) << 32)); + has_pending_u32_ = false; + pending_u32_ = 0; + total_bytes_ += 4; + i = 1; + } + for (; i + 1 < words.size(); i += 2) { + CompressBlock(uint64_t{words[i]} | + (static_cast<uint64_t>(words[i + 1]) << 32)); + total_bytes_ += 8; + } + if (i < words.size()) { + pending_u32_ = words[i]; + has_pending_u32_ = true; + total_bytes_ += 4; + } + } + + SaltMaterial Final() noexcept { + uint64_t b = (total_bytes_ & 0xffu) << 56; + if (has_pending_u32_) { + b |= uint64_t{pending_u32_}; + } + CompressBlock(b); + v_[2] ^= uint64_t{0xee}; + for (int i = 0; i < 4; ++i) SipRound(); + const uint64_t h0 = v_[0] ^ v_[1] ^ v_[2] ^ v_[3]; + v_[1] ^= uint64_t{0xdd}; + for (int i = 0; i < 4; ++i) SipRound(); + const uint64_t h1 = v_[0] ^ v_[1] ^ v_[2] ^ v_[3]; + SaltMaterial out = { + static_cast<uint32_t>(h0), + static_cast<uint32_t>(h0 >> 32), + static_cast<uint32_t>(h1), + static_cast<uint32_t>(h1 >> 32), + }; + return out; + } + + private: + void SipRound() noexcept { + v_[0] += v_[1]; + v_[1] = absl::rotl(v_[1], 13); + v_[1] ^= v_[0]; + v_[0] = absl::rotl(v_[0], 32); + v_[2] += v_[3]; + v_[3] = absl::rotl(v_[3], 16); + v_[3] ^= v_[2]; + v_[0] += v_[3]; + v_[3] = absl::rotl(v_[3], 21); + v_[3] ^= v_[0]; + v_[2] += v_[1]; + v_[1] = absl::rotl(v_[1], 17); + v_[1] ^= v_[2]; + v_[2] = absl::rotl(v_[2], 32); + } + + void CompressBlock(uint64_t m) noexcept { + v_[3] ^= m; + SipRound(); + SipRound(); + v_[0] ^= m; + } + + void Cleanse() noexcept { + CleanseSeedMaterial(v_, sizeof(v_)); + CleanseSeedMaterial(&pending_u32_, sizeof(pending_u32_)); + has_pending_u32_ = false; + total_bytes_ = 0; + } + + uint64_t v_[4]; + uint64_t total_bytes_ = 0; + uint32_t pending_u32_ = 0; + bool has_pending_u32_ = false; +}; + +SaltMaterial SipHashKeyedDomain(const SaltMaterial& salt, uint32_t domain_tag, + uint32_t round, uint64_t param_size, + uint64_t out_size, + absl::Span<const uint32_t> msg_words) noexcept { + SipHash24_128 hasher(salt); + hasher.UpdateU64(uint64_t{domain_tag} | (static_cast<uint64_t>(round) << 32)); + hasher.UpdateU64(param_size); + hasher.UpdateU64(out_size); + hasher.UpdateWordsLe(msg_words); + return hasher.Final(); +} + +void SipHashXorSqueeze(const SaltMaterial& seed, + absl::Span<uint32_t> out) noexcept { + uint64_t counter = 0; + size_t offset = 0; + while (offset < out.size()) { + SipHash24_128 hasher(seed); + hasher.UpdateU64(counter++); + SaltMaterial block = hasher.Final(); + ScopedCleanse block_cleaner(absl::MakeSpan(block)); + const size_t chunk = (std::min)(out.size() - offset, block.size()); + for (size_t i = 0; i < chunk; ++i) { + out[offset + i] ^= block[i]; + } + offset += chunk; + } +} + } // namespace bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values) { @@ -322,16 +462,110 @@ } } -std::optional<uint32_t> GetSaltMaterial() { +SaltMaterial NormalizeSaltMaterial(absl::Span<const uint32_t> words) { + SaltMaterial salt{}; + if (words.size() == salt.size()) { + absl::c_copy(words, salt); + return salt; + } + // Fixed domain-separation key: little-endian ASCII "absl_salt_norm_1". + constexpr SaltMaterial kNormKey = {0x6c736261u, 0x6c61735fu, 0x6f6e5f74u, + 0x315f6d72u}; + SipHash24_128 hasher(kNormKey); + hasher.UpdateU64(static_cast<uint64_t>(words.size())); + hasher.UpdateWordsLe(words); + return hasher.Final(); +} + +void PermuteSeedMaterialWithSalt(const SaltMaterial& salt, uint32_t domain_tag, + uint64_t param_size, + absl::Span<uint32_t> seed_material) { + const size_t n = seed_material.size(); + if (n == 0) { + return; + } + if (n == 1) { + // 6-round 16-bit Feistel PRP: exact bijection on uint32_t. + uint32_t lo = seed_material[0] & 0xffffu; + uint32_t hi = seed_material[0] >> 16; + for (uint32_t r = 0; r < 6; ++r) { + SaltMaterial digest = + SipHashKeyedDomain(salt, domain_tag, r, param_size, + /*out_size=*/1, absl::MakeConstSpan(&hi, 1)); + ScopedCleanse digest_cleaner(absl::MakeSpan(digest)); + const uint32_t next_lo = hi; + const uint32_t next_hi = lo ^ (digest[0] & 0xffffu); + lo = next_lo; + hi = next_hi; + } + seed_material[0] = lo | (hi << 16); + return; + } + + // 4-round balanced Feistel PRP: exact bijection on (uint32_t)^n. + const size_t left_len = n / 2; + auto left = seed_material.subspan(0, left_len); + auto right = seed_material.subspan(left_len); + for (uint32_t r = 0; r < 4; ++r) { + if ((r & 1u) == 0u) { + SaltMaterial round_seed = + SipHashKeyedDomain(salt, domain_tag, r, param_size, n, right); + ScopedCleanse seed_cleaner(absl::MakeSpan(round_seed)); + SipHashXorSqueeze(round_seed, left); + } else { + SaltMaterial round_seed = + SipHashKeyedDomain(salt, domain_tag, r, param_size, n, left); + ScopedCleanse seed_cleaner(absl::MakeSpan(round_seed)); + SipHashXorSqueeze(round_seed, right); + } + } +} + +void DeriveSeedMaterialWithSalt(const SaltMaterial& salt, uint32_t domain_tag, + absl::Span<const uint32_t> seed_words, + absl::Span<uint32_t> out) { + if (out.empty()) { + return; + } + SaltMaterial key = SipHashKeyedDomain( + salt, domain_tag, /*round=*/0, static_cast<uint64_t>(seed_words.size()), + static_cast<uint64_t>(out.size()), seed_words); + ScopedCleanse key_cleaner(absl::MakeSpan(key)); + if (out.size() <= key.size()) { + absl::c_copy_n(key, out.size(), out.data()); + return; + } + // Derive a second 128-bit digest so outputs wider than 128 bits retain + // 256 bits of intermediate entropy (matching kEntropyBitsNeeded). + SaltMaterial extra = SipHashKeyedDomain( + salt, domain_tag, /*round=*/1, static_cast<uint64_t>(seed_words.size()), + static_cast<uint64_t>(out.size()), seed_words); + ScopedCleanse extra_cleaner(absl::MakeSpan(extra)); + uint64_t counter = 0; + size_t offset = 0; + while (offset < out.size()) { + SipHash24_128 hasher(key); + hasher.UpdateU64(counter++); + hasher.UpdateWordsLe(extra); + SaltMaterial block = hasher.Final(); + ScopedCleanse block_cleaner(absl::MakeSpan(block)); + const size_t chunk = (std::min)(out.size() - offset, block.size()); + absl::c_copy_n(block, chunk, out.data() + offset); + offset += chunk; + } +} + +std::optional<SaltMaterial> GetSaltMaterial() { // Salt must be common for all generators within the same process so read it // only once and store in static variable. - static const auto salt_material = []() -> std::optional<uint32_t> { - uint32_t salt_value = 0; + static const auto salt_material = []() -> std::optional<SaltMaterial> { - if (ReadSeedMaterialFromOSEntropy(absl::MakeSpan(&salt_value, 1))) { + SaltMaterial salt_value{}; + if (ReadSeedMaterialFromOSEntropy(absl::MakeSpan(salt_value))) { return salt_value; } + CleanseSeedMaterial(salt_value.data(), sizeof(salt_value)); return std::nullopt; }();
diff --git a/absl/random/internal/seed_material.h b/absl/random/internal/seed_material.h index 23bf4fa..aaff810 100644 --- a/absl/random/internal/seed_material.h +++ b/absl/random/internal/seed_material.h
@@ -15,11 +15,14 @@ #ifndef ABSL_RANDOM_INTERNAL_SEED_MATERIAL_H_ #define ABSL_RANDOM_INTERNAL_SEED_MATERIAL_H_ +#include <array> #include <cassert> +#include <cstddef> #include <cstdint> #include <cstdlib> #include <optional> #include <string> +#include <type_traits> #include <vector> #include "absl/base/config.h" @@ -49,6 +52,51 @@ static_assert(kEntropyBlocksNeeded > 0, "Entropy used to seed URBGs must be nonzero."); +// Amount of salt material (in bits / 32-bit blocks) used to key SaltedSeedSeq. +constexpr size_t kSaltBitsNeeded = 128; +constexpr size_t kSaltBlocksNeeded = + random_internal::SeedBitsToBlocks(kSaltBitsNeeded); + +static_assert(kSaltBlocksNeeded == 4, + "SaltMaterial must be 128 bits (4 x uint32_t)."); + +// 128-bit process/build salt material (4 x uint32_t). +using SaltMaterial = std::array<uint32_t, kSaltBlocksNeeded>; + +// Zeroes `bytes` at `data` using volatile writes so the compiler does not +// optimize away scrubbing of temporary seed or pool buffers. +inline void CleanseSeedMaterial(void* data, size_t bytes) noexcept { + if (data == nullptr || bytes == 0) { + return; + } + volatile unsigned char* p = static_cast<volatile unsigned char*>(data); + while (bytes-- > 0) { + *p++ = 0; + } +} + +// RAII guard that zeroes a buffer on scope exit via CleanseSeedMaterial(). +class ScopedCleanse { + public: + ScopedCleanse(void* data, size_t bytes) noexcept + : data_(data), bytes_(bytes) {} + template <typename T> + explicit ScopedCleanse(absl::Span<T> span) noexcept + : data_(span.data()), bytes_(span.size() * sizeof(T)) { + static_assert(std::is_trivially_copyable_v<T>, + "ScopedCleanse requires trivially copyable element types."); + } + + ScopedCleanse(const ScopedCleanse&) = delete; + ScopedCleanse& operator=(const ScopedCleanse&) = delete; + + ~ScopedCleanse() { CleanseSeedMaterial(data_, bytes_); } + + private: + void* data_; + size_t bytes_; +}; + // Attempts to fill a span of uint32_t-values using an OS-provided source of // true entropy (eg. /dev/urandom) into an array of uint32_t blocks of data. The // resulting array may be used to initialize an instance of a class conforming @@ -91,12 +139,33 @@ void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence, absl::Span<uint32_t> seed_material); -// Returns salt value. +// Normalizes arbitrary-length salt words into a 128-bit `SaltMaterial`. +// Preserves 4-word inputs verbatim (so logged 128-bit salts round-trip +// losslessly) and derives 4 words via SipHash-2-4-128 over all input words and +// length otherwise. +SaltMaterial NormalizeSaltMaterial(absl::Span<const uint32_t> words); + +// Applies a constant-time, 128-bit salt-keyed bijection (Feistel PRP built on +// SipHash-2-4-128) to `seed_material` in place. Domain-separated by +// `domain_tag`, `param_size`, and `seed_material.size()`. Strictly bijective on +// (uint32_t)^n for every n >= 1 and every salt. +void PermuteSeedMaterialWithSalt(const SaltMaterial& salt, uint32_t domain_tag, + uint64_t param_size, + absl::Span<uint32_t> seed_material); + +// Derives `out` from arbitrary-length `seed_words` and `salt` via a +// constant-time keyed SipHash-2-4-128 XOF, domain-separated by `domain_tag`, +// `seed_words.size()`, and `out.size()`. +void DeriveSeedMaterialWithSalt(const SaltMaterial& salt, uint32_t domain_tag, + absl::Span<const uint32_t> seed_words, + absl::Span<uint32_t> out); + +// Returns 128-bit salt value. // // Salt is obtained only once and stored in static variable. // // May return empty value if obtaining the salt was not possible. -std::optional<uint32_t> GetSaltMaterial(); +std::optional<SaltMaterial> GetSaltMaterial(); } // namespace random_internal ABSL_NAMESPACE_END
diff --git a/absl/random/internal/seed_material_test.cc b/absl/random/internal/seed_material_test.cc index c65c1bf..17379dc 100644 --- a/absl/random/internal/seed_material_test.cc +++ b/absl/random/internal/seed_material_test.cc
@@ -14,7 +14,9 @@ #include "absl/random/internal/seed_material.h" +#include <array> #include <bitset> +#include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> @@ -24,6 +26,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/container/flat_hash_set.h" #include "absl/types/span.h" #ifdef __ANDROID__ @@ -246,4 +249,214 @@ } } +TEST(CleanseSeedMaterial, ZeroesBufferContents) { + uint32_t buf[8] = {1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u}; + // Null pointer and zero-length calls must be safe no-ops. + absl::random_internal::CleanseSeedMaterial(nullptr, 0); + absl::random_internal::CleanseSeedMaterial(nullptr, 16); + absl::random_internal::CleanseSeedMaterial(buf, 0); + EXPECT_EQ(buf[0], 1u); + + absl::random_internal::CleanseSeedMaterial(buf, sizeof(buf)); + EXPECT_THAT(buf, Each(Eq(0u))); +} + +TEST(ScopedCleanse, ZeroesBufferOnScopeExit) { + uint32_t raw_buf[4] = {1u, 2u, 3u, 4u}; + { + absl::random_internal::ScopedCleanse cleaner(raw_buf, sizeof(raw_buf)); + EXPECT_EQ(raw_buf[0], 1u); + } + EXPECT_THAT(raw_buf, Each(Eq(0u))); + + std::array<uint32_t, 4> span_buf = {5u, 6u, 7u, 8u}; + { + absl::random_internal::ScopedCleanse cleaner(absl::MakeSpan(span_buf)); + EXPECT_EQ(span_buf[0], 5u); + } + EXPECT_THAT(span_buf, Each(Eq(0u))); +} + +TEST(NormalizeSaltMaterial, PreservesFourWordsVerbatimAndMatchesKat) { + using absl::random_internal::NormalizeSaltMaterial; + using absl::random_internal::SaltMaterial; + + constexpr SaltMaterial kFull = { + 0x01020304u, + 0x05060708u, + 0x090a0b0cu, + 0x0d0e0f10u, + }; + EXPECT_EQ(NormalizeSaltMaterial(kFull), kFull); + + // Reference SipHash-2-4-128 vector for 1-word input {0x12345678}. + const uint32_t kSingleWord[1] = {0x12345678u}; + constexpr SaltMaterial kExpectedNorm1 = { + 0x34027de4u, + 0x0ed68fd1u, + 0xe1c4d52au, + 0xa8e31af5u, + }; + EXPECT_EQ(NormalizeSaltMaterial(kSingleWord), kExpectedNorm1); + + // Distinct lengths and trailing words beyond 32/128 bits must not collide. + const uint32_t kTwoWordsZeroTail[2] = {0x12345678u, 0u}; + const uint32_t kTwoWordsNonZeroTail[2] = {0x12345678u, 1u}; + EXPECT_NE(NormalizeSaltMaterial(kSingleWord), + NormalizeSaltMaterial(kTwoWordsZeroTail)); + EXPECT_NE(NormalizeSaltMaterial(kTwoWordsZeroTail), + NormalizeSaltMaterial(kTwoWordsNonZeroTail)); + + const uint32_t kEightWordsA[8] = {1u, 2u, 3u, 4u, 5u, 6u, 7u, 0u}; + const uint32_t kEightWordsB[8] = {1u, 2u, 3u, 4u, 5u, 6u, 7u, 1u}; + EXPECT_NE(NormalizeSaltMaterial(kEightWordsA), + NormalizeSaltMaterial(kEightWordsB)); +} + +TEST(DeriveSeedMaterialWithSalt, MatchesSipHashKatAndSeparatesDomains) { + using absl::random_internal::DeriveSeedMaterialWithSalt; + using absl::random_internal::SaltMaterial; + + constexpr SaltMaterial kSalt = { + 0x01020304u, + 0x05060708u, + 0x090a0b0cu, + 0x0d0e0f10u, + }; + constexpr uint32_t kSeed[3] = {0xdeadbeefu, 0xcafebabeu, 0x01234567u}; + + // Empty output must be a safe no-op. + DeriveSeedMaterialWithSalt(kSalt, /*domain_tag=*/2u, kSeed, + absl::Span<uint32_t>()); + + // Direct <= 4 word output path (reference SipHash-2-4-128 KAT). + std::array<uint32_t, 4> out4{}; + DeriveSeedMaterialWithSalt(kSalt, /*domain_tag=*/2u, kSeed, + absl::MakeSpan(out4)); + constexpr std::array<uint32_t, 4> kExpected4 = { + 0x7d542ffcu, + 0x05ac2984u, + 0xcc36cbc9u, + 0x585ef79du, + }; + EXPECT_EQ(out4, kExpected4); + + // Wide (> 4 words) 256-bit intermediate key path (reference KAT). + std::array<uint32_t, 10> out{}; + DeriveSeedMaterialWithSalt(kSalt, /*domain_tag=*/2u, kSeed, + absl::MakeSpan(out)); + constexpr std::array<uint32_t, 10> kExpected = { + 0x8eb9a06fu, 0x21b60e8bu, 0xd689ab87u, 0x24bd0bfbu, 0x05954dd6u, + 0xbd2f20c4u, 0x96350bceu, 0xd8c58cafu, 0xb038aa60u, 0x171e3ef0u, + }; + EXPECT_EQ(out, kExpected); + + // Empty input must be distinct from a single zero word. + std::array<uint32_t, 4> out_empty{}; + std::array<uint32_t, 4> out_zero{}; + const uint32_t kZero[1] = {0u}; + DeriveSeedMaterialWithSalt(kSalt, /*domain_tag=*/2u, {}, + absl::MakeSpan(out_empty)); + DeriveSeedMaterialWithSalt(kSalt, /*domain_tag=*/2u, kZero, + absl::MakeSpan(out_zero)); + EXPECT_NE(out_empty, out_zero); + + // Flipping a bit in word 3 (bits 96..127) of the salt must change outputs. + SaltMaterial flipped_salt = kSalt; + flipped_salt[3] ^= 0x80000000u; + std::array<uint32_t, 10> out_flipped{}; + DeriveSeedMaterialWithSalt(flipped_salt, /*domain_tag=*/2u, kSeed, + absl::MakeSpan(out_flipped)); + EXPECT_THAT(out, Pointwise(Ne(), out_flipped)); +} + +TEST(PermuteSeedMaterialWithSalt, IsBijectiveForSingleWordAndDiffusesAllBits) { + using absl::random_internal::PermuteSeedMaterialWithSalt; + using absl::random_internal::SaltMaterial; + + constexpr SaltMaterial kSalt = { + 0x243f6a88u, + 0x85a308d3u, + 0x13198a2eu, + 0x03707344u, + }; + + // Empty span must be a safe no-op. + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/0u, + absl::Span<uint32_t>()); + + // Reference SipHash-2-4-128 Feistel KATs for n = 1 and odd n = 5. + uint32_t kat1 = 0x12345678u; + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/1u, + absl::MakeSpan(&kat1, 1)); + EXPECT_EQ(kat1, 0x07052b2au); + + std::array<uint32_t, 5> kat5 = {1u, 2u, 3u, 4u, 5u}; + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/5u, + absl::MakeSpan(kat5)); + constexpr std::array<uint32_t, 5> kExpectedKat5 = { + 0x4cf87f87u, 0x56902be0u, 0x2069d875u, 0xab38df4fu, 0x531447b9u, + }; + EXPECT_EQ(kat5, kExpectedKat5); + + // Two-word balanced Feistel must diffuse both halves. + std::array<uint32_t, 2> pair_a = {0u, 0u}; + std::array<uint32_t, 2> pair_b = {0u, 1u}; + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/2u, + absl::MakeSpan(pair_a)); + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/2u, + absl::MakeSpan(pair_b)); + EXPECT_THAT(pair_a, Pointwise(Ne(), pair_b)); + + // Single-word 6-round Feistel PRP must have zero collisions. + constexpr size_t kSamples = 10000; + absl::flat_hash_set<uint32_t> seen; + seen.reserve(kSamples); + for (uint32_t i = 0; i < kSamples; ++i) { + uint32_t word = i; + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/1u, + absl::MakeSpan(&word, 1)); + EXPECT_TRUE(seen.insert(word).second); + } + + // Domain separation: param_size and domain_tag separate identical inputs. + std::array<uint32_t, 4> a = {1u, 0u, 0u, 0u}; + std::array<uint32_t, 4> b = a; + std::array<uint32_t, 4> c = a; + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/1u, + absl::MakeSpan(a)); + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/1u, /*param_size=*/2u, + absl::MakeSpan(b)); + PermuteSeedMaterialWithSalt(kSalt, /*domain_tag=*/3u, /*param_size=*/1u, + absl::MakeSpan(c)); + EXPECT_NE(a, b); + EXPECT_NE(a, c); + EXPECT_NE(b, c); + + // Avalanche across all 60 words when flipping bit 0 of the input or word 3 + // of the 128-bit salt. + std::array<uint32_t, 60> base{}; + base[0] = 1u; + std::array<uint32_t, 60> diff_in = base; + diff_in[0] ^= 1u; + std::array<uint32_t, 60> diff_salt = base; + SaltMaterial salt_b = kSalt; + salt_b[3] ^= 1u; + PermuteSeedMaterialWithSalt(kSalt, 1u, 1u, absl::MakeSpan(base)); + PermuteSeedMaterialWithSalt(kSalt, 1u, 1u, absl::MakeSpan(diff_in)); + PermuteSeedMaterialWithSalt(salt_b, 1u, 1u, absl::MakeSpan(diff_salt)); + + size_t changed_in = 0; + size_t changed_salt = 0; + for (size_t i = 0; i < base.size(); ++i) { + changed_in += std::bitset<32>(base[i] ^ diff_in[i]).count(); + changed_salt += std::bitset<32>(base[i] ^ diff_salt[i]).count(); + } + const double total_bits = static_cast<double>(base.size() * 32); + EXPECT_GE(changed_in, 0.4 * total_bits); + EXPECT_LE(changed_in, 0.6 * total_bits); + EXPECT_GE(changed_salt, 0.4 * total_bits); + EXPECT_LE(changed_salt, 0.6 * total_bits); +} + } // namespace
diff --git a/absl/random/internal/traits.h b/absl/random/internal/traits.h index 8404d93..5d53b6b 100644 --- a/absl/random/internal/traits.h +++ b/absl/random/internal/traits.h
@@ -19,6 +19,7 @@ #include <cstdint> #include <limits> #include <type_traits> +#include <utility> #include "absl/base/config.h" #include "absl/meta/type_traits.h" @@ -162,6 +163,60 @@ } } +// Returns whether `T` is a valid `[rand.req.seedseq]` `result_type` +// (an unqualified unsigned integer type of at least 32 bits). +template <typename T> +constexpr bool IsValidSeedSeqResultType() { + if constexpr (std::is_same_v<T, absl::remove_cvref_t<T>> && + std::is_integral_v<T> && std::is_unsigned_v<T>) { + return std::numeric_limits<T>::digits >= 32; + } else { + return false; + } +} + +template <typename SSeq, typename = void> +struct HasValidSeedSeqResultType : std::false_type {}; + +template <typename SSeq> +struct HasValidSeedSeqResultType< + SSeq, std::void_t<typename std::remove_reference_t<SSeq>::result_type>> + : std::bool_constant<IsValidSeedSeqResultType< + typename std::remove_reference_t<SSeq>::result_type>()> {}; + +// Detects whether `std::remove_reference_t<SSeq>` has a valid `result_type` +// and supports `seq.generate(uint32_t*, uint32_t*)` on an lvalue (preserving +// `const`). Short-circuits `generate()` detection when `result_type` is missing +// or invalid. +template <typename SSeq, + bool ValidResult = HasValidSeedSeqResultType<SSeq>::value, + typename = void> +struct HasSeedSeqGenerate : std::false_type {}; + +template <typename SSeq> +struct HasSeedSeqGenerate< + SSeq, true, + std::void_t< + decltype(std::declval<std::remove_reference_t<SSeq>&>().generate( + std::declval<uint32_t*>(), std::declval<uint32_t*>()))>> + : std::true_type {}; + +// Detects whether `std::remove_reference_t<SSeq>` supports `seq.size()` +// convertible to `size_t` on an lvalue (preserving `const`). +template <typename SSeq, typename = void> +struct HasSeedSeqSize : std::false_type {}; + +template <typename SSeq> +struct HasSeedSeqSize< + SSeq, std::enable_if_t<std::is_convertible_v< + decltype(std::declval<std::remove_reference_t<SSeq>&>().size()), + size_t>>> : std::true_type {}; + +// Marks `SaltedSeedSeq` wrappers so engines such as `randen_engine` can draw +// full-rate seed material rather than truncating to `seq.size()`. +template <typename SSeq> +struct IsSaltedSeedSeq : std::false_type {}; + } // namespace random_internal ABSL_NAMESPACE_END } // namespace absl
diff --git a/absl/random/internal/traits_test.cc b/absl/random/internal/traits_test.cc index 08361a4..deb82f7 100644 --- a/absl/random/internal/traits_test.cc +++ b/absl/random/internal/traits_test.cc
@@ -14,6 +14,7 @@ #include "absl/random/internal/traits.h" +#include <cstddef> #include <cstdint> #include <random> #include <type_traits> @@ -22,8 +23,12 @@ namespace { +using absl::random_internal::HasSeedSeqGenerate; +using absl::random_internal::HasSeedSeqSize; using absl::random_internal::is_urbg; using absl::random_internal::is_widening_convertible; +using absl::random_internal::IsSaltedSeedSeq; +using absl::random_internal::IsValidSeedSeqResultType; static_assert(is_urbg<std::minstd_rand>::value); static_assert(!is_urbg<uint64_t>::value); @@ -125,4 +130,89 @@ CheckWideningConvertsTo<bool, float>(); } +enum UnscopedU32Enum : uint32_t { kZero = 0 }; +enum class ScopedU32Enum : uint32_t { kZero = 0 }; +struct EmptyStruct {}; + +struct NoResultSeedSeq { + size_t size() const { return 1; } + void generate(uint32_t*, uint32_t*) {} +}; + +struct MutableOnlySeedSeq { + using result_type = uint32_t; + size_t size() { return 1; } + void generate(uint32_t*, uint32_t*) {} +}; + +struct ConstSeedSeq { + using result_type = uint64_t; + size_t size() const { return 1; } + void generate(uint32_t*, uint32_t*) const {} +}; + +struct InvalidResultAutoGenerateSeedSeq { + using result_type = int; + template <typename It> + auto generate(It begin, It) { + static_assert(sizeof(It) == 0, + "HasSeedSeqGenerate must short-circuit before generate()"); + return *begin; + } +}; + +struct VoidResultAutoGenerateSeedSeq { + using result_type = void; + template <typename It> + auto generate(It begin, It) { + static_assert(sizeof(It) == 0, + "HasSeedSeqGenerate must short-circuit before generate()"); + return *begin; + } +}; + +// IsValidSeedSeqResultType accepts unqualified unsigned integers >= 32 bits. +static_assert(IsValidSeedSeqResultType<uint32_t>()); +static_assert(IsValidSeedSeqResultType<uint64_t>()); +static_assert(IsValidSeedSeqResultType<unsigned int>()); +static_assert(IsValidSeedSeqResultType<unsigned long>()); // NOLINT +static_assert(IsValidSeedSeqResultType<unsigned long long>()); // NOLINT +static_assert(IsValidSeedSeqResultType<std::seed_seq::result_type>()); + +// IsValidSeedSeqResultType rejects narrow, signed, cv-ref, and non-integers. +static_assert(!IsValidSeedSeqResultType<bool>()); +static_assert(!IsValidSeedSeqResultType<uint8_t>()); +static_assert(!IsValidSeedSeqResultType<uint16_t>()); +static_assert(!IsValidSeedSeqResultType<int32_t>()); +static_assert(!IsValidSeedSeqResultType<int64_t>()); +static_assert(!IsValidSeedSeqResultType<const uint32_t>()); +static_assert(!IsValidSeedSeqResultType<volatile uint32_t>()); +static_assert(!IsValidSeedSeqResultType<uint32_t&>()); +static_assert(!IsValidSeedSeqResultType<uint32_t&&>()); +static_assert(!IsValidSeedSeqResultType<float>()); +static_assert(!IsValidSeedSeqResultType<double>()); +static_assert(!IsValidSeedSeqResultType<void>()); +static_assert(!IsValidSeedSeqResultType<UnscopedU32Enum>()); +static_assert(!IsValidSeedSeqResultType<ScopedU32Enum>()); +static_assert(!IsValidSeedSeqResultType<EmptyStruct>()); + +// HasSeedSeqGenerate short-circuits invalid result_type and preserves const. +static_assert(!HasSeedSeqGenerate<NoResultSeedSeq>::value); +static_assert(!HasSeedSeqGenerate<InvalidResultAutoGenerateSeedSeq&>::value); +static_assert(!HasSeedSeqGenerate<VoidResultAutoGenerateSeedSeq&>::value); +static_assert(HasSeedSeqGenerate<MutableOnlySeedSeq&>::value); +static_assert(!HasSeedSeqGenerate<const MutableOnlySeedSeq&>::value); +static_assert(HasSeedSeqGenerate<const ConstSeedSeq&>::value); + +// HasSeedSeqSize preserves const qualification. +static_assert(HasSeedSeqSize<MutableOnlySeedSeq&>::value); +static_assert(!HasSeedSeqSize<const MutableOnlySeedSeq&>::value); +static_assert(HasSeedSeqSize<const ConstSeedSeq&>::value); +static_assert(!HasSeedSeqSize<EmptyStruct>::value); + +// IsSaltedSeedSeq defaults to false for non-SaltedSeedSeq types. +static_assert(!IsSaltedSeedSeq<std::seed_seq>::value); +static_assert(!IsSaltedSeedSeq<ConstSeedSeq>::value); +static_assert(!IsSaltedSeedSeq<EmptyStruct>::value); + } // namespace
diff --git a/absl/random/seed_sequences.cc b/absl/random/seed_sequences.cc index 316381b..7ed197e 100644 --- a/absl/random/seed_sequences.cc +++ b/absl/random/seed_sequences.cc
@@ -18,12 +18,14 @@ #include "absl/base/config.h" #include "absl/random/internal/entropy_pool.h" +#include "absl/random/internal/seed_material.h" namespace absl { ABSL_NAMESPACE_BEGIN SeedSeq MakeSeedSeq() { SeedSeq::result_type seed_material[8]; + random_internal::ScopedCleanse cleaner(seed_material, sizeof(seed_material)); random_internal::GetEntropyFromRandenPool(&seed_material[0], sizeof(seed_material[0]) * 8); return SeedSeq(std::begin(seed_material), std::end(seed_material));
diff --git a/absl/random/seed_sequences.h b/absl/random/seed_sequences.h index a8d953b..1ada5a4 100644 --- a/absl/random/seed_sequences.h +++ b/absl/random/seed_sequences.h
@@ -82,6 +82,7 @@ template <typename URBG> SeedSeq CreateSeedSeqFrom(URBG* urbg) { SeedSeq::result_type seed_material[random_internal::kEntropyBlocksNeeded]; + random_internal::ScopedCleanse cleaner(seed_material, sizeof(seed_material)); if (!random_internal::ReadSeedMaterialFromURBG( urbg, absl::MakeSpan(seed_material))) {