1 // Copyright 2011 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 #include "base/rand_util.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <algorithm>
11 #include <cmath>
12 #include <limits>
13 #include <memory>
14 #include <vector>
15
16 #include "base/logging.h"
17 #include "base/time/time.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19
20 namespace base {
21
22 namespace {
23
24 const int kIntMin = std::numeric_limits<int>::min();
25 const int kIntMax = std::numeric_limits<int>::max();
26
27 } // namespace
28
TEST(RandUtilTest,RandInt)29 TEST(RandUtilTest, RandInt) {
30 EXPECT_EQ(base::RandInt(0, 0), 0);
31 EXPECT_EQ(base::RandInt(kIntMin, kIntMin), kIntMin);
32 EXPECT_EQ(base::RandInt(kIntMax, kIntMax), kIntMax);
33
34 // Check that the DCHECKS in RandInt() don't fire due to internal overflow.
35 // There was a 50% chance of that happening, so calling it 40 times means
36 // the chances of this passing by accident are tiny (9e-13).
37 for (int i = 0; i < 40; ++i)
38 base::RandInt(kIntMin, kIntMax);
39 }
40
TEST(RandUtilTest,RandDouble)41 TEST(RandUtilTest, RandDouble) {
42 // Force 64-bit precision, making sure we're not in a 80-bit FPU register.
43 volatile double number = base::RandDouble();
44 EXPECT_GT(1.0, number);
45 EXPECT_LE(0.0, number);
46 }
47
TEST(RandUtilTest,RandFloat)48 TEST(RandUtilTest, RandFloat) {
49 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
50 volatile float number = base::RandFloat();
51 EXPECT_GT(1.f, number);
52 EXPECT_LE(0.f, number);
53 }
54
TEST(RandUtilTest,RandTimeDelta)55 TEST(RandUtilTest, RandTimeDelta) {
56 {
57 const auto delta =
58 base::RandTimeDelta(-base::Seconds(2), -base::Seconds(1));
59 EXPECT_GE(delta, -base::Seconds(2));
60 EXPECT_LT(delta, -base::Seconds(1));
61 }
62
63 {
64 const auto delta = base::RandTimeDelta(-base::Seconds(2), base::Seconds(2));
65 EXPECT_GE(delta, -base::Seconds(2));
66 EXPECT_LT(delta, base::Seconds(2));
67 }
68
69 {
70 const auto delta = base::RandTimeDelta(base::Seconds(1), base::Seconds(2));
71 EXPECT_GE(delta, base::Seconds(1));
72 EXPECT_LT(delta, base::Seconds(2));
73 }
74 }
75
TEST(RandUtilTest,RandTimeDeltaUpTo)76 TEST(RandUtilTest, RandTimeDeltaUpTo) {
77 const auto delta = base::RandTimeDeltaUpTo(base::Seconds(2));
78 EXPECT_FALSE(delta.is_negative());
79 EXPECT_LT(delta, base::Seconds(2));
80 }
81
TEST(RandUtilTest,BitsToOpenEndedUnitInterval)82 TEST(RandUtilTest, BitsToOpenEndedUnitInterval) {
83 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
84 volatile double all_zeros = BitsToOpenEndedUnitInterval(0x0);
85 EXPECT_EQ(0.0, all_zeros);
86
87 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
88 volatile double smallest_nonzero = BitsToOpenEndedUnitInterval(0x1);
89 EXPECT_LT(0.0, smallest_nonzero);
90
91 for (uint64_t i = 0x2; i < 0x10; ++i) {
92 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
93 volatile double number = BitsToOpenEndedUnitInterval(i);
94 EXPECT_EQ(i * smallest_nonzero, number);
95 }
96
97 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
98 volatile double all_ones = BitsToOpenEndedUnitInterval(UINT64_MAX);
99 EXPECT_GT(1.0, all_ones);
100 }
101
TEST(RandUtilTest,BitsToOpenEndedUnitIntervalF)102 TEST(RandUtilTest, BitsToOpenEndedUnitIntervalF) {
103 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
104 volatile float all_zeros = BitsToOpenEndedUnitIntervalF(0x0);
105 EXPECT_EQ(0.f, all_zeros);
106
107 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
108 volatile float smallest_nonzero = BitsToOpenEndedUnitIntervalF(0x1);
109 EXPECT_LT(0.f, smallest_nonzero);
110
111 for (uint64_t i = 0x2; i < 0x10; ++i) {
112 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
113 volatile float number = BitsToOpenEndedUnitIntervalF(i);
114 EXPECT_EQ(i * smallest_nonzero, number);
115 }
116
117 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
118 volatile float all_ones = BitsToOpenEndedUnitIntervalF(UINT64_MAX);
119 EXPECT_GT(1.f, all_ones);
120 }
121
TEST(RandUtilTest,RandBytes)122 TEST(RandUtilTest, RandBytes) {
123 const size_t buffer_size = 50;
124 char buffer[buffer_size];
125 memset(buffer, 0, buffer_size);
126 base::RandBytes(buffer, buffer_size);
127 std::sort(buffer, buffer + buffer_size);
128 // Probability of occurrence of less than 25 unique bytes in 50 random bytes
129 // is below 10^-25.
130 EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25);
131 }
132
133 // Verify that calling base::RandBytes with an empty buffer doesn't fail.
TEST(RandUtilTest,RandBytes0)134 TEST(RandUtilTest, RandBytes0) {
135 base::RandBytes(nullptr, 0);
136 }
137
TEST(RandUtilTest,RandBytesAsVector)138 TEST(RandUtilTest, RandBytesAsVector) {
139 std::vector<uint8_t> random_vec = base::RandBytesAsVector(0);
140 EXPECT_TRUE(random_vec.empty());
141 random_vec = base::RandBytesAsVector(1);
142 EXPECT_EQ(1U, random_vec.size());
143 random_vec = base::RandBytesAsVector(145);
144 EXPECT_EQ(145U, random_vec.size());
145 char accumulator = 0;
146 for (auto i : random_vec) {
147 accumulator |= i;
148 }
149 // In theory this test can fail, but it won't before the universe dies of
150 // heat death.
151 EXPECT_NE(0, accumulator);
152 }
153
TEST(RandUtilTest,RandBytesAsString)154 TEST(RandUtilTest, RandBytesAsString) {
155 std::string random_string = base::RandBytesAsString(1);
156 EXPECT_EQ(1U, random_string.size());
157 random_string = base::RandBytesAsString(145);
158 EXPECT_EQ(145U, random_string.size());
159 char accumulator = 0;
160 for (auto i : random_string)
161 accumulator |= i;
162 // In theory this test can fail, but it won't before the universe dies of
163 // heat death.
164 EXPECT_NE(0, accumulator);
165 }
166
167 // Make sure that it is still appropriate to use RandGenerator in conjunction
168 // with std::random_shuffle().
TEST(RandUtilTest,RandGeneratorForRandomShuffle)169 TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
170 EXPECT_EQ(base::RandGenerator(1), 0U);
171 EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
172 std::numeric_limits<int64_t>::max());
173 }
174
TEST(RandUtilTest,RandGeneratorIsUniform)175 TEST(RandUtilTest, RandGeneratorIsUniform) {
176 // Verify that RandGenerator has a uniform distribution. This is a
177 // regression test that consistently failed when RandGenerator was
178 // implemented this way:
179 //
180 // return base::RandUint64() % max;
181 //
182 // A degenerate case for such an implementation is e.g. a top of
183 // range that is 2/3rds of the way to MAX_UINT64, in which case the
184 // bottom half of the range would be twice as likely to occur as the
185 // top half. A bit of calculus care of jar@ shows that the largest
186 // measurable delta is when the top of the range is 3/4ths of the
187 // way, so that's what we use in the test.
188 constexpr uint64_t kTopOfRange =
189 (std::numeric_limits<uint64_t>::max() / 4ULL) * 3ULL;
190 constexpr double kExpectedAverage = static_cast<double>(kTopOfRange / 2);
191 constexpr double kAllowedVariance = kExpectedAverage / 50.0; // +/- 2%
192 constexpr int kMinAttempts = 1000;
193 constexpr int kMaxAttempts = 1000000;
194
195 double cumulative_average = 0.0;
196 int count = 0;
197 while (count < kMaxAttempts) {
198 uint64_t value = base::RandGenerator(kTopOfRange);
199 cumulative_average = (count * cumulative_average + value) / (count + 1);
200
201 // Don't quit too quickly for things to start converging, or we may have
202 // a false positive.
203 if (count > kMinAttempts &&
204 kExpectedAverage - kAllowedVariance < cumulative_average &&
205 cumulative_average < kExpectedAverage + kAllowedVariance) {
206 break;
207 }
208
209 ++count;
210 }
211
212 ASSERT_LT(count, kMaxAttempts) << "Expected average was " << kExpectedAverage
213 << ", average ended at " << cumulative_average;
214 }
215
TEST(RandUtilTest,RandUint64ProducesBothValuesOfAllBits)216 TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
217 // This tests to see that our underlying random generator is good
218 // enough, for some value of good enough.
219 uint64_t kAllZeros = 0ULL;
220 uint64_t kAllOnes = ~kAllZeros;
221 uint64_t found_ones = kAllZeros;
222 uint64_t found_zeros = kAllOnes;
223
224 for (size_t i = 0; i < 1000; ++i) {
225 uint64_t value = base::RandUint64();
226 found_ones |= value;
227 found_zeros &= value;
228
229 if (found_zeros == kAllZeros && found_ones == kAllOnes)
230 return;
231 }
232
233 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
234 }
235
TEST(RandUtilTest,RandBytesLonger)236 TEST(RandUtilTest, RandBytesLonger) {
237 // Fuchsia can only retrieve 256 bytes of entropy at a time, so make sure we
238 // handle longer requests than that.
239 std::string random_string0 = base::RandBytesAsString(255);
240 EXPECT_EQ(255u, random_string0.size());
241 std::string random_string1 = base::RandBytesAsString(1023);
242 EXPECT_EQ(1023u, random_string1.size());
243 std::string random_string2 = base::RandBytesAsString(4097);
244 EXPECT_EQ(4097u, random_string2.size());
245 }
246
247 // Benchmark test for RandBytes(). Disabled since it's intentionally slow and
248 // does not test anything that isn't already tested by the existing RandBytes()
249 // tests.
TEST(RandUtilTest,DISABLED_RandBytesPerf)250 TEST(RandUtilTest, DISABLED_RandBytesPerf) {
251 // Benchmark the performance of |kTestIterations| of RandBytes() using a
252 // buffer size of |kTestBufferSize|.
253 const int kTestIterations = 10;
254 const size_t kTestBufferSize = 1 * 1024 * 1024;
255
256 std::unique_ptr<uint8_t[]> buffer(new uint8_t[kTestBufferSize]);
257 const base::TimeTicks now = base::TimeTicks::Now();
258 for (int i = 0; i < kTestIterations; ++i)
259 base::RandBytes(buffer.get(), kTestBufferSize);
260 const base::TimeTicks end = base::TimeTicks::Now();
261
262 LOG(INFO) << "RandBytes(" << kTestBufferSize
263 << ") took: " << (end - now).InMicroseconds() << "µs";
264 }
265
TEST(RandUtilTest,InsecureRandomGeneratorProducesBothValuesOfAllBits)266 TEST(RandUtilTest, InsecureRandomGeneratorProducesBothValuesOfAllBits) {
267 // This tests to see that our underlying random generator is good
268 // enough, for some value of good enough.
269 uint64_t kAllZeros = 0ULL;
270 uint64_t kAllOnes = ~kAllZeros;
271 uint64_t found_ones = kAllZeros;
272 uint64_t found_zeros = kAllOnes;
273
274 InsecureRandomGenerator generator;
275
276 for (size_t i = 0; i < 1000; ++i) {
277 uint64_t value = generator.RandUint64();
278 found_ones |= value;
279 found_zeros &= value;
280
281 if (found_zeros == kAllZeros && found_ones == kAllOnes)
282 return;
283 }
284
285 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
286 }
287
288 namespace {
289
290 constexpr double kXp1Percent = -2.33;
291 constexpr double kXp99Percent = 2.33;
292
ChiSquaredCriticalValue(double nu,double x_p)293 double ChiSquaredCriticalValue(double nu, double x_p) {
294 // From "The Art Of Computer Programming" (TAOCP), Volume 2, Section 3.3.1,
295 // Table 1. This is the asymptotic value for nu > 30, up to O(1 / sqrt(nu)).
296 return nu + sqrt(2. * nu) * x_p + 2. / 3. * (x_p * x_p) - 2. / 3.;
297 }
298
ExtractBits(uint64_t value,int from_bit,int num_bits)299 int ExtractBits(uint64_t value, int from_bit, int num_bits) {
300 return (value >> from_bit) & ((1 << num_bits) - 1);
301 }
302
303 // Performs a Chi-Squared test on a subset of |num_bits| extracted starting from
304 // |from_bit| in the generated value.
305 //
306 // See TAOCP, Volume 2, Section 3.3.1, and
307 // https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test for details.
308 //
309 // This is only one of the many, many random number generator test we could do,
310 // but they are cumbersome, as they are typically very slow, and expected to
311 // fail from time to time, due to their probabilistic nature.
312 //
313 // The generator we use has however been vetted with the BigCrush test suite
314 // from Marsaglia, so this should suffice as a smoke test that our
315 // implementation is wrong.
ChiSquaredTest(InsecureRandomGenerator & gen,size_t n,int from_bit,int num_bits)316 bool ChiSquaredTest(InsecureRandomGenerator& gen,
317 size_t n,
318 int from_bit,
319 int num_bits) {
320 const int range = 1 << num_bits;
321 CHECK_EQ(static_cast<int>(n % range), 0) << "Makes computations simpler";
322 std::vector<size_t> samples(range, 0);
323
324 // Count how many samples pf each value are found. All buckets should be
325 // almost equal if the generator is suitably uniformly random.
326 for (size_t i = 0; i < n; i++) {
327 int sample = ExtractBits(gen.RandUint64(), from_bit, num_bits);
328 samples[sample] += 1;
329 }
330
331 // Compute the Chi-Squared statistic, which is:
332 // \Sum_{k=0}^{range-1} \frac{(count - expected)^2}{expected}
333 double chi_squared = 0.;
334 double expected_count = n / range;
335 for (size_t sample_count : samples) {
336 double deviation = sample_count - expected_count;
337 chi_squared += (deviation * deviation) / expected_count;
338 }
339
340 // The generator should produce numbers that are not too far of (chi_squared
341 // lower than a given quantile), but not too close to the ideal distribution
342 // either (chi_squared is too low).
343 //
344 // See The Art Of Computer Programming, Volume 2, Section 3.3.1 for details.
345 return chi_squared > ChiSquaredCriticalValue(range - 1, kXp1Percent) &&
346 chi_squared < ChiSquaredCriticalValue(range - 1, kXp99Percent);
347 }
348
349 } // namespace
350
TEST(RandUtilTest,InsecureRandomGeneratorChiSquared)351 TEST(RandUtilTest, InsecureRandomGeneratorChiSquared) {
352 constexpr int kIterations = 50;
353
354 // Specifically test the low bits, which are usually weaker in random number
355 // generators. We don't use them for the 32 bit number generation, but let's
356 // make sure they are still suitable.
357 for (int start_bit : {1, 2, 3, 8, 12, 20, 32, 48, 54}) {
358 int pass_count = 0;
359 for (int i = 0; i < kIterations; i++) {
360 size_t samples = 1 << 16;
361 InsecureRandomGenerator gen;
362 // Fix the seed to make the test non-flaky.
363 gen.ReseedForTesting(kIterations + 1);
364 bool pass = ChiSquaredTest(gen, samples, start_bit, 8);
365 pass_count += pass;
366 }
367
368 // We exclude 1% on each side, so we expect 98% of tests to pass, meaning 98
369 // * kIterations / 100. However this is asymptotic, so add a bit of leeway.
370 int expected_pass_count = (kIterations * 98) / 100;
371 EXPECT_GE(pass_count, expected_pass_count - ((kIterations * 2) / 100))
372 << "For start_bit = " << start_bit;
373 }
374 }
375
TEST(RandUtilTest,InsecureRandomGeneratorRandDouble)376 TEST(RandUtilTest, InsecureRandomGeneratorRandDouble) {
377 InsecureRandomGenerator gen;
378
379 for (int i = 0; i < 1000; i++) {
380 volatile double x = gen.RandDouble();
381 EXPECT_GE(x, 0.);
382 EXPECT_LT(x, 1.);
383 }
384 }
385 } // namespace base
386