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.
4
5 #ifndef BASE_RAND_UTIL_H_
6 #define BASE_RAND_UTIL_H_
7
8 #include <stddef.h>
9 #include <stdint.h>
10
11 #include <algorithm>
12 #include <string>
13 #include <vector>
14
15 #include "base/base_export.h"
16 #include "base/compiler_specific.h"
17 #include "base/containers/span.h"
18 #include "base/gtest_prod_util.h"
19 #include "build/build_config.h"
20
21 #if !BUILDFLAG(IS_NACL)
22 #include "third_party/boringssl/src/include/openssl/rand.h"
23 #endif
24
25 namespace memory_simulator {
26 class MemoryHolder;
27 }
28
29 namespace base {
30
31 class TimeDelta;
32
33 namespace internal {
34
35 #if !BUILDFLAG(IS_NACL)
36 void ConfigureBoringSSLBackedRandBytesFieldTrial();
37 #endif
38
39 // Returns a random double in range [0, 1). For use in allocator shim to avoid
40 // infinite recursion. Thread-safe.
41 BASE_EXPORT double RandDoubleAvoidAllocation();
42
43 } // namespace internal
44
45 // Returns a random number in range [0, UINT64_MAX]. Thread-safe.
46 BASE_EXPORT uint64_t RandUint64();
47
48 // Returns a random number between min and max (inclusive). Thread-safe.
49 //
50 // TODO(crbug.com/40283703): Change from fully-closed to half-closed (i.e.
51 // exclude `max`) to parallel other APIs here.
52 BASE_EXPORT int RandInt(int min, int max);
53
54 // Returns a random number in range [0, range). Thread-safe.
55 BASE_EXPORT uint64_t RandGenerator(uint64_t range);
56
57 // Returns a random double in range [0, 1). Thread-safe.
58 BASE_EXPORT double RandDouble();
59
60 // Returns a random float in range [0, 1). Thread-safe.
61 BASE_EXPORT float RandFloat();
62
63 // Returns a random duration in [`start`, `limit`). Thread-safe.
64 //
65 // REQUIRES: `start` < `limit`
66 BASE_EXPORT TimeDelta RandTimeDelta(TimeDelta start, TimeDelta limit);
67
68 // Returns a random duration in [`TimeDelta()`, `limit`). Thread-safe.
69 //
70 // REQUIRES: `limit.is_positive()`
71 BASE_EXPORT TimeDelta RandTimeDeltaUpTo(TimeDelta limit);
72
73 // Given input |bits|, convert with maximum precision to a double in
74 // the range [0, 1). Thread-safe.
75 BASE_EXPORT double BitsToOpenEndedUnitInterval(uint64_t bits);
76
77 // Given input `bits`, convert with maximum precision to a float in the range
78 // [0, 1). Thread-safe.
79 BASE_EXPORT float BitsToOpenEndedUnitIntervalF(uint64_t bits);
80
81 // Fills `output` with cryptographically secure random data. Thread-safe.
82 //
83 // Although implementations are required to use a cryptographically secure
84 // random number source, code outside of base/ that relies on this should use
85 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
86 BASE_EXPORT void RandBytes(span<uint8_t> output);
87
88 // Creates a vector of `length` bytes, fills it with random data, and returns
89 // it. Thread-safe.
90 //
91 // Although implementations are required to use a cryptographically secure
92 // random number source, code outside of base/ that relies on this should use
93 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
94 BASE_EXPORT std::vector<uint8_t> RandBytesAsVector(size_t length);
95
96 // DEPRECATED. Prefer RandBytesAsVector() above.
97 // Fills a string of length |length| with random data and returns it.
98 // Thread-safe.
99 //
100 // Note that this is a variation of |RandBytes| with a different return type.
101 // The returned string is likely not ASCII/UTF-8. Use with care.
102 //
103 // Although implementations are required to use a cryptographically secure
104 // random number source, code outside of base/ that relies on this should use
105 // crypto::RandBytes instead to ensure the requirement is easily discoverable.
106 BASE_EXPORT std::string RandBytesAsString(size_t length);
107
108 // An STL UniformRandomBitGenerator backed by RandUint64.
109 class RandomBitGenerator {
110 public:
111 using result_type = uint64_t;
min()112 static constexpr result_type min() { return 0; }
max()113 static constexpr result_type max() { return UINT64_MAX; }
operator()114 result_type operator()() const { return RandUint64(); }
115
116 RandomBitGenerator() = default;
117 ~RandomBitGenerator() = default;
118 };
119
120 #if !BUILDFLAG(IS_NACL)
121 class NonAllocatingRandomBitGenerator {
122 public:
123 using result_type = uint64_t;
min()124 static constexpr result_type min() { return 0; }
max()125 static constexpr result_type max() { return UINT64_MAX; }
operator()126 result_type operator()() const {
127 uint64_t result;
128 RAND_get_system_entropy_for_custom_prng(reinterpret_cast<uint8_t*>(&result),
129 sizeof(result));
130 return result;
131 }
132
133 NonAllocatingRandomBitGenerator() = default;
134 ~NonAllocatingRandomBitGenerator() = default;
135 };
136 #endif
137
138 // Shuffles [first, last) randomly. Thread-safe.
139 template <typename Itr>
RandomShuffle(Itr first,Itr last)140 void RandomShuffle(Itr first, Itr last) {
141 std::shuffle(first, last, RandomBitGenerator());
142 }
143
144 #if BUILDFLAG(IS_POSIX)
145 BASE_EXPORT int GetUrandomFD();
146 #endif
147
148 class MetricsSubSampler;
149
150 // Fast, insecure pseudo-random number generator.
151 //
152 // WARNING: This is not the generator you are looking for. This has significant
153 // caveats:
154 // - It is non-cryptographic, so easy to miuse
155 // - It is neither fork() nor clone()-safe.
156 // - Synchronization is up to the client.
157 //
158 // Always prefer base::Rand*() above, unless you have a use case where its
159 // overhead is too high, or system calls are disallowed.
160 //
161 // Performance: As of 2021, rough overhead on Linux on a desktop machine of
162 // base::RandUint64() is ~800ns per call (it performs a system call). On Windows
163 // it is lower. On the same machine, this generator's cost is ~2ns per call,
164 // regardless of platform.
165 //
166 // This is different from |Rand*()| above as it is guaranteed to never make a
167 // system call to generate a new number, except to seed it. This should *never*
168 // be used for cryptographic applications, and is not thread-safe.
169 //
170 // It is seeded using base::RandUint64() in the constructor, meaning that it
171 // doesn't need to be seeded. It can be re-seeded though, with
172 // ReseedForTesting(). Its period is long enough that it should not need to be
173 // re-seeded during use.
174 //
175 // Uses the XorShift128+ generator under the hood.
176 class BASE_EXPORT InsecureRandomGenerator {
177 public:
178 // Never use outside testing, not enough entropy.
179 void ReseedForTesting(uint64_t seed);
180
181 uint32_t RandUint32();
182 uint64_t RandUint64();
183 // In [0, 1).
184 double RandDouble();
185
186 private:
187 InsecureRandomGenerator();
188 // State.
189 uint64_t a_ = 0, b_ = 0;
190
191 // Before adding a new friend class, make sure that the overhead of
192 // base::Rand*() is too high, using something more representative than a
193 // microbenchmark.
194
195 // Uses the generator to fill memory pages with random content to make them
196 // hard to compress, in a simulation tool not bundled with Chrome. CPU
197 // overhead must be minimized to correctly measure memory effects.
198 friend class memory_simulator::MemoryHolder;
199 // Uses the generator to sub-sample metrics.
200 friend class MetricsSubSampler;
201
202 FRIEND_TEST_ALL_PREFIXES(RandUtilTest,
203 InsecureRandomGeneratorProducesBothValuesOfAllBits);
204 FRIEND_TEST_ALL_PREFIXES(RandUtilTest, InsecureRandomGeneratorChiSquared);
205 FRIEND_TEST_ALL_PREFIXES(RandUtilTest, InsecureRandomGeneratorRandDouble);
206 FRIEND_TEST_ALL_PREFIXES(RandUtilPerfTest, InsecureRandomRandUint64);
207 };
208
209 class BASE_EXPORT MetricsSubSampler {
210 public:
211 MetricsSubSampler();
212 bool ShouldSample(double probability);
213
214 // Make any call to ShouldSample for any instance of MetricsSubSampler
215 // return true for testing. Cannot be used in conjunction with
216 // ScopedNeverSampleForTesting.
217 class BASE_EXPORT ScopedAlwaysSampleForTesting {
218 public:
219 ScopedAlwaysSampleForTesting();
220 ~ScopedAlwaysSampleForTesting();
221 };
222
223 // Make any call to ShouldSample for any instance of MetricsSubSampler
224 // return false for testing. Cannot be used in conjunction with
225 // ScopedAlwaysSampleForTesting.
226 class BASE_EXPORT ScopedNeverSampleForTesting {
227 public:
228 ScopedNeverSampleForTesting();
229 ~ScopedNeverSampleForTesting();
230 };
231
232 private:
233 InsecureRandomGenerator generator_;
234 };
235
236 } // namespace base
237
238 #endif // BASE_RAND_UTIL_H_
239