Coverage Report

Created: 2025-07-14 07:05

/rust/registry/src/index.crates.io-6f17d22bba15001f/getrandom-0.2.16/src/lib.rs
Line
Count
Source (jump to first uncovered line)
1
//! Interface to the operating system's random number generator.
2
//!
3
//! # Supported targets
4
//!
5
//! | Target            | Target Triple      | Implementation
6
//! | ----------------- | ------------------ | --------------
7
//! | Linux, Android    | `*‑linux‑*`        | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
8
//! | Windows           | `*‑windows‑*`      | [`BCryptGenRandom`]
9
//! | macOS             | `*‑apple‑darwin`   | [`getentropy`][3]
10
//! | iOS, tvOS, watchOS | `*‑apple‑ios`, `*-apple-tvos`, `*-apple-watchos` | [`CCRandomGenerateBytes`]
11
//! | FreeBSD           | `*‑freebsd`        | [`getrandom`][5]
12
//! | OpenBSD           | `*‑openbsd`        | [`getentropy`][7]
13
//! | NetBSD            | `*‑netbsd`         | [`getrandom`][16] if available, otherwise [`kern.arandom`][8]
14
//! | Dragonfly BSD     | `*‑dragonfly`      | [`getrandom`][9]
15
//! | Solaris           | `*‑solaris`        | [`getrandom`][11] (with `GRND_RANDOM`)
16
//! | illumos           | `*‑illumos`        | [`getrandom`][12]
17
//! | Fuchsia OS        | `*‑fuchsia`        | [`cprng_draw`]
18
//! | Redox             | `*‑redox`          | `/dev/urandom`
19
//! | Haiku             | `*‑haiku`          | `/dev/urandom` (identical to `/dev/random`)
20
//! | Hermit            | `*-hermit`         | [`sys_read_entropy`]
21
//! | Hurd              | `*-hurd-*`         | [`getrandom`][17]
22
//! | SGX               | `x86_64‑*‑sgx`     | [`RDRAND`]
23
//! | VxWorks           | `*‑wrs‑vxworks‑*`  | `randABytes` after checking entropy pool initialization with `randSecure`
24
//! | ESP-IDF           | `*‑espidf`         | [`esp_fill_random`]
25
//! | Emscripten        | `*‑emscripten`     | [`getentropy`][13]
26
//! | WASI              | `wasm32‑wasi`      | [`random_get`]
27
//! | Web Browser and Node.js | `wasm*‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js, see [WebAssembly support]
28
//! | SOLID             | `*-kmc-solid_*`    | `SOLID_RNG_SampleRandomBytes`
29
//! | Nintendo 3DS      | `*-nintendo-3ds`   | [`getrandom`][18]
30
//! | PS Vita           | `*-vita-*`         | [`getentropy`][13]
31
//! | QNX Neutrino      | `*‑nto-qnx*`       | [`/dev/urandom`][14] (identical to `/dev/random`)
32
//! | AIX               | `*-ibm-aix`        | [`/dev/urandom`][15]
33
//! | Cygwin            | `*-cygwin`         | [`getrandom`][19] (based on [`RtlGenRandom`])
34
//!
35
//! Pull Requests that add support for new targets to `getrandom` are always welcome.
36
//!
37
//! ## Unsupported targets
38
//!
39
//! By default, `getrandom` will not compile on unsupported targets, but certain
40
//! features allow a user to select a "fallback" implementation if no supported
41
//! implementation exists.
42
//!
43
//! All of the below mechanisms only affect unsupported
44
//! targets. Supported targets will _always_ use their supported implementations.
45
//! This prevents a crate from overriding a secure source of randomness
46
//! (either accidentally or intentionally).
47
//!
48
//! ## `/dev/urandom` fallback on Linux and Android
49
//!
50
//! On Linux targets the fallback is present only if either `target_env` is `musl`,
51
//! or `target_arch` is one of the following: `aarch64`, `arm`, `powerpc`, `powerpc64`,
52
//! `s390x`, `x86`, `x86_64`. Other supported targets [require][platform-support]
53
//! kernel versions which support `getrandom` system call, so fallback is not needed.
54
//!
55
//! On Android targets the fallback is present only for the following `target_arch`es:
56
//! `aarch64`, `arm`, `x86`, `x86_64`. Other `target_arch`es (e.g. RISC-V) require
57
//! sufficiently high API levels.
58
//!
59
//! The fallback can be disabled by enabling the `linux_disable_fallback` crate feature.
60
//! Note that doing so will bump minimum supported Linux kernel version to 3.17 and
61
//! Android API level to 23 (Marshmallow).
62
//!
63
//! ### RDRAND on x86
64
//!
65
//! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using
66
//! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64`
67
//! targets. This feature has no effect on other CPU architectures.
68
//!
69
//! ### WebAssembly support
70
//!
71
//! This crate fully supports the
72
//! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and
73
//! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/)
74
//! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used
75
//! by `wasm-pack`) is not automatically
76
//! supported since, from the target name alone, we cannot deduce which
77
//! JavaScript interface is in use (or if JavaScript is available at all).
78
//!
79
//! Instead, *if the `js` Cargo feature is enabled*, this crate will assume
80
//! that you are building for an environment containing JavaScript, and will
81
//! call the appropriate methods. Both web browser (main window and Web Workers)
82
//! and Node.js environments are supported, invoking the methods
83
//! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain.
84
//!
85
//! To enable the `js` Cargo feature, add the following to the `dependencies`
86
//! section in your `Cargo.toml` file:
87
//! ```toml
88
//! [dependencies]
89
//! getrandom = { version = "0.2", features = ["js"] }
90
//! ```
91
//!
92
//! This can be done even if `getrandom` is not a direct dependency. Cargo
93
//! allows crates to enable features for indirect dependencies.
94
//!
95
//! This feature should only be enabled for binary, test, or benchmark crates.
96
//! Library crates should generally not enable this feature, leaving such a
97
//! decision to *users* of their library. Also, libraries should not introduce
98
//! their own `js` features *just* to enable `getrandom`'s `js` feature.
99
//!
100
//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
101
//!
102
//! #### Node.js ES module support
103
//!
104
//! Node.js supports both [CommonJS modules] and [ES modules]. Due to
105
//! limitations in wasm-bindgen's [`module`] support, we cannot directly
106
//! support ES Modules running on Node.js. However, on Node v15 and later, the
107
//! module author can add a simple shim to support the Web Cryptography API:
108
//! ```js
109
//! import { webcrypto } from 'node:crypto'
110
//! globalThis.crypto = webcrypto
111
//! ```
112
//! This crate will then use the provided `webcrypto` implementation.
113
//!
114
//! ### Platform Support
115
//! This crate generally supports the same operating system and platform versions
116
//! that the Rust standard library does. Additional targets may be supported using
117
//! pluggable custom implementations.
118
//!
119
//! This means that as Rust drops support for old versions of operating systems
120
//! (such as old Linux kernel versions, Android API levels, etc) in stable releases,
121
//! `getrandom` may create new patch releases (`0.N.x`) that remove support for
122
//! outdated platform versions.
123
//!
124
//! ### Custom implementations
125
//!
126
//! The [`register_custom_getrandom!`] macro allows a user to mark their own
127
//! function as the backing implementation for [`getrandom`]. See the macro's
128
//! documentation for more information about writing and registering your own
129
//! custom implementations.
130
//!
131
//! Note that registering a custom implementation only has an effect on targets
132
//! that would otherwise not compile. Any supported targets (including those
133
//! using `rdrand` and `js` Cargo features) continue using their normal
134
//! implementations even if a function is registered.
135
//!
136
//! ## Early boot
137
//!
138
//! Sometimes, early in the boot process, the OS has not collected enough
139
//! entropy to securely seed its RNG. This is especially common on virtual
140
//! machines, where standard "random" events are hard to come by.
141
//!
142
//! Some operating system interfaces always block until the RNG is securely
143
//! seeded. This can take anywhere from a few seconds to more than a minute.
144
//! A few (Linux, NetBSD and Solaris) offer a choice between blocking and
145
//! getting an error; in these cases, we always choose to block.
146
//!
147
//! On Linux (when the `getrandom` system call is not available), reading from
148
//! `/dev/urandom` never blocks, even when the OS hasn't collected enough
149
//! entropy yet. To avoid returning low-entropy bytes, we first poll
150
//! `/dev/random` and only switch to `/dev/urandom` once this has succeeded.
151
//!
152
//! On OpenBSD, this kind of entropy accounting isn't available, and on
153
//! NetBSD, blocking on it is discouraged. On these platforms, nonblocking
154
//! interfaces are used, even when reliable entropy may not be available.
155
//! On the platforms where it is used, the reliability of entropy accounting
156
//! itself isn't free from controversy. This library provides randomness
157
//! sourced according to the platform's best practices, but each platform has
158
//! its own limits on the grade of randomness it can promise in environments
159
//! with few sources of entropy.
160
//!
161
//! ## Error handling
162
//!
163
//! We always choose failure over returning known insecure "random" bytes. In
164
//! general, on supported platforms, failure is highly unlikely, though not
165
//! impossible. If an error does occur, then it is likely that it will occur
166
//! on every call to `getrandom`, hence after the first successful call one
167
//! can be reasonably confident that no errors will occur.
168
//!
169
//! [1]: https://manned.org/getrandom.2
170
//! [2]: https://manned.org/urandom.4
171
//! [3]: https://www.unix.com/man-page/mojave/2/getentropy/
172
//! [4]: https://www.unix.com/man-page/mojave/4/urandom/
173
//! [5]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
174
//! [7]: https://man.openbsd.org/getentropy.2
175
//! [8]: https://man.netbsd.org/sysctl.7
176
//! [9]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom
177
//! [11]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html
178
//! [12]: https://illumos.org/man/2/getrandom
179
//! [13]: https://github.com/emscripten-core/emscripten/pull/12240
180
//! [14]: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/r/random.html
181
//! [15]: https://www.ibm.com/docs/en/aix/7.3?topic=files-random-urandom-devices
182
//! [16]: https://man.netbsd.org/getrandom.2
183
//! [17]: https://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getrandom
184
//! [18]: https://github.com/rust3ds/shim-3ds/commit/b01d2568836dea2a65d05d662f8e5f805c64389d
185
//! [19]: https://github.com/cygwin/cygwin/blob/main/winsup/cygwin/libc/getentropy.cc
186
//!
187
//! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
188
//! [`RtlGenRandom`]: https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom
189
//! [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
190
//! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
191
//! [`CCRandomGenerateBytes`]: https://opensource.apple.com/source/CommonCrypto/CommonCrypto-60074/include/CommonRandom.h.auto.html
192
//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
193
//! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size
194
//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
195
//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
196
//! [WebAssembly support]: #webassembly-support
197
//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
198
//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
199
//! [CommonJS modules]: https://nodejs.org/api/modules.html
200
//! [ES modules]: https://nodejs.org/api/esm.html
201
//! [`sys_read_entropy`]: https://github.com/hermit-os/kernel/blob/315f58ff5efc81d9bf0618af85a59963ff55f8b1/src/syscalls/entropy.rs#L47-L55
202
//! [platform-support]: https://doc.rust-lang.org/stable/rustc/platform-support.html
203
204
#![doc(
205
    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
