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/pool_urbg.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/endian.h"
27 #include "absl/base/internal/raw_logging.h"
28 #include "absl/base/internal/spinlock.h"
29 #include "absl/base/internal/sysinfo.h"
30 #include "absl/base/internal/unaligned_access.h"
31 #include "absl/base/optimization.h"
32 #include "absl/random/internal/randen.h"
33 #include "absl/random/internal/seed_material.h"
34 #include "absl/random/seed_gen_exception.h"
35
36 using absl::base_internal::SpinLock;
37 using absl::base_internal::SpinLockHolder;
38
39 namespace absl {
40 ABSL_NAMESPACE_BEGIN
41 namespace random_internal {
42 namespace {
43
44 // RandenPoolEntry is a thread-safe pseudorandom bit generator, implementing a
45 // single generator within a RandenPool<T>. It is an internal implementation
46 // detail, and does not aim to conform to [rand.req.urng].
47 //
48 // NOTE: There are alignment issues when used on ARM, for instance.
49 // See the allocation code in PoolAlignedAlloc().
50 class RandenPoolEntry {
51 public:
52 static constexpr size_t kState = RandenTraits::kStateBytes / sizeof(uint32_t);
53 static constexpr size_t kCapacity =
54 RandenTraits::kCapacityBytes / sizeof(uint32_t);
55
Init(absl::Span<const uint32_t> data)56 void Init(absl::Span<const uint32_t> data) {
57 SpinLockHolder l(&mu_); // Always uncontested.
58 std::copy(data.begin(), data.end(), std::begin(state_));
59 next_ = kState;
60 }
61
62 // Copy bytes into out.
63 void Fill(uint8_t* out, size_t bytes) ABSL_LOCKS_EXCLUDED(mu_);
64
65 // Returns random bits from the buffer in units of T.
66 template <typename T>
67 inline T Generate() ABSL_LOCKS_EXCLUDED(mu_);
68
MaybeRefill()69 inline void MaybeRefill() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
70 if (next_ >= kState) {
71 next_ = kCapacity;
72 impl_.Generate(state_);
73 }
74 }
75
76 private:
77 // Randen URBG state.
78 uint32_t state_[kState] ABSL_GUARDED_BY(mu_); // First to satisfy alignment.
79 SpinLock mu_;
80 const Randen impl_;
81 size_t next_ ABSL_GUARDED_BY(mu_);
82 };
83
84 template <>
Generate()85 inline uint8_t RandenPoolEntry::Generate<uint8_t>() {
86 SpinLockHolder l(&mu_);
87 MaybeRefill();
88 return static_cast<uint8_t>(state_[next_++]);
89 }
90
91 template <>
Generate()92 inline uint16_t RandenPoolEntry::Generate<uint16_t>() {
93 SpinLockHolder l(&mu_);
94 MaybeRefill();
95 return static_cast<uint16_t>(state_[next_++]);
96 }
97
98 template <>
Generate()99 inline uint32_t RandenPoolEntry::Generate<uint32_t>() {
100 SpinLockHolder l(&mu_);
101 MaybeRefill();
102 return state_[next_++];
103 }
104
105 template <>
Generate()106 inline uint64_t RandenPoolEntry::Generate<uint64_t>() {
107 SpinLockHolder l(&mu_);
108 if (next_ >= kState - 1) {
109 next_ = kCapacity;
110 impl_.Generate(state_);
111 }
112 auto p = state_ + next_;
113 next_ += 2;
114
115 uint64_t result;
116 std::memcpy(&result, p, sizeof(result));
117 return result;
118 }
119
Fill(uint8_t * out,size_t bytes)120 void RandenPoolEntry::Fill(uint8_t* out, size_t bytes) {
121 SpinLockHolder l(&mu_);
122 while (bytes > 0) {
123 MaybeRefill();
124 size_t remaining = (kState - next_) * sizeof(state_[0]);
125 size_t to_copy = std::min(bytes, remaining);
126 std::memcpy(out, &state_[next_], to_copy);
127 out += to_copy;
128 bytes -= to_copy;
129 next_ += (to_copy + sizeof(state_[0]) - 1) / sizeof(state_[0]);
130 }
131 }
132
133 // Number of pooled urbg entries.
134 static constexpr int kPoolSize = 8;
135
136 // Shared pool entries.
137 static absl::once_flag pool_once;
138 ABSL_CACHELINE_ALIGNED static RandenPoolEntry* shared_pools[kPoolSize];
139
140 // Returns an id in the range [0 ... kPoolSize), which indexes into the
141 // pool of random engines.
142 //
143 // Each thread to access the pool is assigned a sequential ID (without reuse)
144 // from the pool-id space; the id is cached in a thread_local variable.
145 // This id is assigned based on the arrival-order of the thread to the
146 // GetPoolID call; this has no binary, CL, or runtime stability because
147 // on subsequent runs the order within the same program may be significantly
148 // different. However, as other thread IDs are not assigned sequentially,
149 // this is not expected to matter.
GetPoolID()150 int GetPoolID() {
151 static_assert(kPoolSize >= 1,
152 "At least one urbg instance is required for PoolURBG");
153
154 ABSL_CONST_INIT static std::atomic<int64_t> sequence{0};
155
156 #ifdef ABSL_HAVE_THREAD_LOCAL
157 static thread_local int my_pool_id = -1;
158 if (ABSL_PREDICT_FALSE(my_pool_id < 0)) {
159 my_pool_id = (sequence++ % kPoolSize);
160 }
161 return my_pool_id;
162 #else
163 static pthread_key_t tid_key = [] {
164 pthread_key_t tmp_key;
165 int err = pthread_key_create(&tmp_key, nullptr);
166 if (err) {
167 ABSL_RAW_LOG(FATAL, "pthread_key_create failed with %d", err);
168 }
169 return tmp_key;
170 }();
171
172 // Store the value in the pthread_{get/set}specific. However an uninitialized
173 // value is 0, so add +1 to distinguish from the null value.
174 intptr_t my_pool_id =
175 reinterpret_cast<intptr_t>(pthread_getspecific(tid_key));
176 if (ABSL_PREDICT_FALSE(my_pool_id == 0)) {
177 // No allocated ID, allocate the next value, cache it, and return.
178 my_pool_id = (sequence++ % kPoolSize) + 1;
179 int err = pthread_setspecific(tid_key, reinterpret_cast<void*>(my_pool_id));
180 if (err) {
181 ABSL_RAW_LOG(FATAL, "pthread_setspecific failed with %d", err);
182 }
183 }
184 return my_pool_id - 1;
185 #endif
186 }
187
188 // Allocate a RandenPoolEntry with at least 32-byte alignment, which is required
189 // by ARM platform code.
PoolAlignedAlloc()190 RandenPoolEntry* PoolAlignedAlloc() {
191 constexpr size_t kAlignment =
192 ABSL_CACHELINE_SIZE > 32 ? ABSL_CACHELINE_SIZE : 32;
193
194 // Not all the platforms that we build for have std::aligned_alloc, however
195 // since we never free these objects, we can over allocate and munge the
196 // pointers to the correct alignment.
197 void* memory = std::malloc(sizeof(RandenPoolEntry) + kAlignment);
198 auto x = reinterpret_cast<intptr_t>(memory);
199 auto y = x % kAlignment;
200 void* aligned =
201 (y == 0) ? memory : reinterpret_cast<void*>(x + kAlignment - y);
202 return new (aligned) RandenPoolEntry();
203 }
204
205 // Allocate and initialize kPoolSize objects of type RandenPoolEntry.
206 //
207 // The initialization strategy is to initialize one object directly from
208 // OS entropy, then to use that object to seed all of the individual
209 // pool instances.
InitPoolURBG()210 void InitPoolURBG() {
211 static constexpr size_t kSeedSize =
212 RandenTraits::kStateBytes / sizeof(uint32_t);
213 // Read the seed data from OS entropy once.
214 uint32_t seed_material[kPoolSize * kSeedSize];
215 if (!random_internal::ReadSeedMaterialFromOSEntropy(
216 absl::MakeSpan(seed_material))) {
217 random_internal::ThrowSeedGenException();
218 }
219 for (int i = 0; i < kPoolSize; i++) {
220 shared_pools[i] = PoolAlignedAlloc();
221 shared_pools[i]->Init(
222 absl::MakeSpan(&seed_material[i * kSeedSize], kSeedSize));
223 }
224 }
225
226 // Returns the pool entry for the current thread.
GetPoolForCurrentThread()227 RandenPoolEntry* GetPoolForCurrentThread() {
228 absl::call_once(pool_once, InitPoolURBG);
229 return shared_pools[GetPoolID()];
230 }
231
232 } // namespace
233
234 template <typename T>
Generate()235 typename RandenPool<T>::result_type RandenPool<T>::Generate() {
236 auto* pool = GetPoolForCurrentThread();
237 return pool->Generate<T>();
238 }
239
240 template <typename T>
Fill(absl::Span<result_type> data)241 void RandenPool<T>::Fill(absl::Span<result_type> data) {
242 auto* pool = GetPoolForCurrentThread();
243 pool->Fill(reinterpret_cast<uint8_t*>(data.data()),
244 data.size() * sizeof(result_type));
245 }
246
247 template class RandenPool<uint8_t>;
248 template class RandenPool<uint16_t>;
249 template class RandenPool<uint32_t>;
250 template class RandenPool<uint64_t>;
251
252 } // namespace random_internal
253 ABSL_NAMESPACE_END
254 } // namespace absl
255