• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 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 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include "base/rand_util.h"
11 
12 #include <zircon/syscalls.h>
13 
14 #include <atomic>
15 
16 #include "base/containers/span.h"
17 #include "base/feature_list.h"
18 #include "third_party/boringssl/src/include/openssl/rand.h"
19 
20 namespace base {
21 
22 namespace internal {
23 
24 namespace {
25 
26 // The BoringSSl helpers are duplicated in rand_util_posix.cc and
27 // rand_util_win.cc.
28 std::atomic<bool> g_use_boringssl;
29 
30 BASE_FEATURE(kUseBoringSSLForRandBytes,
31              "UseBoringSSLForRandBytes",
32              FEATURE_DISABLED_BY_DEFAULT);
33 
34 }  // namespace
35 
ConfigureBoringSSLBackedRandBytesFieldTrial()36 void ConfigureBoringSSLBackedRandBytesFieldTrial() {
37   g_use_boringssl.store(FeatureList::IsEnabled(kUseBoringSSLForRandBytes),
38                         std::memory_order_relaxed);
39 }
40 
UseBoringSSLForRandBytes()41 bool UseBoringSSLForRandBytes() {
42   return g_use_boringssl.load(std::memory_order_relaxed);
43 }
44 
45 }  // namespace internal
46 
RandBytes(span<uint8_t> output)47 void RandBytes(span<uint8_t> output) {
48   if (internal::UseBoringSSLForRandBytes()) {
49     // BoringSSL's RAND_bytes always returns 1. Any error aborts the program.
50     (void)RAND_bytes(output.data(), output.size());
51     return;
52   }
53 
54   zx_cprng_draw(output.data(), output.size());
55 }
56 
57 namespace internal {
58 
RandDoubleAvoidAllocation()59 double RandDoubleAvoidAllocation() {
60   uint64_t number;
61   zx_cprng_draw(&number, sizeof(number));
62   // This transformation is explained in rand_util.cc.
63   return (number >> 11) * 0x1.0p-53;
64 }
65 
66 }  // namespace internal
67 
68 }  // namespace base
69