206
    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
207
    html_root_url = "https://docs.rs/getrandom/0.2.16"
208
)]
209
#![no_std]
210
#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
211
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
212
213
#[macro_use]
214
extern crate cfg_if;
215
216
use crate::util::{slice_as_uninit_mut, slice_assume_init_mut};
217
use core::mem::MaybeUninit;
218
219
mod error;
220
mod util;
221
// To prevent a breaking change when targets are added, we always export the
222
// register_custom_getrandom macro, so old Custom RNG crates continue to build.
223
#[cfg(feature = "custom")]
224
mod custom;
225
#[cfg(feature = "std")]
226
mod error_impls;
227
228
pub use crate::error::Error;
229
230
// System-specific implementations.
231
//
232
// These should all provide getrandom_inner with the signature
233
// `fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`.
234
// The function MUST fully initialize `dest` when `Ok(())` is returned.
235
// The function MUST NOT ever write uninitialized bytes into `dest`,
236
// regardless of what value it returns.
237
cfg_if! {
238
    if #[cfg(any(target_os = "haiku", target_os = "redox", target_os = "nto", target_os = "aix"))] {
239
        mod util_libc;
240
        #[path = "use_file.rs"] mod imp;
241
    } else if #[cfg(any(
242
        target_os = "macos",
243
        target_os = "openbsd",
