rand/rngs/
thread.rs

1// Copyright 2018 Developers of the Rand project.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Thread-local random number generator
10
11use core::{cell::UnsafeCell, convert::Infallible};
12use std::fmt;
13use std::rc::Rc;
14use std::thread_local;
15
16use super::{SysError, SysRng};
17use rand_core::SeedableRng;
18use rand_core::block::{BlockRng, Generator};
19use rand_core::{TryCryptoRng, TryRng};
20
21// Rationale for using `UnsafeCell` in `ThreadRng`:
22//
23// Previously we used a `RefCell`, with an overhead of ~15%. There will only
24// ever be one mutable reference to the interior of the `UnsafeCell`, because
25// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a
26// single thread (which is the definition of `ThreadRng`), there will only ever
27// be one of these methods active at a time.
28//
29// A possible scenario where there could be multiple mutable references is if
30// `ThreadRng` is used inside `next_u32` and co. But the implementation is
31// completely under our control. We just have to ensure none of them use
32// `ThreadRng` internally, which is nonsensical anyway. We should also never run
33// `ThreadRng` in destructors of its implementation, which is also nonsensical.
34
35// Number of generated bytes after which to reseed `ThreadRng`.
36// According to benchmarks, reseeding has a noticeable impact with thresholds
37// of 32 kB and less. We choose 64 kiB output to avoid significant overhead;
38// since a block consists of 16 4-byte words this equals 1024 blocks.
39const RESEED_BLOCK_THRESHOLD: u64 = 1024;
40
41type Core = chacha20::ChaChaCore<chacha20::R12, chacha20::variants::Legacy>;
42type Results = <Core as Generator>::Output;
43
44struct ReseedingCore {
45    inner: Core,
46}
47
48impl Generator for ReseedingCore {
49    type Output = Results;
50
51    #[inline(always)]
52    fn generate(&mut self, results: &mut Results) {
53        if self.inner.get_block_pos() >= RESEED_BLOCK_THRESHOLD {
54            self.try_to_reseed();
55        }
56        self.inner.generate(results);
57    }
58}
59
60impl ReseedingCore {
61    /// Reseed the internal PRNG.
62    fn reseed(&mut self) -> Result<(), SysError> {
63        Core::try_from_rng(&mut SysRng).map(|result| self.inner = result)
64    }
65
66    #[cold]
67    #[inline(never)]
68    fn try_to_reseed(&mut self) {
69        trace!("Reseeding RNG (periodic reseed)");
70
71        if let Err(e) = self.reseed() {
72            warn!("Reseeding RNG failed: {e}");
73        }
74    }
75}
76
77/// A reference to the thread-local generator
78///
79/// This type is a reference to a lazily-initialized thread-local generator.
80/// An instance can be obtained via [`rand::rng()`][crate::rng()] or via
81/// [`ThreadRng::default()`].
82/// The handle cannot be passed between threads (is not `Send` or `Sync`).
83///
84/// # Security
85///
86/// Security must be considered relative to a threat model and validation
87/// requirements. The Rand project can provide no guarantee of fitness for
88/// purpose. The design criteria for `ThreadRng` are as follows:
89///
90/// - Automatic seeding via [`SysRng`] and after every 64 kB of output.
91///   Limitation: there is no automatic reseeding on process fork (see [below](#fork)).
92/// - A rigorusly analyzed, unpredictable (cryptographic) pseudo-random generator
93///   (see [the book on security](https://rust-random.github.io/book/guide-rngs.html#security)).
94///   The currently selected algorithm is ChaCha (12-rounds).
95///   See also [`StdRng`] documentation.
96/// - Not to leak internal state through [`Debug`] or serialization
97///   implementations.
98/// - No further protections exist to in-memory state. In particular, the
99///   implementation is not required to zero memory on exit (of the process or
100///   thread). (This may change in the future.)
101/// - Be fast enough for general-purpose usage. Note in particular that
102///   `ThreadRng` is designed to be a "fast, reasonably secure generator"
103///   (where "reasonably secure" implies the above criteria).
104///
105/// We leave it to the user to determine whether this generator meets their
106/// security requirements. For an alternative, see [`SysRng`].
107///
108/// # Fork
109///
110/// `ThreadRng` is not automatically reseeded on fork. It is recommended to
111/// explicitly call [`ThreadRng::reseed`] immediately after a fork, for example:
112/// ```ignore
113/// fn do_fork() {
114///     let pid = unsafe { libc::fork() };
115///     if pid == 0 {
116///         // Reseed ThreadRng in child processes:
117///         rand::rng().reseed();
118///     }
119/// }
120/// ```
121///
122/// Methods on `ThreadRng` are not reentrant-safe and thus should not be called
123/// from an interrupt (e.g. a fork handler) unless it can be guaranteed that no
124/// other method on the same `ThreadRng` is currently executing.
125///
126/// [`StdRng`]: crate::rngs::StdRng
127#[derive(Clone)]
128pub struct ThreadRng {
129    // Rc is explicitly !Send and !Sync
130    rng: Rc<UnsafeCell<BlockRng<ReseedingCore>>>,
131}
132
133impl ThreadRng {
134    /// Immediately reseed the generator
135    ///
136    /// This discards any remaining random data in the cache.
137    pub fn reseed(&mut self) -> Result<(), SysError> {
138        // SAFETY: We must make sure to stop using `rng` before anyone else
139        // creates another mutable reference
140        let rng = unsafe { &mut *self.rng.get() };
141        rng.reset_and_skip(0);
142        rng.core.reseed()
143    }
144}
145
146/// Debug implementation does not leak internal state
147impl fmt::Debug for ThreadRng {
148    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
149        write!(fmt, "ThreadRng {{ .. }}")
150    }
151}
152
153thread_local!(
154    // We require Rc<..> to avoid premature freeing when ThreadRng is used
155    // within thread-local destructors. See #968.
156    static THREAD_RNG_KEY: Rc<UnsafeCell<BlockRng<ReseedingCore>>> = {
157        Rc::new(UnsafeCell::new(BlockRng::new(ReseedingCore {
158            inner: Core::try_from_rng(&mut SysRng).unwrap_or_else(|err| {
159                panic!("could not initialize ThreadRng: {}", err)
160            }),
161        })))
162    }
163);
164
165/// Access a fast, pre-initialized generator
166///
167/// This is a handle to the local [`ThreadRng`].
168///
169/// See also [`crate::rngs`] for alternatives.
170///
171/// # Example
172///
173/// ```
174/// use rand::prelude::*;
175///
176/// # fn main() {
177///
178/// let mut numbers = [1, 2, 3, 4, 5];
179/// numbers.shuffle(&mut rand::rng());
180/// println!("Numbers: {numbers:?}");
181///
182/// // Using a local binding avoids an initialization-check on each usage:
183/// let mut rng = rand::rng();
184///
185/// println!("True or false: {}", rng.random::<bool>());
186/// println!("A simulated die roll: {}", rng.random_range(1..=6));
187/// # }
188/// ```
189///
190/// # Security
191///
192/// Refer to [`ThreadRng#Security`].
193pub fn rng() -> ThreadRng {
194    let rng = THREAD_RNG_KEY.with(|t| t.clone());
195    ThreadRng { rng }
196}
197
198impl Default for ThreadRng {
199    fn default() -> ThreadRng {
200        rng()
201    }
202}
203
204impl TryRng for ThreadRng {
205    type Error = Infallible;
206
207    #[inline(always)]
208    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
209        // SAFETY: We must make sure to stop using `rng` before anyone else
210        // creates another mutable reference
211        let rng = unsafe { &mut *self.rng.get() };
212        Ok(rng.next_word())
213    }
214
215    #[inline(always)]
216    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
217        // SAFETY: We must make sure to stop using `rng` before anyone else
218        // creates another mutable reference
219        let rng = unsafe { &mut *self.rng.get() };
220        Ok(rng.next_u64_from_u32())
221    }
222
223    #[inline(always)]
224    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
225        // SAFETY: We must make sure to stop using `rng` before anyone else
226        // creates another mutable reference
227        let rng = unsafe { &mut *self.rng.get() };
228        rng.fill_bytes(dest);
229        Ok(())
230    }
231}
232
233impl TryCryptoRng for ThreadRng {}
234
235#[cfg(test)]
236mod test {
237    #[test]
238    fn test_thread_rng() {
239        use crate::RngExt;
240        let mut r = crate::rng();
241        r.random::<i32>();
242        assert_eq!(r.random_range(0..1), 0);
243    }
244
245    #[test]
246    fn test_debug_output() {
247        // We don't care about the exact output here, but it must not include
248        // private CSPRNG state or the cache stored by BlockRng!
249        assert_eq!(std::format!("{:?}", crate::rng()), "ThreadRng { .. }");
250    }
251}