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;
12use std::rc::Rc;
13use std::thread_local;
14
15use super::std::Core;
16use crate::rngs::adapter::ReseedingRng;
17use crate::rngs::OsRng;
18use crate::{CryptoRng, Error, RngCore, SeedableRng};
19
20// Rationale for using `UnsafeCell` in `ThreadRng`:
21//
22// Previously we used a `RefCell`, with an overhead of ~15%. There will only
23// ever be one mutable reference to the interior of the `UnsafeCell`, because
24// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a
25// single thread (which is the definition of `ThreadRng`), there will only ever
26// be one of these methods active at a time.
27//
28// A possible scenario where there could be multiple mutable references is if
29// `ThreadRng` is used inside `next_u32` and co. But the implementation is
30// completely under our control. We just have to ensure none of them use
31// `ThreadRng` internally, which is nonsensical anyway. We should also never run
32// `ThreadRng` in destructors of its implementation, which is also nonsensical.
33
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 kB to avoid significant overhead.
38const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64;
39
40/// A reference to the thread-local generator
41///
42/// An instance can be obtained via [`thread_rng`] or via `ThreadRng::default()`.
43/// This handle is safe to use everywhere (including thread-local destructors),
44/// though it is recommended not to use inside a fork handler.
45/// The handle cannot be passed between threads (is not `Send` or `Sync`).
46///
47/// `ThreadRng` uses the same PRNG as [`StdRng`] for security and performance
48/// and is automatically seeded from [`OsRng`].
49///
50/// Unlike `StdRng`, `ThreadRng` uses the [`ReseedingRng`] wrapper to reseed
51/// the PRNG from fresh entropy every 64 kiB of random data as well as after a
52/// fork on Unix (though not quite immediately; see documentation of
53/// [`ReseedingRng`]).
54/// Note that the reseeding is done as an extra precaution against side-channel
55/// attacks and mis-use (e.g. if somehow weak entropy were supplied initially).
56/// The PRNG algorithms used are assumed to be secure.
57///
58/// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng
59/// [`StdRng`]: crate::rngs::StdRng
60#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))]
61#[derive(Clone, Debug)]
62pub struct ThreadRng {
63 // Rc is explicitly !Send and !Sync
64 rng: Rc<UnsafeCell<ReseedingRng<Core, OsRng>>>,
65}
66
67thread_local!(
68 // We require Rc<..> to avoid premature freeing when thread_rng is used
69 // within thread-local destructors. See #968.
70 static THREAD_RNG_KEY: Rc<UnsafeCell<ReseedingRng<Core, OsRng>>> = {
71 let r = Core::from_rng(OsRng).unwrap_or_else(|err|
72 panic!("could not initialize thread_rng: {}", err));
73 let rng = ReseedingRng::new(r,
74 THREAD_RNG_RESEED_THRESHOLD,
75 OsRng);
76 Rc::new(UnsafeCell::new(rng))
77 }
78);
79
80/// Retrieve the lazily-initialized thread-local random number generator,
81/// seeded by the system. Intended to be used in method chaining style,
82/// e.g. `thread_rng().gen::<i32>()`, or cached locally, e.g.
83/// `let mut rng = thread_rng();`. Invoked by the `Default` trait, making
84/// `ThreadRng::default()` equivalent.
85///
86/// For more information see [`ThreadRng`].
87#[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))]
88pub fn thread_rng() -> ThreadRng {
89 let rng: Rc>> = THREAD_RNG_KEY.with(|t: &Rc>>| t.clone());
90 ThreadRng { rng }
91}
92
93impl Default for ThreadRng {
94 fn default() -> ThreadRng {
95 crate::prelude::thread_rng()
96 }
97}
98
99impl RngCore for ThreadRng {
100 #[inline(always)]
101 fn next_u32(&mut self) -> u32 {
102 // SAFETY: We must make sure to stop using `rng` before anyone else
103 // creates another mutable reference
104 let rng = unsafe { &mut *self.rng.get() };
105 rng.next_u32()
106 }
107
108 #[inline(always)]
109 fn next_u64(&mut self) -> u64 {
110 // SAFETY: We must make sure to stop using `rng` before anyone else
111 // creates another mutable reference
112 let rng = unsafe { &mut *self.rng.get() };
113 rng.next_u64()
114 }
115
116 fn fill_bytes(&mut self, dest: &mut [u8]) {
117 // SAFETY: We must make sure to stop using `rng` before anyone else
118 // creates another mutable reference
119 let rng = unsafe { &mut *self.rng.get() };
120 rng.fill_bytes(dest)
121 }
122
123 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
124 // SAFETY: We must make sure to stop using `rng` before anyone else
125 // creates another mutable reference
126 let rng = unsafe { &mut *self.rng.get() };
127 rng.try_fill_bytes(dest)
128 }
129}
130
131impl CryptoRng for ThreadRng {}
132
133
134#[cfg(test)]
135mod test {
136 #[test]
137 fn test_thread_rng() {
138 use crate::Rng;
139 let mut r = crate::thread_rng();
140 r.gen::<i32>();
141 assert_eq!(r.gen_range(0..1), 0);
142 }
143}
144