244
        target_os = "vita",
245
        target_os = "emscripten",
246
    ))] {
247
        mod util_libc;
248
        #[path = "getentropy.rs"] mod imp;
249
    } else if #[cfg(any(
250
        target_os = "dragonfly",
251
        target_os = "freebsd",
252
        target_os = "hurd",
253
        target_os = "illumos",
254
        // Check for target_arch = "arm" to only include the 3DS. Does not
255
        // include the Nintendo Switch (which is target_arch = "aarch64").
256
        all(target_os = "horizon", target_arch = "arm"),
257
        target_os = "cygwin",
258
    ))] {
259
        mod util_libc;
260
        #[path = "getrandom.rs"] mod imp;
261
    } else if #[cfg(all(
262
        not(feature = "linux_disable_fallback"),
263
        any(
264
            // Rust supports Android API level 19 (KitKat) [0] and the next upgrade targets
265
            // level 21 (Lollipop) [1], while `getrandom(2)` was added only in
266
            // level 23 (Marshmallow). Note that it applies only to the "old" `target_arch`es,
267
            // RISC-V Android targets sufficiently new API level, same will apply for potential
268
            // new Android `target_arch`es.
269
            // [0]: https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html
270
            // [1]: https://github.com/rust-lang/rust/pull/120593
271
            all(
272
                target_os = "android",
273
                any(
274
                    target_arch = "aarch64",
275
                    target_arch = "arm",
276
                    target_arch = "x86",
277
                    target_arch = "x86_64",
278
                ),
279
            ),
280
            // Only on these `target_arch`es Rust supports Linux kernel versions (3.2+)
281
            // that precede the version (3.17) in which `getrandom(2)` was added:
282
            // https://doc.rust-lang.org/stable/rustc/platform-support.html
283
            all(
284
                target_os = "linux",
285
                any(
286
                    target_arch = "aarch64",
287
                    target_arch = "arm",
288
                    target_arch = "powerpc",
289
                    target_arch = "powerpc64",
290
                    target_arch = "s390x",
291
                    target_arch = "x86",
292
                    target_arch = "x86_64",
293
                    // Minimum supported Linux kernel version for MUSL targets
294
                    // is not specified explicitly (as of Rust 1.77) and they
295
                    // are used in practice to target pre-3.17 kernels.
296
                    target_env = "musl",
297
                ),
298
            )
299
        ),
