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