diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fadd73f4aa2..ff422a2e4d2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,6 +23,8 @@ jobs: toolchain: nightly - name: rand run: cargo doc --all-features --no-deps + - name: thread_rng + run: cargo doc --all-features --package rand_trng --no-deps - name: rand_core run: cargo doc --all-features --package rand_core --no-deps - name: rand_distr @@ -95,7 +97,10 @@ jobs: cargo test --target ${{ matrix.target }} --examples - name: Test rand (all stable features) run: | - cargo test --target ${{ matrix.target }} --features=serde,log,small_rng + cargo test --target ${{ matrix.target }} --features=serde,log,small_rng,thread_rng + - name: Test thread_rng + run: | + cargo test --target ${{ matrix.target }} --manifest-path rand_trng/Cargo.toml - name: Test rand_core run: | cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml @@ -140,6 +145,7 @@ jobs: # all stable features: cross test --no-fail-fast --target ${{ matrix.target }} --features=serde,log,small_rng cross test --no-fail-fast --target ${{ matrix.target }} --examples + cross test --no-fail-fast --target ${{ matrix.target }} --manifest-path rand_trng/Cargo.toml cross test --no-fail-fast --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml cross test --no-fail-fast --target ${{ matrix.target }} --manifest-path rand_distr/Cargo.toml --features=serde cross test --no-fail-fast --target ${{ matrix.target }} --manifest-path rand_pcg/Cargo.toml --features=serde @@ -157,7 +163,8 @@ jobs: - name: Test rand run: | cargo miri test --no-default-features --lib --tests - cargo miri test --features=log,small_rng + cargo miri test --features=log,small_rng,thread_rng + cargo miri test --manifest-path rand_trng/Cargo.toml cargo miri test --manifest-path rand_core/Cargo.toml cargo miri test --manifest-path rand_core/Cargo.toml --features=serde cargo miri test --manifest-path rand_core/Cargo.toml --no-default-features diff --git a/Cargo.toml b/Cargo.toml index 1f2eccdc638..7446341f16c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ features = ["small_rng", "serde"] [features] # Meta-features: -default = ["std", "std_rng", "getrandom", "small_rng"] +default = ["std", "std_rng", "getrandom", "small_rng", "thread_rng"] nightly = [] # some additions requiring nightly Rust serde = ["dep:serde", "rand_core/serde"] @@ -45,6 +45,9 @@ getrandom = ["rand_core/getrandom"] # Option (requires nightly Rust): experimental SIMD support simd_support = ["zerocopy/simd-nightly"] +# Option (enabled by default): enable ThreadRng +thread_rng = ["rand_trng", "std"] + # Option (enabled by default): enable StdRng std_rng = ["dep:rand_chacha"] @@ -65,6 +68,7 @@ members = [ "rand_distr", "rand_chacha", "rand_pcg", + "rand_trng", ] exclude = ["benches"] @@ -72,6 +76,7 @@ exclude = ["benches"] rand_core = { path = "rand_core", version = "=0.9.0-alpha.1", default-features = false } log = { version = "0.4.4", optional = true } serde = { version = "1.0.103", features = ["derive"], optional = true } +rand_trng = { version = "0.9.0", path = "rand_trng", optional = true } rand_chacha = { path = "rand_chacha", version = "=0.9.0-alpha.1", default-features = false, optional = true } zerocopy = { version = "0.8.0", default-features = false, features = ["simd"] } diff --git a/rand_trng/Cargo.toml b/rand_trng/Cargo.toml new file mode 100644 index 00000000000..87c312cb841 --- /dev/null +++ b/rand_trng/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "rand_trng" +version = "0.9.0" +authors = ["The Rand Project Developers"] +license = "MIT OR Apache-2.0" +readme = "README.md" +repository = "https://github.com/rust-random/rand" +documentation = "https://docs.rs/thread-rng" +description = "Lazily-initialized thread-local random number generator" +keywords = ["random", "rng"] +categories = ["algorithms", "no-std"] +autobenches = true +edition = "2021" +rust-version = "1.61" + +[dependencies] +rand_chacha = { path = "../rand_chacha", version = "=0.9.0-alpha.1", features = ["getrandom", "std"] } diff --git a/rand_trng/LICENSE-APACHE b/rand_trng/LICENSE-APACHE new file mode 100644 index 00000000000..455787c2334 --- /dev/null +++ b/rand_trng/LICENSE-APACHE @@ -0,0 +1,187 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. diff --git a/rand_trng/LICENSE-MIT b/rand_trng/LICENSE-MIT new file mode 100644 index 00000000000..195285fe967 --- /dev/null +++ b/rand_trng/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright 2024 Developers of the Rand project + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/rand_trng/README.md b/rand_trng/README.md new file mode 100644 index 00000000000..6da0400baea --- /dev/null +++ b/rand_trng/README.md @@ -0,0 +1,21 @@ +# rand_trng: lazily-initialized thread-local random number generator + +[![Test Status](https://github.com/rust-random/rand/workflows/Tests/badge.svg?event=push)](https://github.com/rust-random/rand/actions) +[![Latest version](https://img.shields.io/crates/v/rand_trng.svg)](https://crates.io/crates/rand_trng) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://docs.rs/rand_trng/badge.svg)](https://docs.rs/rand_trng) + +## License + +The crate is licensed under either of: + +* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) +* [MIT license](http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/rand_trng/src/lib.rs b/rand_trng/src/lib.rs new file mode 100644 index 00000000000..ea02dfd0f3b --- /dev/null +++ b/rand_trng/src/lib.rs @@ -0,0 +1,200 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Thread-local random number generator + +use core::cell::UnsafeCell; +use std::fmt; +use std::rc::Rc; +use std::thread_local; + +pub use rand_chacha::rand_core::{self, CryptoRng, RngCore}; + +use rand_chacha::{rand_core::SeedableRng, ChaCha12Rng}; + +// Number of generated bytes after which to reseed `ThreadRng`. +// According to benchmarks, reseeding has a noticeable impact with thresholds +// of 32 kB and less. We choose 64 kB to avoid significant overhead. +const RESEED_THRESHOLD: isize = 1024 * 64; + +struct InnerState { + rng: ChaCha12Rng, + bytes_until_reseed: isize, +} + +impl InnerState { + #[inline(always)] + fn reseed(&mut self) -> Result<(), rand_core::getrandom::Error> { + self.bytes_until_reseed = RESEED_THRESHOLD; + self.rng = ChaCha12Rng::try_from_os_rng()?; + Ok(()) + } + + #[inline(always)] + fn reseed_check(&mut self, n: isize) { + if self.bytes_until_reseed < 0 { + // If system RNG has failed for some reason, ignore the error + // and continue to work with the old RNG state. + let _ = self.reseed(); + } + self.bytes_until_reseed -= n; + } +} + +thread_local!( + // We require Rc<..> to avoid premature freeing when ThreadRng is used + // within thread-local destructors. See https://github.com/rust-random/rand/issues/968. + // + // Rationale for using `UnsafeCell`: + // + // Previously we used a `RefCell`, with an overhead of ~15%. There will only + // ever be one mutable reference to the interior of the `UnsafeCell`, because + // we only have such a reference inside `next_u32`, `next_u64`, etc. Within a + // single thread (which is the definition of `ThreadRng`), there will only ever + // be one of these methods active at a time. + // + // A possible scenario where there could be multiple mutable references is if + // `ThreadRng` is used inside `next_u32` and co. But the implementation is + // completely under our control. We just have to ensure none of them use + // `ThreadRng` internally, which is nonsensical anyway. We should also never run + // `ThreadRng` in destructors of its implementation, which is also nonsensical. + static THREAD_RNG_KEY: Rc> = { + let rng = match ChaCha12Rng::try_from_os_rng() { + Ok(rng) => rng, + Err(err) => panic!("could not initialize ThreadRng: {err}"), + }; + Rc::new(UnsafeCell::new(InnerState { rng, bytes_until_reseed: RESEED_THRESHOLD })) + } +); + +/// A reference to the thread-local generator. +/// +/// This type is a reference to a lazily-initialized thread-local generator. +/// An instance can be obtained via [`ThreadRng::new()`] or [`ThreadRng::default()`]. +/// The handle cannot be passed between threads (is not [`Send`] or [`Sync`]). +/// +/// # Example +/// +/// ``` +/// use rand_trng::{ThreadRng, RngCore}; +/// +/// let mut rng = ThreadRng::new(); +/// +/// let random_u32 = rng.next_u32(); +/// let random_u64 = rng.next_u64(); +/// +/// let mut buf = [0u8; 32]; +/// rng.fill_bytes(&mut buf); +/// ``` +/// +/// # Security +/// +/// Security must be considered relative to a threat model and validation +/// requirements. The Rand project can provide no guarantee of fitness for +/// purpose. The design criteria for `ThreadRng` are as follows: +/// +/// - Automatic seeding via [`OsRng`] and periodically thereafter after every 64 KiB of +/// generated data. Limitation: there is no automatic +/// reseeding on process fork (see [below](#fork)). +/// - A rigorusly analyzed, unpredictable (cryptographic) pseudo-random generator +/// (see [the book on security](https://rust-random.github.io/book/guide-rngs.html#security)). +/// The currently selected algorithm is ChaCha (12-rounds). +/// - Not to leak internal state through [`Debug`] or serialization implementations. +/// - No further protections exist to in-memory state. In particular, the +/// implementation is not required to zero memory on exit (of the process or +/// thread). (This may change in the future.) +/// - Be fast enough for general-purpose usage. Note in particular that +/// `ThreadRng` is designed to be a "fast, reasonably secure generator" +/// (where "reasonably secure" implies the above criteria). +/// +/// We leave it to the user to determine whether this generator meets their +/// security requirements. For an alternative, see [`OsRng`]. +/// +/// # Fork +/// +/// `ThreadRng` is not automatically reseeded on fork. It is recommended to +/// explicitly call [`ThreadRng::reseed`] immediately after a fork, for example: +/// ```ignore +/// fn do_fork() { +/// let pid = unsafe { libc::fork() }; +/// if pid == 0 { +/// // Reseed ThreadRng in child processes: +/// rand::rng().reseed(); +/// } +/// } +/// ``` +/// +/// Methods on `ThreadRng` are not reentrant-safe and thus should not be called +/// from an interrupt (e.g. a fork handler) unless it can be guaranteed that no +/// other method on the same `ThreadRng` is currently executing. +/// +/// [`OsRng`]: rand_core::OsRng +#[derive(Clone)] +pub struct ThreadRng { + rng: Rc>, +} + +impl ThreadRng { + /// Create a reference to the thread-local generator. + pub fn new() -> Self { + Default::default() + } + + /// Immediately reseed the generator + /// + /// This discards any remaining random data in the cache. + pub fn reseed(&mut self) -> Result<(), rand_core::getrandom::Error> { + // SAFETY: The state is thread-local and the reference does not leak from this method + let s = unsafe { &mut *self.rng.get() }; + s.reseed() + } +} + +/// Debug implementation does not leak internal state +impl fmt::Debug for ThreadRng { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("ThreadRng { .. }") + } +} + +impl Default for ThreadRng { + fn default() -> Self { + let rng = THREAD_RNG_KEY.with(|t| t.clone()); + Self { rng } + } +} + +impl RngCore for ThreadRng { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + // SAFETY: The state is thread-local and the reference does not leak from this method + let s = unsafe { &mut *self.rng.get() }; + s.reseed_check(core::mem::size_of::() as isize); + s.rng.next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + // SAFETY: The state is thread-local and the reference does not leak from this method + let s = unsafe { &mut *self.rng.get() }; + s.reseed_check(core::mem::size_of::() as isize); + s.rng.next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + // SAFETY: The state is thread-local and the reference does not leak from this method + let s = unsafe { &mut *self.rng.get() }; + // Valid allocations can not be bigger than `isize::MAX` bytes, + // so we can cast length to `isize` without issues. + s.reseed_check(dest.len() as isize); + s.rng.fill_bytes(dest) + } +} + +impl CryptoRng for ThreadRng {} diff --git a/src/lib.rs b/src/lib.rs index 833fe0c0e46..412cec97e0d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -102,14 +102,45 @@ mod rng; pub mod rngs; pub mod seq; -// Public exports -#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] -pub use crate::rngs::thread::rng; +/// Access a fast, pre-initialized generator +/// +/// This is a handle to the local [`ThreadRng`]. +/// +/// See also [`crate::rngs`] for alternatives. +/// +/// # Example +/// +/// ``` +/// use rand::prelude::*; +/// +/// # fn main() { +/// +/// let mut numbers = [1, 2, 3, 4, 5]; +/// numbers.shuffle(&mut rand::rng()); +/// println!("Numbers: {numbers:?}"); +/// +/// // Using a local binding avoids an initialization-check on each usage: +/// let mut rng = rand::rng(); +/// +/// println!("True or false: {}", rng.random::()); +/// println!("A simulated die roll: {}", rng.random_range(1..=6)); +/// # } +/// ``` +/// +/// # Security +/// +/// Refer to the [`ThreadRng`] docs. +/// +/// [`ThreadRng`]: rand_trng::ThreadRng +#[cfg(feature = "thread_rng")] +pub fn rng() -> rand_trng::ThreadRng { + Default::default() +} /// Access the thread-local generator /// /// Use [`rand::rng()`](rng()) instead. -#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] +#[cfg(feature = "thread_rng")] #[deprecated(since = "0.9.0", note = "renamed to `rng`")] #[inline] pub fn thread_rng() -> crate::rngs::ThreadRng { @@ -165,7 +196,7 @@ use crate::distr::{Distribution, Standard}; /// /// [`Standard`]: distr::Standard /// [`ThreadRng`]: rngs::ThreadRng -#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] +#[cfg(feature = "thread_rng")] #[inline] pub fn random() -> T where diff --git a/src/rngs/mod.rs b/src/rngs/mod.rs index bfb5bf6e960..dae445aa6bd 100644 --- a/src/rngs/mod.rs +++ b/src/rngs/mod.rs @@ -95,15 +95,13 @@ mod xoshiro256plusplus; #[cfg(feature = "std_rng")] mod std; -#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] -pub(crate) mod thread; #[cfg(feature = "small_rng")] pub use self::small::SmallRng; #[cfg(feature = "std_rng")] pub use self::std::StdRng; -#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] -pub use self::thread::ThreadRng; +#[cfg(feature = "thread_rng")] +pub use rand_trng::ThreadRng; #[cfg(feature = "getrandom")] pub use rand_core::OsRng; diff --git a/src/rngs/std.rs b/src/rngs/std.rs index d59291b8567..aa52408724c 100644 --- a/src/rngs/std.rs +++ b/src/rngs/std.rs @@ -10,7 +10,7 @@ use rand_core::{CryptoRng, RngCore, SeedableRng}; -#[cfg(any(test, feature = "getrandom"))] +#[cfg(test)] pub(crate) use rand_chacha::ChaCha12Core as Core; use rand_chacha::ChaCha12Rng as Rng; diff --git a/src/rngs/thread.rs b/src/rngs/thread.rs deleted file mode 100644 index 64ca0e1f761..00000000000 --- a/src/rngs/thread.rs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Thread-local random number generator - -use core::cell::UnsafeCell; -use std::fmt; -use std::rc::Rc; -use std::thread_local; - -use rand_core::{CryptoRng, RngCore, SeedableRng}; - -use super::std::Core; -use crate::rngs::OsRng; -use crate::rngs::ReseedingRng; - -// Rationale for using `UnsafeCell` in `ThreadRng`: -// -// Previously we used a `RefCell`, with an overhead of ~15%. There will only -// ever be one mutable reference to the interior of the `UnsafeCell`, because -// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a -// single thread (which is the definition of `ThreadRng`), there will only ever -// be one of these methods active at a time. -// -// A possible scenario where there could be multiple mutable references is if -// `ThreadRng` is used inside `next_u32` and co. But the implementation is -// completely under our control. We just have to ensure none of them use -// `ThreadRng` internally, which is nonsensical anyway. We should also never run -// `ThreadRng` in destructors of its implementation, which is also nonsensical. - -// Number of generated bytes after which to reseed `ThreadRng`. -// According to benchmarks, reseeding has a noticeable impact with thresholds -// of 32 kB and less. We choose 64 kB to avoid significant overhead. -const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64; - -/// A reference to the thread-local generator -/// -/// This type is a reference to a lazily-initialized thread-local generator. -/// An instance can be obtained via [`rand::rng()`][crate::rng()] or via -/// [`ThreadRng::default()`]. -/// The handle cannot be passed between threads (is not `Send` or `Sync`). -/// -/// # Security -/// -/// Security must be considered relative to a threat model and validation -/// requirements. The Rand project can provide no guarantee of fitness for -/// purpose. The design criteria for `ThreadRng` are as follows: -/// -/// - Automatic seeding via [`OsRng`] and periodically thereafter (see -/// ([`ReseedingRng`] documentation). Limitation: there is no automatic -/// reseeding on process fork (see [below](#fork)). -/// - A rigorusly analyzed, unpredictable (cryptographic) pseudo-random generator -/// (see [the book on security](https://rust-random.github.io/book/guide-rngs.html#security)). -/// The currently selected algorithm is ChaCha (12-rounds). -/// See also [`StdRng`] documentation. -/// - Not to leak internal state through [`Debug`] or serialization -/// implementations. -/// - No further protections exist to in-memory state. In particular, the -/// implementation is not required to zero memory on exit (of the process or -/// thread). (This may change in the future.) -/// - Be fast enough for general-purpose usage. Note in particular that -/// `ThreadRng` is designed to be a "fast, reasonably secure generator" -/// (where "reasonably secure" implies the above criteria). -/// -/// We leave it to the user to determine whether this generator meets their -/// security requirements. For an alternative, see [`OsRng`]. -/// -/// # Fork -/// -/// `ThreadRng` is not automatically reseeded on fork. It is recommended to -/// explicitly call [`ThreadRng::reseed`] immediately after a fork, for example: -/// ```ignore -/// fn do_fork() { -/// let pid = unsafe { libc::fork() }; -/// if pid == 0 { -/// // Reseed ThreadRng in child processes: -/// rand::rng().reseed(); -/// } -/// } -/// ``` -/// -/// Methods on `ThreadRng` are not reentrant-safe and thus should not be called -/// from an interrupt (e.g. a fork handler) unless it can be guaranteed that no -/// other method on the same `ThreadRng` is currently executing. -/// -/// [`ReseedingRng`]: crate::rngs::ReseedingRng -/// [`StdRng`]: crate::rngs::StdRng -#[derive(Clone)] -pub struct ThreadRng { - // Rc is explicitly !Send and !Sync - rng: Rc>>, -} - -impl ThreadRng { - /// Immediately reseed the generator - /// - /// This discards any remaining random data in the cache. - pub fn reseed(&mut self) -> Result<(), rand_core::getrandom::Error> { - // SAFETY: We must make sure to stop using `rng` before anyone else - // creates another mutable reference - let rng = unsafe { &mut *self.rng.get() }; - rng.reseed() - } -} - -/// Debug implementation does not leak internal state -impl fmt::Debug for ThreadRng { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "ThreadRng {{ .. }}") - } -} - -thread_local!( - // We require Rc<..> to avoid premature freeing when ThreadRng is used - // within thread-local destructors. See #968. - static THREAD_RNG_KEY: Rc>> = { - let r = Core::try_from_os_rng().unwrap_or_else(|err| - panic!("could not initialize ThreadRng: {}", err)); - let rng = ReseedingRng::new(r, - THREAD_RNG_RESEED_THRESHOLD, - OsRng); - Rc::new(UnsafeCell::new(rng)) - } -); - -/// Access a fast, pre-initialized generator -/// -/// This is a handle to the local [`ThreadRng`]. -/// -/// See also [`crate::rngs`] for alternatives. -/// -/// # Example -/// -/// ``` -/// use rand::prelude::*; -/// -/// # fn main() { -/// -/// let mut numbers = [1, 2, 3, 4, 5]; -/// numbers.shuffle(&mut rand::rng()); -/// println!("Numbers: {numbers:?}"); -/// -/// // Using a local binding avoids an initialization-check on each usage: -/// let mut rng = rand::rng(); -/// -/// println!("True or false: {}", rng.random::()); -/// println!("A simulated die roll: {}", rng.random_range(1..=6)); -/// # } -/// ``` -/// -/// # Security -/// -/// Refer to [`ThreadRng#Security`]. -pub fn rng() -> ThreadRng { - let rng = THREAD_RNG_KEY.with(|t| t.clone()); - ThreadRng { rng } -} - -impl Default for ThreadRng { - fn default() -> ThreadRng { - rng() - } -} - -impl RngCore for ThreadRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - // SAFETY: We must make sure to stop using `rng` before anyone else - // creates another mutable reference - let rng = unsafe { &mut *self.rng.get() }; - rng.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - // SAFETY: We must make sure to stop using `rng` before anyone else - // creates another mutable reference - let rng = unsafe { &mut *self.rng.get() }; - rng.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - // SAFETY: We must make sure to stop using `rng` before anyone else - // creates another mutable reference - let rng = unsafe { &mut *self.rng.get() }; - rng.fill_bytes(dest) - } -} - -impl CryptoRng for ThreadRng {} - -#[cfg(test)] -mod test { - #[test] - fn test_thread_rng() { - use crate::Rng; - let mut r = crate::rng(); - r.random::(); - assert_eq!(r.random_range(0..1), 0); - } - - #[test] - fn test_debug_output() { - // We don't care about the exact output here, but it must not include - // private CSPRNG state or the cache stored by BlockRng! - assert_eq!(std::format!("{:?}", crate::rng()), "ThreadRng { .. }"); - } -}