300
    ))] {
301
        mod util_libc;
302
        mod use_file;
303
        mod lazy;
304
        #[path = "linux_android_with_fallback.rs"] mod imp;
305
    } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
306
        mod util_libc;
307
        #[path = "linux_android.rs"] mod imp;
308
    } else if #[cfg(target_os = "solaris")] {
309
        mod util_libc;
310
        #[path = "solaris.rs"] mod imp;
311
    } else if #[cfg(target_os = "netbsd")] {
312
        mod util_libc;
313
        #[path = "netbsd.rs"] mod imp;
314
    } else if #[cfg(target_os = "fuchsia")] {
315
        #[path = "fuchsia.rs"] mod imp;
316
    } else if #[cfg(any(target_os = "ios", target_os = "visionos", target_os = "watchos", target_os = "tvos"))] {
317
        #[path = "apple-other.rs"] mod imp;
318
    } else if #[cfg(all(target_arch = "wasm32", target_os = "wasi"))] {
319
        #[path = "wasi.rs"] mod imp;
320
    } else if #[cfg(target_os = "hermit")] {
321
        #[path = "hermit.rs"] mod imp;
322
    } else if #[cfg(target_os = "vxworks")] {
323
        mod util_libc;
324
        #[path = "vxworks.rs"] mod imp;
