1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_RAND_UTIL_H_
6 #define BASE_RAND_UTIL_H_
14 #include "base/base_export.h"
15 #include "base/compiler_specific.h"
16 #include "base/gtest_prod_util.h"
17 #include "build/build_config.h"
19 #if !BUILDFLAG(IS_NACL)
20 #include "third_party/boringssl/src/include/openssl/rand.h"
27 #if BUILDFLAG(IS_ANDROID)
28 // Sets the implementation of RandBytes according to the corresponding
29 // base::Feature. Thread safe: allows to switch while RandBytes() is in use.
30 void ConfigureRandBytesFieldTrial();
33 #if !BUILDFLAG(IS_NACL)
34 void ConfigureBoringSSLBackedRandBytesFieldTrial();
37 // Returns a random double in range [0, 1). For use in allocator shim to avoid
38 // infinite recursion. Thread-safe.
39 BASE_EXPORT double RandDoubleAvoidAllocation();
41 } // namespace internal
43 // Returns a random number in range [0, UINT64_MAX]. Thread-safe.
44 BASE_EXPORT uint64_t RandUint64();
46 // Returns a random number between min and max (inclusive). Thread-safe.
47 BASE_EXPORT int RandInt(int min, int max);
49 // Returns a random number in range [0, range). Thread-safe.
50 BASE_EXPORT uint64_t RandGenerator(uint64_t range);
52 // Returns a random double in range [0, 1). Thread-safe.
53 BASE_EXPORT double RandDouble();
55 // Returns a random float in range [0, 1). Thread-safe.
56 BASE_EXPORT float RandFloat();
58 // Given input |bits|, convert with maximum precision to a double in
59 // the range [0, 1). Thread-safe.
60 BASE_EXPORT double BitsToOpenEndedUnitInterval(uint64_t bits);
62 // Given input `bits`, convert with maximum precision to a float in the range
63 // [0, 1). Thread-safe.
64 BASE_EXPORT float BitsToOpenEndedUnitIntervalF(uint64_t bits);
66 // Fills |output_length| bytes of |output| with random data. Thread-safe.
68 // Although implementations are required to use a cryptographically secure
69 // random number source, code outside of base/ that relies on this should use
70 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
71 BASE_EXPORT void RandBytes(void* output, size_t output_length);
73 // Fills a string of length |length| with random data and returns it.
74 // |length| should be nonzero. Thread-safe.
76 // Note that this is a variation of |RandBytes| with a different return type.
77 // The returned string is likely not ASCII/UTF-8. Use with care.
79 // Although implementations are required to use a cryptographically secure
80 // random number source, code outside of base/ that relies on this should use
81 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
82 BASE_EXPORT std::string RandBytesAsString(size_t length);
84 // An STL UniformRandomBitGenerator backed by RandUint64.
85 class RandomBitGenerator {
87 using result_type = uint64_t;
88 static constexpr result_type min() { return 0; }
89 static constexpr result_type max() { return UINT64_MAX; }
90 result_type operator()() const { return RandUint64(); }
92 RandomBitGenerator() = default;
93 ~RandomBitGenerator() = default;
96 #if !BUILDFLAG(IS_NACL)
97 class NonAllocatingRandomBitGenerator {
99 using result_type = uint64_t;
100 static constexpr result_type min() { return 0; }
101 static constexpr result_type max() { return UINT64_MAX; }
102 result_type operator()() const {
104 RAND_get_system_entropy_for_custom_prng(reinterpret_cast<uint8_t*>(&result),
109 NonAllocatingRandomBitGenerator() = default;
110 ~NonAllocatingRandomBitGenerator() = default;
114 // Shuffles [first, last) randomly. Thread-safe.
115 template <typename Itr>
116 void RandomShuffle(Itr first, Itr last) {
117 std::shuffle(first, last, RandomBitGenerator());
120 #if BUILDFLAG(IS_POSIX)
121 BASE_EXPORT int GetUrandomFD();
124 class MetricsSubSampler;
126 // Fast, insecure pseudo-random number generator.
128 // WARNING: This is not the generator you are looking for. This has significant
130 // - It is non-cryptographic, so easy to miuse
131 // - It is neither fork() nor clone()-safe.
132 // - Synchronization is up to the client.
134 // Always prefer base::Rand*() above, unless you have a use case where its
135 // overhead is too high, or system calls are disallowed.
137 // Performance: As of 2021, rough overhead on Linux on a desktop machine of
138 // base::RandUint64() is ~800ns per call (it performs a system call). On Windows
139 // it is lower. On the same machine, this generator's cost is ~2ns per call,
140 // regardless of platform.
142 // This is different from |Rand*()| above as it is guaranteed to never make a
143 // system call to generate a new number, except to seed it. This should *never*
144 // be used for cryptographic applications, and is not thread-safe.
146 // It is seeded using base::RandUint64() in the constructor, meaning that it
147 // doesn't need to be seeded. It can be re-seeded though, with
148 // ReseedForTesting(). Its period is long enough that it should not need to be
149 // re-seeded during use.
151 // Uses the XorShift128+ generator under the hood.
152 class BASE_EXPORT InsecureRandomGenerator {
154 // Never use outside testing, not enough entropy.
155 void ReseedForTesting(uint64_t seed);
157 uint32_t RandUint32();
158 uint64_t RandUint64();
163 InsecureRandomGenerator();
165 uint64_t a_ = 0, b_ = 0;
167 // Before adding a new friend class, make sure that the overhead of
168 // base::Rand*() is too high, using something more representative than a
171 // Uses the generator to sub-sample metrics.
172 friend class MetricsSubSampler;
174 FRIEND_TEST_ALL_PREFIXES(RandUtilTest,
175 InsecureRandomGeneratorProducesBothValuesOfAllBits);
176 FRIEND_TEST_ALL_PREFIXES(RandUtilTest, InsecureRandomGeneratorChiSquared);
177 FRIEND_TEST_ALL_PREFIXES(RandUtilTest, InsecureRandomGeneratorRandDouble);
178 FRIEND_TEST_ALL_PREFIXES(RandUtilPerfTest, InsecureRandomRandUint64);
181 class BASE_EXPORT MetricsSubSampler {
184 bool ShouldSample(double probability);
187 InsecureRandomGenerator generator_;
192 #endif // BASE_RAND_UTIL_H_