• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/random/internal/entropy_pool.h"
16 
17 #include <algorithm>
18 #include <atomic>
19 #include <cstdint>
20 #include <cstring>
21 #include <iterator>
22 
23 #include "absl/base/attributes.h"
24 #include "absl/base/call_once.h"
25 #include "absl/base/config.h"
26 #include "absl/base/internal/spinlock.h"
27 #include "absl/base/optimization.h"
28 #include "absl/base/thread_annotations.h"
29 #include "absl/random/internal/randen.h"
30 #include "absl/random/internal/randen_traits.h"
31 #include "absl/random/internal/seed_material.h"
32 #include "absl/random/seed_gen_exception.h"
33 #include "absl/types/span.h"
34 
35 using absl::base_internal::SpinLock;
36 using absl::base_internal::SpinLockHolder;
37 
38 namespace absl {
39 ABSL_NAMESPACE_BEGIN
40 namespace random_internal {
41 namespace {
42 
43 // RandenPoolEntry is a thread-safe pseudorandom bit generator, implementing a
44 // single generator within a RandenPool<T>. It is an internal implementation
45 // detail, and does not aim to conform to [rand.req.urng].
46 //
47 // NOTE: There are alignment issues when used on ARM, for instance.
48 // See the allocation code in PoolAlignedAlloc().
49 class RandenPoolEntry {
50  public:
51   static constexpr size_t kState = RandenTraits::kStateBytes / sizeof(uint32_t);
52   static constexpr size_t kCapacity =
53       RandenTraits::kCapacityBytes / sizeof(uint32_t);
54 
Init(absl::Span<const uint32_t> data)55   void Init(absl::Span<const uint32_t> data) {
56     SpinLockHolder l(&mu_);  // Always uncontested.
57     std::copy(data.begin(), data.end(), std::begin(state_));
58     next_ = kState;
59   }
60 
61   // Copy bytes into out.
62   void Fill(uint8_t* out, size_t bytes) ABSL_LOCKS_EXCLUDED(mu_);
63 
MaybeRefill()64   inline void MaybeRefill() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
65     if (next_ >= kState) {
66       next_ = kCapacity;
67       impl_.Generate(state_);
68     }
69   }
70 
available() const71   inline size_t available() const ABSL_SHARED_LOCKS_REQUIRED(mu_) {
72     return kState - next_;
73   }
74 
75  private:
76   // Randen URBG state.
77   uint32_t state_[kState] ABSL_GUARDED_BY(mu_);  // First to satisfy alignment.
78   SpinLock mu_;
79   const Randen impl_;
80   size_t next_ ABSL_GUARDED_BY(mu_);
81 };
82 
Fill(uint8_t * out,size_t bytes)83 void RandenPoolEntry::Fill(uint8_t* out, size_t bytes) {
84   SpinLockHolder l(&mu_);
85   while (bytes > 0) {
86     MaybeRefill();
87     size_t remaining = available() * sizeof(state_[0]);
88     size_t to_copy = std::min(bytes, remaining);
89     std::memcpy(out, &state_[next_], to_copy);
90     out += to_copy;
91     bytes -= to_copy;
92     next_ += (to_copy + sizeof(state_[0]) - 1) / sizeof(state_[0]);
93   }
94 }
95 
96 // Number of pooled urbg entries.
97 static constexpr size_t kPoolSize = 8;
98 
99 // Shared pool entries.
100 static absl::once_flag pool_once;
101 ABSL_CACHELINE_ALIGNED static RandenPoolEntry* shared_pools[kPoolSize];
102 
103 // Returns an id in the range [0 ... kPoolSize), which indexes into the
104 // pool of random engines.
105 //
106 // Each thread to access the pool is assigned a sequential ID (without reuse)
107 // from the pool-id space; the id is cached in a thread_local variable.
108 // This id is assigned based on the arrival-order of the thread to the
109 // GetPoolID call; this has no binary, CL, or runtime stability because
110 // on subsequent runs the order within the same program may be significantly
111 // different. However, as other thread IDs are not assigned sequentially,
112 // this is not expected to matter.
GetPoolID()113 size_t GetPoolID() {
114   static_assert(kPoolSize >= 1,
115                 "At least one urbg instance is required for PoolURBG");
116 
117   ABSL_CONST_INIT static std::atomic<uint64_t> sequence{0};
118 
119 #ifdef ABSL_HAVE_THREAD_LOCAL
120   static thread_local size_t my_pool_id = kPoolSize;
121   if (ABSL_PREDICT_FALSE(my_pool_id == kPoolSize)) {
122     my_pool_id = (sequence++ % kPoolSize);
123   }
124   return my_pool_id;
125 #else
126   static pthread_key_t tid_key = [] {
127     pthread_key_t tmp_key;
128     int err = pthread_key_create(&tmp_key, nullptr);
129     if (err) {
130       ABSL_RAW_LOG(FATAL, "pthread_key_create failed with %d", err);
131     }
132     return tmp_key;
133   }();
134 
135   // Store the value in the pthread_{get/set}specific. However an uninitialized
136   // value is 0, so add +1 to distinguish from the null value.
137   uintptr_t my_pool_id =
138       reinterpret_cast<uintptr_t>(pthread_getspecific(tid_key));
139   if (ABSL_PREDICT_FALSE(my_pool_id == 0)) {
140     // No allocated ID, allocate the next value, cache it, and return.
141     my_pool_id = (sequence++ % kPoolSize) + 1;
142     int err = pthread_setspecific(tid_key, reinterpret_cast<void*>(my_pool_id));
143     if (err) {
144       ABSL_RAW_LOG(FATAL, "pthread_setspecific failed with %d", err);
145     }
146   }
147   return my_pool_id - 1;
148 #endif
149 }
150 
151 // Allocate a RandenPoolEntry with at least 32-byte alignment, which is required
152 // by ARM platform code.
PoolAlignedAlloc()153 RandenPoolEntry* PoolAlignedAlloc() {
154   constexpr size_t kAlignment =
155       ABSL_CACHELINE_SIZE > 32 ? ABSL_CACHELINE_SIZE : 32;
156 
157   // Not all the platforms that we build for have std::aligned_alloc, however
158   // since we never free these objects, we can over allocate and munge the
159   // pointers to the correct alignment.
160   uintptr_t x = reinterpret_cast<uintptr_t>(
161       new char[sizeof(RandenPoolEntry) + kAlignment]);
162   auto y = x % kAlignment;
163   void* aligned = reinterpret_cast<void*>(y == 0 ? x : (x + kAlignment - y));
164   return new (aligned) RandenPoolEntry();
165 }
166 
167 // Allocate and initialize kPoolSize objects of type RandenPoolEntry.
InitPoolURBG()168 void InitPoolURBG() {
169   static constexpr size_t kSeedSize =
170       RandenTraits::kStateBytes / sizeof(uint32_t);
171   // Read OS entropy once, and use it to initialize each pool entry.
172   uint32_t seed_material[kPoolSize * kSeedSize];
173   if (!ReadSeedMaterialFromOSEntropy(absl::MakeSpan(seed_material))) {
174     ThrowSeedGenException();
175   }
176   for (size_t i = 0; i < kPoolSize; i++) {
177     shared_pools[i] = PoolAlignedAlloc();
178     shared_pools[i]->Init(
179         absl::MakeSpan(&seed_material[i * kSeedSize], kSeedSize));
180   }
181 }
182 
183 // Returns the pool entry for the current thread.
GetPoolForCurrentThread()184 RandenPoolEntry* GetPoolForCurrentThread() {
185   absl::call_once(pool_once, InitPoolURBG);
186   return shared_pools[GetPoolID()];
187 }
188 
189 }  // namespace
190 
GetEntropyFromRandenPool(void * dest,size_t bytes)191 void GetEntropyFromRandenPool(void* dest, size_t bytes) {
192   auto* pool = GetPoolForCurrentThread();
193   pool->Fill(reinterpret_cast<uint8_t*>(dest), bytes);
194 }
195 
196 }  // namespace random_internal
197 ABSL_NAMESPACE_END
198 }  // namespace absl
199