325
    } else if #[cfg(target_os = "solid_asp3")] {
326
        #[path = "solid.rs"] mod imp;
327
    } else if #[cfg(target_os = "espidf")] {
328
        #[path = "espidf.rs"] mod imp;
329
    } else if #[cfg(windows)] {
330
        #[path = "windows.rs"] mod imp;
331
    } else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
332
        mod lazy;
333
        #[path = "rdrand.rs"] mod imp;
334
    } else if #[cfg(all(feature = "rdrand",
335
                        any(target_arch = "x86_64", target_arch = "x86")))] {
336
        mod lazy;
337
        #[path = "rdrand.rs"] mod imp;
338
    } else if #[cfg(all(feature = "js",
339
                        any(target_arch = "wasm32", target_arch = "wasm64"),
340
                        target_os = "unknown"))] {
341
        #[path = "js.rs"] mod imp;
342
    } else if #[cfg(feature = "custom")] {
343
        use custom as imp;
344
    } else if #[cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"),
345
                        target_os = "unknown"))] {
346
        compile_error!("the wasm*-unknown-unknown targets are not supported by \
347
                        default, you may need to enable the \"js\" feature. \
348
                        For more information see: \
349
                        https://docs.rs/getrandom/#webassembly-support");
350
    } else {
351
        compile_error!("target is not supported, for more information see: \
352
                        https://docs.rs/getrandom/#unsupported-targets");
353
    }
354
}
355
356
/// Fill `dest` with random bytes from the system's preferred random number
357
/// source.
358
///
359
/// This function returns an error on any failure, including partial reads. We
360
/// make no guarantees regarding the contents of `dest` on error. If `dest` is
361
/// empty, `getrandom` immediately returns success, making no calls to the
362
/// underlying operating system.
363
///
364
/// Blocking is possible, at least during early boot; see module documentation.
365
///
366
/// In general, `getrandom` will be fast enough for interactive usage, though
367
/// significantly slower than a user-space CSPRNG; for the latter consider
368
/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
369
#[inline]
370
0
pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
371
0
    // SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape, and
372
0
    // `getrandom_uninit` guarantees it will never de-initialize any part of
373
0
    // `dest`.
374
0
    getrandom_uninit(unsafe { slice_as_uninit_mut(dest) })?;
375
0
    Ok(())
376
0
}
Unexecuted instantiation: getrandom::getrandom
Unexecuted instantiation: getrandom::getrandom
Unexecuted instantiation: getrandom::getrandom
Unexecuted instantiation: getrandom::getrandom
377
378
/// Version of the `getrandom` function which fills `dest` with random bytes
379
/// returns a mutable reference to those bytes.
380
///
381
/// On successful completion this function is guaranteed to return a slice
382
/// which points to the same memory as `dest` and has the same length.
383
/// In other words, it's safe to assume that `dest` is initialized after
384
/// this function has returned `Ok`.
385
///
386
/// No part of `dest` will ever be de-initialized at any point, regardless
387
/// of what is returned.
388
///
389
/// # Examples
390
///
391
/// ```ignore
392
/// # // We ignore this test since `uninit_array` is unstable.
393
/// #![feature(maybe_uninit_uninit_array)]
394
/// # fn main() -> Result<(), getrandom::Error> {
395
/// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>();
396
/// let buf: &mut [u8] = getrandom::getrandom_uninit(&mut buf)?;
397
/// # Ok(()) }
398
/// ```
399
#[inline]
400
0
pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> {
401
0
    if !dest.is_empty() {
402
0
        imp::getrandom_inner(dest)?;
403
0
    }
404
    // SAFETY: `dest` has been fully initialized by `imp::getrandom_inner`
405
    // since it returned `Ok`.
406
0
    Ok(unsafe { slice_assume_init_mut(dest) })
407
0
}
Unexecuted instantiation: getrandom::getrandom_uninit
Unexecuted instantiation: getrandom::getrandom_uninit
Unexecuted instantiation: getrandom::getrandom_uninit
Unexecuted instantiation: getrandom::getrandom_uninit