issue_numbers listlengths 1 1 | test_patch stringlengths 277 33.4k | hints_text stringlengths 0 25.3k | patch stringlengths 451 21.2k | version stringclasses 2 values | created_at stringdate 2021-01-03 05:40:59 2025-03-03 13:33:55 | base_commit stringlengths 40 40 | pull_number int64 192 614 | problem_statement stringlengths 189 2.98k | repo stringclasses 1 value | instance_id stringlengths 26 26 | updated_at stringdate 2021-01-04 06:05:18 2025-03-22 06:42:54 | environment_setup_commit stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
[
"446"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -16,28 +16,6 @@ env:
RUSTFLAGS: "-Dwarnings"
jobs:
- check-doc:
- name: Docs, deadlinks, minimal dependencies
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v3
- - uses: dtolnay/rust-toolchain@nightly # Needed for -Z minimal-versions and doc_cfg
- - name: Install precompiled cargo-deadlinks
- run: |
- VERSION=0.8.1
- URL="https://github.com/deadlinks/cargo-deadlinks/releases/download/${VERSION}/cargo-deadlinks-linux"
- wget -O ~/.cargo/bin/cargo-deadlinks $URL
- chmod +x ~/.cargo/bin/cargo-deadlinks
- cargo deadlinks --version
- - uses: Swatinem/rust-cache@v2
- - name: Generate Docs
- env:
- RUSTDOCFLAGS: --cfg docsrs
- run: cargo deadlinks -- --features=custom,std
- - run: |
- cargo generate-lockfile -Z minimal-versions
- cargo test --features=custom,std
-
main-tests:
name: Tier 1 Test
runs-on: ${{ matrix.os }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -54,7 +32,7 @@ jobs:
- os: macos-14
toolchain: stable
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.toolchain }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -80,7 +58,7 @@ jobs:
# TODO: Find a Linux image/runner with CONFIG_X86_X32_ABI set
cargo_test_opts: --no-run
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -111,7 +89,7 @@ jobs:
target: aarch64-apple-ios-sim
ios_platform: auto-ios-aarch64-sim
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -158,7 +136,7 @@ jobs:
stable-i686-msvc,
]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.toolchain }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -169,7 +147,7 @@ jobs:
name: Test Windows 7 impl on Windows 10
runs-on: windows-2022
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
# Win7 targets are Tier3, so pin a nightly where libstd builds.
- uses: dtolnay/rust-toolchain@master
with:
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -193,7 +171,7 @@ jobs:
wasm32-unknown-emscripten,
]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Install precompiled cross
run: |
VERSION=v0.2.5
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -207,7 +185,7 @@ jobs:
name: macOS ARM64 Build/Link
runs-on: macos-12
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
targets: aarch64-apple-darwin, aarch64-apple-ios
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -229,7 +207,7 @@ jobs:
x86_64-unknown-netbsd,
]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Install precompiled cross
run: |
VERSION=v0.2.5
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -256,7 +234,7 @@ jobs:
host: x86_64-apple-darwin
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: choco install wget
if: runner.os == 'Windows'
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -287,7 +265,7 @@ jobs:
name: wasm64 Build/Link
runs-on: ubuntu-22.04
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly # Need to build libstd
with:
components: rust-src
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -302,7 +280,7 @@ jobs:
name: WASI Test
runs-on: ubuntu-22.04
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-wasi
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -326,7 +304,7 @@ jobs:
x86_64-fortanix-unknown-sgx,
]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -368,7 +346,7 @@ jobs:
- target: i686-unknown-hurd-gnu
features: ["std"]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly # Required to build libcore
with:
components: rust-src
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -379,23 +357,9 @@ jobs:
name: No Atomics Build
runs-on: ubuntu-22.04
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: riscv32i-unknown-none-elf
- uses: Swatinem/rust-cache@v2
- run: cargo build --features custom --target riscv32i-unknown-none-elf
-
- clippy-fmt:
- name: Clippy + rustfmt
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v1
- - uses: dtolnay/rust-toolchain@stable
- with:
- components: rustfmt, clippy
- - uses: Swatinem/rust-cache@v2
- - name: clippy
- run: cargo clippy --all --features=custom,std
- - name: fmt
- run: cargo fmt --all -- --check
diff --git /dev/null b/.github/workflows/workspace.yml
new file mode 100644
--- /dev/null
+++ b/.github/workflows/workspace.yml
@@ -0,0 +1,94 @@
+name: Workspace
+
+on:
+ push:
+ branches: master
+ pull_request:
+ branches: master
+
+permissions:
+ contents: read
+
+jobs:
+ clippy:
+ name: Clippy
+ runs-on: ubuntu-latest
+ env:
+ RUSTFLAGS: "-Dwarnings"
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ # We need Nightly for -Zbuild-std.
+ # Fixed Nigthly version is used to prevent
+ # CI failures which are not relevant to PR changes
+ # on introduction of new Clippy lints.
+ toolchain: nightly-2024-06-11
+ components: clippy,rust-src
+ - name: std feature
+ run: cargo clippy --features std
+ - name: custom feature
+ run: cargo clippy -Zbuild-std=core --target riscv32i-unknown-none-elf --features custom
+ - name: iOS (apple-other.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-apple-ios
+ - name: ESP-IDF (espidf.rs)
+ run: cargo clippy -Zbuild-std=core --target riscv32imc-esp-espidf
+ - name: Fuchsia (fuchsia.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-unknown-fuchsia
+ - name: OpenBSD (getentropy.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-unknown-openbsd
+ - name: FreeBSD (getrandom.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-unknown-freebsd
+ - name: Hermit (hermit.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-unknown-hermit
+ - name: Web WASM (js.rs)
+ run: cargo clippy -Zbuild-std --target wasm32-unknown-unknown --features js
+ - name: Linux (linux_android.rs)
+ run: cargo clippy --target x86_64-unknown-linux-gnu --features linux_disable_fallback
+ - name: Linux (linux_android_with_fallback.rs)
+ run: cargo clippy --target x86_64-unknown-linux-gnu
+ - name: NetBSD (netbsd.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-unknown-netbsd
+ - name: Fortranix SGX (rdrand.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-fortanix-unknown-sgx
+ - name: Solaris (solaris.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-pc-solaris
+ - name: SOLID (solid.rs)
+ run: cargo clippy -Zbuild-std=core --target aarch64-kmc-solid_asp3
+ - name: Redox (use_file.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-unknown-redox
+ - name: VxWorks (vxworks.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-wrs-vxworks
+ - name: WASI (wasi.rs)
+ run: cargo clippy -Zbuild-std=core --target wasm32-wasip2
+ - name: Windows 7 (windows7.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-win7-windows-msvc
+ - name: Windows (windows.rs)
+ run: cargo clippy -Zbuild-std=core --target x86_64-pc-windows-msvc
+
+ fmt:
+ name: rustfmt
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: rustfmt
+ - uses: Swatinem/rust-cache@v2
+ - name: fmt
+ run: cargo fmt --all -- --check
+
+ check-doc:
+ name: rustdoc
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ # We need Nightly for doc_auto_cfg
+ toolchain: nightly-2024-06-11
+ - uses: Swatinem/rust-cache@v2
+ - name: Generate Docs
+ env:
+ RUSTDOCFLAGS: "-Dwarnings --cfg docsrs"
+ run: cargo doc --no-deps --features custom
| diff --git a/src/lazy.rs b/src/lazy.rs
--- a/src/lazy.rs
+++ b/src/lazy.rs
@@ -26,7 +26,7 @@ pub(crate) struct LazyUsize(AtomicUsize);
impl LazyUsize {
// The initialization is not completed.
- const UNINIT: usize = usize::max_value();
+ const UNINIT: usize = usize::MAX;
pub const fn new() -> Self {
Self(AtomicUsize::new(Self::UNINIT))
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -17,7 +17,7 @@ use core::{
/// - On AIX, /dev/urandom will "provide cryptographically secure output".
/// - On Haiku and QNX Neutrino they are identical.
const FILE_PATH: &[u8] = b"/dev/urandom\0";
-const FD_UNINIT: usize = usize::max_value();
+const FD_UNINIT: usize = usize::MAX;
// Do not inline this when it is the fallback implementation, but don't mark it
// `#[cold]` because it is hot when it is actually used.
diff --git a/src/vxworks.rs b/src/vxworks.rs
--- a/src/vxworks.rs
+++ b/src/vxworks.rs
@@ -1,6 +1,7 @@
//! Implementation for VxWorks
use crate::{util_libc::last_os_error, Error};
use core::{
+ cmp::Ordering::{Equal, Greater, Less},
mem::MaybeUninit,
sync::atomic::{AtomicBool, Ordering::Relaxed},
};
diff --git a/src/vxworks.rs b/src/vxworks.rs
--- a/src/vxworks.rs
+++ b/src/vxworks.rs
@@ -9,17 +10,21 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
static RNG_INIT: AtomicBool = AtomicBool::new(false);
while !RNG_INIT.load(Relaxed) {
let ret = unsafe { libc::randSecure() };
- if ret < 0 {
- return Err(Error::VXWORKS_RAND_SECURE);
- } else if ret > 0 {
- RNG_INIT.store(true, Relaxed);
- break;
+ match ret.cmp(&0) {
+ Greater => {
+ RNG_INIT.store(true, Relaxed);
+ break;
+ }
+ Equal => unsafe {
+ libc::usleep(10);
+ },
+ Less => return Err(Error::VXWORKS_RAND_SECURE),
}
- unsafe { libc::usleep(10) };
}
// Prevent overflow of i32
- for chunk in dest.chunks_mut(i32::max_value() as usize) {
+ let chunk_size = usize::try_from(i32::MAX).expect("VxWorks does not support 16-bit targets");
+ for chunk in dest.chunks_mut(chunk_size) {
let ret = unsafe { libc::randABytes(chunk.as_mut_ptr().cast::<u8>(), chunk.len() as i32) };
if ret != 0 {
return Err(last_os_error());
diff --git a/src/windows.rs b/src/windows.rs
--- a/src/windows.rs
+++ b/src/windows.rs
@@ -18,6 +18,7 @@
//! - Requires advapi32.dll (in addition to bcryptprimitives.dll)
//! - Requires using name "SystemFunction036"
//! - Thin wrapper around ProcessPrng
+//!
//! For more information see the Windows RNG Whitepaper: https://aka.ms/win10rng
use crate::Error;
use core::mem::MaybeUninit;
diff --git a/src/windows7.rs b/src/windows7.rs
--- a/src/windows7.rs
+++ b/src/windows7.rs
@@ -25,7 +25,8 @@ const TRUE: BOOLEAN = 1u8;
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Prevent overflow of u32
- for chunk in dest.chunks_mut(u32::max_value() as usize) {
+ let chunk_size = usize::try_from(i32::MAX).expect("Windows does not support 16-bit targets");
+ for chunk in dest.chunks_mut(chunk_size) {
let ret = unsafe { RtlGenRandom(chunk.as_mut_ptr().cast::<c_void>(), chunk.len() as u32) };
if ret != TRUE {
return Err(Error::WINDOWS_RTL_GEN_RANDOM);
| 0.2 | 2024-06-12T09:10:45Z | 3174f0caa091a0e02ebef082e114f9754f3a933b | 477 | Run `cargo clippy` in CI for all targets
Right now `cargo clippy` is only run 64-bit Linux targets. It should be run for all targets so that important lints that statically enforce safety checks are checked on all targets. See #445 in particular.
| rust-random/getrandom | rust-random__getrandom-477 | 2024-06-14T19:27:51Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 | |
[
"600"
] | diff --git a/src/backends/linux_android_with_fallback.rs b/src/backends/linux_android_with_fallback.rs
--- a/src/backends/linux_android_with_fallback.rs
+++ b/src/backends/linux_android_with_fallback.rs
@@ -17,18 +17,28 @@ type GetRandomFn = unsafe extern "C" fn(*mut c_void, libc::size_t, libc::c_uint)
/// or not supported by kernel.
const NOT_AVAILABLE: NonNull<c_void> = unsafe { NonNull::new_unchecked(usize::MAX as *mut c_void) };
-static GETRANDOM_FN: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
+static GETRANDOM_FN: AtomicPtr<c_void> = AtomicPtr::new(core::ptr::null_mut());
#[cold]
#[inline(never)]
fn init() -> NonNull<c_void> {
- static NAME: &[u8] = b"getrandom\0";
- let name_ptr = NAME.as_ptr().cast::<libc::c_char>();
- let raw_ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) };
+ // Use static linking to `libc::getrandom` on MUSL targets and `dlsym` everywhere else
+ #[cfg(not(target_env = "musl"))]
+ let raw_ptr = {
+ static NAME: &[u8] = b"getrandom\0";
+ let name_ptr = NAME.as_ptr().cast::<libc::c_char>();
+ unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) }
+ };
+ #[cfg(target_env = "musl")]
+ let raw_ptr = {
+ let fptr: GetRandomFn = libc::getrandom;
+ unsafe { transmute::<GetRandomFn, *mut c_void>(fptr) }
+ };
+
let res_ptr = match NonNull::new(raw_ptr) {
Some(fptr) => {
- let getrandom_fn = unsafe { mem::transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
- let dangling_ptr = ptr::NonNull::dangling().as_ptr();
+ let getrandom_fn = unsafe { transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
+ let dangling_ptr = NonNull::dangling().as_ptr();
// Check that `getrandom` syscall is supported by kernel
let res = unsafe { getrandom_fn(dangling_ptr, 0, 0) };
if cfg!(getrandom_test_linux_fallback) {
| diff --git a/src/backends/linux_android_with_fallback.rs b/src/backends/linux_android_with_fallback.rs
--- a/src/backends/linux_android_with_fallback.rs
+++ b/src/backends/linux_android_with_fallback.rs
@@ -3,8 +3,8 @@ use super::use_file;
use crate::Error;
use core::{
ffi::c_void,
- mem::{self, MaybeUninit},
- ptr::{self, NonNull},
+ mem::{transmute, MaybeUninit},
+ ptr::NonNull,
sync::atomic::{AtomicPtr, Ordering},
};
use use_file::util_libc;
diff --git a/src/backends/linux_android_with_fallback.rs b/src/backends/linux_android_with_fallback.rs
--- a/src/backends/linux_android_with_fallback.rs
+++ b/src/backends/linux_android_with_fallback.rs
@@ -54,7 +64,7 @@ fn init() -> NonNull<c_void> {
res_ptr
}
-// prevent inlining of the fallback implementation
+// Prevent inlining of the fallback implementation
#[inline(never)]
fn use_file_fallback(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
use_file::fill_inner(dest)
diff --git a/src/backends/linux_android_with_fallback.rs b/src/backends/linux_android_with_fallback.rs
--- a/src/backends/linux_android_with_fallback.rs
+++ b/src/backends/linux_android_with_fallback.rs
@@ -78,7 +88,7 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
use_file_fallback(dest)
} else {
// note: `transmute` is currently the only way to convert a pointer into a function reference
- let getrandom_fn = unsafe { mem::transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
+ let getrandom_fn = unsafe { transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
util_libc::sys_fill_exact(dest, |buf| unsafe {
getrandom_fn(buf.as_mut_ptr().cast(), buf.len(), 0)
})
| 0.3 | 2025-02-05T11:45:16Z | ce3b017fdee0233c6ecd61e68b96a84bf6f911bf | 602 | linux_android_with_fallback never uses getrandom on musl
This regressed in #508.
`dlsym` can't look up a statically linked symbol, and the result is _always_ falling back to /dev/urandom.
| rust-random/getrandom | rust-random__getrandom-602 | 2025-03-22T06:42:54Z | 76ed428dadd7cc8be4f04d495a22806e86e7749e | |
[
"433"
] | diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "getrandom"
-version = "0.3.0-rc.0"
+version = "0.3.0"
edition = "2021"
rust-version = "1.63" # Sync tests.yml and README.md.
authors = ["The Rand Project Developers"]
| CC: @dhardy @vks for how this might affect `rand`
>We are not making any changes to the API of this crate
There was a proposal to rename `getrandom(_uninit)` to `fill(_uninit)`, plus there is #365, but I do not have a concrete proposal for it now. Associated `Error` constants could also use a bit of work, e.g. I am not sure it's worth to expose constants like `VXWORKS_RAND_SECURE` on all platforms. We also can use this release to reconsider our `cfg`s (e.g. #230 and #346). It's also worth to tweak `__getrandom_custom`'s signature to remove this [hack](https://github.com/rust-random/getrandom/blob/master/src/custom.rs#L94-L99).
Moreover, we can use this release to relax our MSRV policy in the vein suggested by @briansmith, but this should be done together with `rand`.
>getrandom is widely used throughout the Rust ecosystem so updating all callers can be somewhat tedious.
I think it's rarely used directly, usually it's done through `rand` crates.
>It's not clear how a user can have a custom implementation work with both versions of getrandom.
It's possible to do this:
```rust
[dependencies]
getrandom02 = { version = "0.2", package = "getrandom" }
getrandom = "0.3"
```
And call the registering macros from each crate (assuming `extern` functions are called differently).
As @josephlr says, pushing these changes to a `0.2.x` release does not break any formal stability guarantees and likely won't cause a large number of issues, though it's impossible to be certain.
I have a slight preference for bumping the version to `0.3` since the drawbacks are small:
- Custom backends *can* support multiple versions of `getrandom` as @newpavlov says. An example of this in action: `winit` supports *three* versions of `raw-window-handle` (optionally).
- No other dependants will be affected. Some build trees may end up using multiple `getrandom` versions, but this hardly matters.
> * No other dependants will be affected. Some build trees may end up using multiple `getrandom` versions, but this hardly matters.
I understand what you're saying, but in practice it does matter. Many people have their CI set up to reject multiple versions of a dependency by default. so they have to either make an exception to their CI rules, and/or they submit PRs upstream to try to upgrade everybody to the new version, which is extra work for everybody. Then those upstream projects (such as some I maintain) end up having to choose to drop support for 0.2 to help these people, or spend time trying to explain to them (over and over, indefinitely) why it "hardly matters." Either way it ends up being disproportionate amount of effort.
If we release 0.3:
* What will we cap the MSRV to for the 0.3 series? 1.63 and insist on a 0.4 for any higher MSRV? Otherwise, I guess many projects will want to stick with 0.2.
* When we add new OS support for 0.3, will we backport those to 0.2? In general will we keep maintaining 0.2? Depending on the MSRV policy for 0.3, there is likely going to be pressure to maintain 0.2.
> There was a proposal to rename getrandom(_uninit) to fill(_uninit),
It would be nice but (a) it can be done in a backward-compatible way by renaming it to `fill` and providing a wrapper named `getrandom[_uninit]` that is optionally marked `#[deprecated]`.
> https://github.com/rust-random/getrandom/issues/365
I think nonblocking getrandom should be a separate API and so it could be added in a SemVer-capable manner. And/or we could implement the old API in terms of the new API, optionally eventually marking the old API `#[deprecated]`.
> Associated Error constants could also use a bit of work, e.g. I am not sure it's worth to expose constants like VXWORKS_RAND_SECURE on all platforms.
Better to discuss it in its own issue to reach a decision.
> We also can use this release to reconsider our cfgs (e.g. https://github.com/rust-random/getrandom/issues/230 and https://github.com/rust-random/getrandom/issues/346). It's also worth to tweak __getrandom_custom's signature to remove this [hack](https://github.com/rust-random/getrandom/blob/master/src/custom.rs#L94-L99).
Yes, these are basically bugs that we've deferred fixes for until we make a SemVer-breaking version bump, so we should do this for 0.3.
I opened #438 and #439 to discuss breaking changes to the API and feature flags respectively. I'm convinced by the arguments above, we should release these changes as a breaking change.
> * What will we cap the MSRV to for the 0.3 series?
Personally, I think that we should cap the MSRV for the upcoming release at 1.57 (1.56 is Rust 2021, and 1.57 gives us panicking in `const` which is super nice for static checks). My preference would actually be to release these upcoming changes as 1.0. I know @newpavlov wants to wait for MSRV-aware dependency resolution, but I'm not sure why we should block releasing 1.0 on that feature.
For 1.0 and onward, we can just say that removing platform support and increasing the MSRV can be done in a minor version, and that:
- we won't drop platform support until Rust libstd does
- our MSRV will always be "conservative" (maybe 2 years of old compiler versions?)
That way folks can put `getrandom = "1.0"` in their dependency file if they are fine with an MSRV of "2 years ago" and if they really want to for-sure not be broken, they can do `getrandom = "~1.0"`
> * When we add new OS support for 0.3, will we backport those to 0.2? In general will we keep maintaining 0.2? Depending on the MSRV policy for 0.3, there is likely going to be pressure to maintain 0.2.
I really wouldn't want to bother back-porting changes. I think we could have backports be "contributions welcome". I'd be fine reviewing backports, but I don't want to do the backporting (especially if nobody's actually using it).
I don't think we should release v1.0, not only because of the MSRV-aware resolver, but also because we will introduce new APIs. There are also potential for new features like "global crate features", which can be quite useful for us. Remember that we always can use the semver trick to release v0.3-compatible v1.0, assuming the APIs stay stable enough.
>I really wouldn't want to bother back-porting changes. I think we could have backports be "contributions welcome". I'd be fine reviewing backports, but I don't want to do the backporting (especially if nobody's actually using it).
I agree with this, IIRC we acted similarly with v0.1 backports.
The main problem with trying to make the next release be 1.0: The release will be long-delayed because there's too much perfecting and too many potential compatibility-breaking changes.
I think we need to accept the MSRV increases for 0.2 and do a 0.2 release soon, so that we don't get into a state where we can't do a release because master isn't good enough to be 1.0.
@josephlr
FYI I temporarily disabled the review requirement as we discussed in the email. Unreviewed changes start from this [commit](https://github.com/rust-random/getrandom/commit/6c6fbefed7455bf903a9c299c18349c30d7082dd) and have to reviewed before we release v0.3.
To reply to @newpavlov here instead of in #544:
> @dhardy My plan is to release getrandom v0.3 before before rand v0.9. You will not be able to silently migrate from v0.2 to v0.3 even with [rust-random/rand#1537](https://github.com/rust-random/rand/pull/1537) because of the changes around [optional backend handling](https://github.com/rust-random/getrandom?tab=readme-ov-file#opt-in-backends).
So there are breaking changes, but not in the API. We already tell people using `rand` to use a direct dependency on `getrandom` when needing to customise the implementation so in a certain sense it would not be a breaking change to update `getrandom`, but on the other hand it could still cause issues.
I'd like to be able to release rand v1.0 soon after v0.9; I don't know if getrandom has plans for 1.0 soon?
I think we could release v1.0 relatively soon (in a year or two after the v0.3 release) assuming no issues will be found with the new APIs. One thing which I would like to do with v1.0 (here and with `rand`) is to migrate to the 2024 edition and relax our MSRV policy by telling users to rely on the new MSRV-dependent resolver. But since it involves a substantial MSRV bump, I don't think we should rush it.
From [the docs](https://doc.rust-lang.org/nightly/edition-guide/rust-2024/cargo-resolver.html),
> The resolver is a global setting for a [workspace](https://doc.rust-lang.org/nightly/cargo/reference/workspaces.html), and the setting is ignored in dependencies.
So IIUC `rand` / `getrandom` doesn't need to use Edition 2024 or resolver=3 to benefit from this; it's enough for a dependant application to use Edition 2024 / resolver=3. This means we don't need to raise our MSRV to benefit.
With that in mind, I see no point in bumping the MSRV to use Edition 2024.
---
Do you have a plan for getrandom v0.3 / something you need help with? I'd like to get rand v0.9 out *soon* because of `gen` being a reserved keyword in Edition 2024.
>So IIUC rand / getrandom doesn't need to use Edition 2024 or resolver=3 to benefit from this
In my understanding, the problem is that resolver=3 will be available only on Rust 1.85 and later. So if `rand` v0.9.0 and v0.9.1 will have MSRV equal to 1.63 and 1.70, it will create problems for hypothetical users of 1.65 tollchain. So I think it's easier to just bump MSRV to 1.85 in a hypothetical v1.0 release.
>Do you have a plan for getrandom v0.3 / something you need help with?
I plan to cut a pre-release after finishing #546. It's probably worth to do a PSA on URLO and Reddit, since the new opt-in target handling could be somewhat controversial with WASM developers.
Sorry @newpavlov for my delay in reviewing stuff for v0.3. I should have some time over the next week to review stuff. I started by reviewing #559 is there anything in particular I should look at next, or should I just start at the last time a reviewed a PR (which is https://github.com/rust-random/getrandom/commit/baae5fcb1cb508b7b7717b35a6c6f313be8d8ed2 I think)?
I also really like the organizational changes in #538 it made the code much easier to read.
@josephlr
You also can just take a look at the current state of the crate. You may have new ideas/suggestions after looking at it with fresh eyes.
I would like to get this + rand released early next week if possible. Are there any blocking issues / reviews required / other to-do items?
I don't have anything in mind, so we only need a green light from @josephlr. | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [Unreleased]
+## [0.3.0] - 2024-12-16
### Breaking Changes
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,17 +19,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `register_custom_getrandom!` macro [#504]
- Implementation of `From<NonZeroU32>` for `Error` and `Error::code` method [#507]
- Internet Explorer 11 support [#554]
+- Target-specific assocciated `Error` constants [#562]
### Changed
-- Use `ProcessPrng` on Windows 10 and up, and use RtlGenRandom on older legacy Windows versions [#415]
+- Use `ProcessPrng` on Windows 10 and up, and use `RtlGenRandom` on older Windows versions [#415]
- Do not use locale-specific `strerror_r` for retrieving error code descriptions [#440]
-- Avoid assuming usize is the native word size in the `rdrand` backend [#442]
+- Avoid assuming `usize` is the native word size in the `rdrand` backend [#442]
- Do not read from `errno` when `libc` did not indicate error on Solaris [#448]
- Switch from `libpthread`'s mutex to `futex` on Linux and to `nanosleep`-based wait loop
on other targets in the `use_file` backend [#490]
- Do not retry on `EAGAIN` while polling `/dev/random` on Linux [#522]
-- Remove separate codepath for Node.js in the `wasm_js` backend (bumps minimum supported Node.js
- version to v19) [#557]
+- Remove separate codepath for Node.js in the `wasm_js` backend
+ (bumps minimum supported Node.js version to v19) [#557]
+- Use `js_namespace` in the `wasm_js` backend [#559]
### Added
- `wasm32-wasip1` and `wasm32-wasip2` support [#499]
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +40,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `rndr` opt-in backend [#512]
- Automatic MemorySanitizer support [#521] [#571]
- `u32` and `u64` functions for generating random values of the respective type [#544]
+- `wasm32v1-none` support in the `wasm_js` backend [#560]
+- `wasm_js` crate feature which allows users to enable the `wasm_js` opt-in backend [#574]
### Fixed
- NetBSD fallback code based on `KERN_ARND` [#555]
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -59,7 +63,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#554]: https://github.com/rust-random/getrandom/pull/554
[#555]: https://github.com/rust-random/getrandom/pull/555
[#557]: https://github.com/rust-random/getrandom/pull/557
+[#559]: https://github.com/rust-random/getrandom/pull/559
+[#560]: https://github.com/rust-random/getrandom/pull/560
+[#562]: https://github.com/rust-random/getrandom/pull/562
[#571]: https://github.com/rust-random/getrandom/pull/571
+[#574]: https://github.com/rust-random/getrandom/pull/574
## [0.2.15] - 2024-05-06
### Added
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -511,6 +519,7 @@ Publish initial implementation.
## [0.0.0] - 2019-01-19
Publish an empty template library.
+[0.3.0]: https://github.com/rust-random/getrandom/compare/v0.2.15...v0.3.0
[0.2.15]: https://github.com/rust-random/getrandom/compare/v0.2.14...v0.2.15
[0.2.14]: https://github.com/rust-random/getrandom/compare/v0.2.13...v0.2.14
[0.2.13]: https://github.com/rust-random/getrandom/compare/v0.2.12...v0.2.13
| 0.2 | 2024-12-11T15:34:59Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 | 563 | Release 0.3?
We have a few changes coming up (#425, #414 , #432) which will make the following changes to the compatibility of this crate:
- Increase the Minimum Supported Rust Version (MSRV) from 1.36 (released July 4, 2019) to 1.56 (released October 21, 2021).
- Increase the supported OS version of `*-pc-windows-{gnu,msvc}` from Windows Vista (released November 30, 2006) to Windows 10 (released July 15, 2015).
- Rust increased its minimum Windows OS version from Windows 7 to Windows 10 in [February 26th, 2024](https://blog.rust-lang.org/2024/02/26/Windows-7.html).
- Older versions of Windows are still supported under the `x86_64-win7-windows-msvc` and `i686-win7-windows-msvc` targets
- We would intend to continue to support the `*-win7-*` targets (via [`RtlGenRandom`](https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom))
- We are **not** making any changes to the API of this crate
- We are **not** making any changes to the features of this crate
The [Rust Semver Compatibility Guide](https://doc.rust-lang.org/cargo/reference/semver.html) does not specify if such actions would be breaking changes. Both:
- [changing the minimum version of Rust required](https://doc.rust-lang.org/cargo/reference/semver.html#env-new-rust)
- [changing the platform and environment requirements](https://doc.rust-lang.org/cargo/reference/semver.html#env-change-requirements)
are listed as "Possibly-breaking" changes.
My personal preference would be to release these changes as `0.2.16` (not consider this a breaking change) because:
- `getrandom` is widely used throughout the Rust ecosystem so updating all callers can be somewhat tedious.
- It's not clear how a user can have a `custom` implementation work with both versions of `getrandom`.
- Both the MSRV increases and the Windows platform increases are less disruptive than an Semver-breaking change.
However, if we do decide to have this be a breaking change, we should discuss if there are any other semver-breaking changes we wish to make (see #346 and #230). Another option would just be to get consensus on #232 and release these changes as 1.0
| rust-random/getrandom | rust-random__getrandom-563 | 2025-01-25T11:47:42Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"228"
] | diff --git a/src/rdrand.rs b/src/rdrand.rs
--- a/src/rdrand.rs
+++ b/src/rdrand.rs
@@ -24,74 +25,106 @@ cfg_if! {
// Implementation Guide" - Section 5.2.1 and "Intel® 64 and IA-32 Architectures
// Software Developer’s Manual" - Volume 1 - Section 7.3.17.1.
const RETRY_LIMIT: usize = 10;
-const WORD_SIZE: usize = mem::size_of::<usize>();
#[target_feature(enable = "rdrand")]
-unsafe fn rdrand() -> Result<[u8; WORD_SIZE], Error> {
+unsafe fn rdrand() -> Option<usize> {
for _ in 0..RETRY_LIMIT {
- let mut el = mem::zeroed();
- if rdrand_step(&mut el) == 1 {
- // AMD CPUs from families 14h to 16h (pre Ryzen) sometimes fail to
- // set CF on bogus random data, so we check these values explicitly.
- // See https://github.com/systemd/systemd/issues/11810#issuecomment-489727505
- // We perform this check regardless of target to guard against
- // any implementation that incorrectly fails to set CF.
- if el != 0 && el != !0 {
- return Ok(el.to_ne_bytes());
- }
- // Keep looping in case this was a false positive.
+ let mut val = 0;
+ if rdrand_step(&mut val) == 1 {
+ return Some(val as usize);
}
}
- Err(Error::FAILED_RDRAND)
+ None
}
-// "rdrand" target feature requires "+rdrnd" flag, see https://github.com/rust-lang/rust/issues/49653.
+// "rdrand" target feature requires "+rdrand" flag, see https://github.com/rust-lang/rust/issues/49653.
#[cfg(all(target_env = "sgx", not(target_feature = "rdrand")))]
compile_error!(
- "SGX targets require 'rdrand' target feature. Enable by using -C target-feature=+rdrnd."
+ "SGX targets require 'rdrand' target feature. Enable by using -C target-feature=+rdrand."
);
-#[cfg(target_feature = "rdrand")]
-fn is_rdrand_supported() -> bool {
- true
+// Run a small self-test to make sure we aren't repeating values
+// Adapted from Linux's test in arch/x86/kernel/cpu/rdrand.c
+// Fails with probability < 2^(-90) on 32-bit systems
+#[target_feature(enable = "rdrand")]
+unsafe fn self_test() -> bool {
+ // On AMD, RDRAND returns 0xFF...FF on failure, count it as a collision.
+ let mut prev = !0; // TODO(MSRV 1.43): Move to usize::MAX
+ let mut fails = 0;
+ for _ in 0..8 {
+ match rdrand() {
+ Some(val) if val == prev => fails += 1,
+ Some(val) => prev = val,
+ None => return false,
+ };
+ }
+ fails <= 2
}
-// TODO use is_x86_feature_detected!("rdrand") when that works in core. See:
-// https://github.com/rust-lang-nursery/stdsimd/issues/464
-#[cfg(not(target_feature = "rdrand"))]
-fn is_rdrand_supported() -> bool {
- use crate::util::LazyBool;
+fn is_rdrand_good() -> bool {
+ #[cfg(not(target_feature = "rdrand"))]
+ {
+ // SAFETY: All Rust x86 targets are new enough to have CPUID, and we
+ // check that leaf 1 is supported before using it.
+ let cpuid0 = unsafe { arch::__cpuid(0) };
+ if cpuid0.eax < 1 {
+ return false;
+ }
+ let cpuid1 = unsafe { arch::__cpuid(1) };
- // SAFETY: All Rust x86 targets are new enough to have CPUID, and if CPUID
- // is supported, CPUID leaf 1 is always supported.
- const FLAG: u32 = 1 << 30;
- static HAS_RDRAND: LazyBool = LazyBool::new();
- HAS_RDRAND.unsync_init(|| unsafe { (arch::__cpuid(1).ecx & FLAG) != 0 })
+ let vendor_id = [
+ cpuid0.ebx.to_le_bytes(),
+ cpuid0.edx.to_le_bytes(),
+ cpuid0.ecx.to_le_bytes(),
+ ];
+ if vendor_id == [*b"Auth", *b"enti", *b"cAMD"] {
+ let mut family = (cpuid1.eax >> 8) & 0xF;
+ if family == 0xF {
+ family += (cpuid1.eax >> 20) & 0xFF;
+ }
+ // AMD CPUs families before 17h (Zen) sometimes fail to set CF when
+ // RDRAND fails after suspend. Don't use RDRAND on those families.
+ // See https://bugzilla.redhat.com/show_bug.cgi?id=1150286
+ if family < 0x17 {
+ return false;
+ }
+ }
+
+ const RDRAND_FLAG: u32 = 1 << 30;
+ if cpuid1.ecx & RDRAND_FLAG == 0 {
+ return false;
+ }
+ }
+
+ // SAFETY: We have already checked that rdrand is available.
+ unsafe { self_test() }
}
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
- if !is_rdrand_supported() {
+ static RDRAND_GOOD: LazyBool = LazyBool::new();
+ if !RDRAND_GOOD.unsync_init(is_rdrand_good) {
return Err(Error::NO_RDRAND);
}
-
- // SAFETY: After this point, rdrand is supported, so calling the rdrand
- // functions is not undefined behavior.
- unsafe { rdrand_exact(dest) }
+ // SAFETY: After this point, we know rdrand is supported.
+ unsafe { rdrand_exact(dest) }.ok_or(Error::FAILED_RDRAND)
}
+// TODO: make this function safe when we have feature(target_feature_11)
#[target_feature(enable = "rdrand")]
-unsafe fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
+unsafe fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Option<()> {
// We use chunks_exact_mut instead of chunks_mut as it allows almost all
// calls to memcpy to be elided by the compiler.
- let mut chunks = dest.chunks_exact_mut(WORD_SIZE);
+ let mut chunks = dest.chunks_exact_mut(size_of::<usize>());
for chunk in chunks.by_ref() {
- chunk.copy_from_slice(slice_as_uninit(&rdrand()?));
+ let src = rdrand()?.to_ne_bytes();
+ chunk.copy_from_slice(slice_as_uninit(&src));
}
let tail = chunks.into_remainder();
let n = tail.len();
if n > 0 {
- tail.copy_from_slice(slice_as_uninit(&rdrand()?[..n]));
+ let src = rdrand()?.to_ne_bytes();
+ tail.copy_from_slice(slice_as_uninit(&src[..n]));
}
- Ok(())
+ Some(())
}
| In the `rdrand` crate, I saw very similar logic:
```
if el == 0 || el == !0 {
// Certain AMD CPUs may return broken data for `rdrand`. In those cases they
// will return a bitpattern where all-ones is set. In case this was a
// false-positive we just try again. If this happens `RETRY_LIMIT` times, we
// will naturally fall into the `HardwareFailure` branch.
```
Interestingly, the rdrand crate source code says that the bit pattern is all-ones when an AMD CPU fails, but it also checks all-zeroes, but doesn't explain why. And getrandom does the same, without any explanation.
I dug into the systemd patch at https://github.com/poettering/systemd/commit/c6372bea618554f9688cbe2222c394b11002388d and it also checks both values. It has a clearer explanation of the reasoning:
> ```
> /* Apparently on some AMD CPUs RDRAND will sometimes (after a suspend/resume cycle?) report success
> * via the carry flag but nonetheless return the same fixed value -1 in all cases. This appears to be
> * a bad bug in the CPU or firmware. Let's deal with that and work-around this by explicitly checking
> * for this special value (and also 0, just to be sure) and filtering it out.
> ```
So the value 0 is being screened out "just in case." Doesn't sound good to me.
I think that what might be not too terrible for systemd in that particular circumstance may be not quite good enough for a general purpose `getrandom` library.
I try not to comment on this repo too much (since I passed off maintainership), but I do remember a little about this issue.
> RDRAND-based output is (too) biased
Biased, yes, and you are right that this was initially only considered in the case of `u64` values. But is 1-in-2^31 bias too much? Depends on the application I guess; certainly this case is more arguable than for 1-in-2^63. We could perhaps set the minimum output size at 64-bits?
> So the value 0 is being screened out "just in case." Doesn't sound good to me.
> It seems like Google has reason to believe that some family 0x17 models may also be bad.
I wish we could just go to the AMD website and find a listing of all possible failure cases. Alas, we lack comprehensive sources of information, and also the possibility that this might later be discovered in future CPUs, so is there much more we *can* do?
Apparently this also affects some of the latest AMD CPUs, but in a harder-to-detect way: [collisions on Ryzen 5900X](https://github.com/systemd/systemd/issues/18184#issuecomment-758155962).
(Perhaps the better answer is never to trust RDRAND on an AMD CPU? Not to say there aren't [potential issues](https://en.wikipedia.org/wiki/RDRAND#Security_issues) with other vendors.)
Thanks @dhardy. I remember that second systemd issue now. Here's [an important comment](https://github.com/systemd/systemd/issues/18184#issuecomment-758119633) from that issue:
> systemd uses RDRAND to generate UUIDs only, nothing else, and exactly as suggested by the whitepapers. if this generates non-unique UUIDs that so easily collide then the RNG is just rubbish.
I don't know if that claim is accurate, but if it is accurate then it explains why systemd is comfortable with using a non-uniform RNG.
The `rdrand` crate was also doing the same thing as this; over the weekend they changed their implementation to avoid filtering out usize::MIN and usize::MAX; see https://github.com/nagisa/rust_rdrand/issues/16#issuecomment-932976717.
I think we should introduce separate code paths for affected families and everyone else. I have proposed it previously, but we chose the current approach for simplicity sake. It would be nice to have more info on the 0x17 family.
>So the value 0 is being screened out "just in case." Doesn't sound good to me.
This hardware bug is **really** scary, so I think "just in case" is perfectly fine here. I think it's better to have small bias, than potentially zeroed nonces/keys. Personally, I think that on affected families it may be worth to go even further and check that we do not encounter collisions by calling the step function twice and checking that it returns different results each time.
> > So the value 0 is being screened out "just in case." Doesn't sound good to me.
>
> This hardware bug is **really** scary, so I think "just in case" is perfectly fine here.
Why only all-zeroes and all-ones are scary, but no other values? My understanding is that AMD documented and/or somebody observed that all-ones happen in the case of the specific AMD failure; did AMD document or did somebody observe that the all-zero value occurs for these failures?
> Personally, I think that on affected families it may be worth to go even further and check that we do not encounter collisions by calling the step function twice and checking that it returns different results each time.
False positives would occur. (This type of test is documented in NIST/FIPS standards and implementation guidance, FYI.)
As I mentioned in #230, I don't think it is a good idea to default to using RDRAND for any target. What I would prefer is that there is no purely-RDRAND-based implementation in `getrandom`; instead, when targeting the OS-less targets, users can register their own custom RNG using the existing mechanism, and if they want their custom RNG to use (just) RDRAND then they could use the rdrand crate for that. That would remove the use of RDRAND completely from `getrandom`. Then people could build "real" CSPRNGs that use RDRAND only as an entropy source instead of as the entire CSPRNG.
> Why only all-zeroes and all-ones are scary, but no other values? My understanding is that AMD documented and/or somebody observed that all-ones happen in the case of the specific AMD failure; did AMD document or did somebody observe that the all-zero value occurs for these failures?
Some context on why that check is the way it is. The check is basically "did the implementation forget to set the CF flag". Both AMD and Intel document what value is put in the destination register on failure. For AMD it is all 1s (as discussed above), for Intel it is all 0s (see section 5.2 of [Intel's DRNG whitepaper](https://www.intel.com/content/www/us/en/developer/articles/guide/intel-digital-random-number-generator-drng-software-implementation-guide.html)). So we just check for both.
This is obviously not an ideal state, as ideally the `RDRAND` instruction would never have bugs on any architecture, but it is what it is.
> That would remove the use of RDRAND completely from `getrandom`.
I agree on many of the things in #230, but removing RDRAND completely is unlikely. Many users of this crate (myself included) rely on this functionality and its simple ergonomics, and I wouldn't want to break them.
I was looking into this issue today, and I think we should just mimic what the Linux Kernel does here:
- Check if `cpuid` claims to support RDRAND
- Unconditionally disable on AMD families 0x15 ([Bulldozer](https://en.wikipedia.org/wiki/Bulldozer_(microarchitecture)) / [Piledriver](https://en.wikipedia.org/wiki/Piledriver_(microarchitecture)) / [Steamroller](https://en.wikipedia.org/wiki/Steamroller_(microarchitecture)) / [Excavator](https://en.wikipedia.org/wiki/Excavator_(microarchitecture))) and 0x16 ([Jaguar](https://en.wikipedia.org/wiki/Jaguar_(microarchitecture)) / [Puma](https://en.wikipedia.org/wiki/Puma_(microarchitecture)))
- These are the known-bad implementations where AMD CPUs will report success in RDRAND despite returning `usize::MAX`. This is the bug the current code tries to avoid.
- Linux implementation in [`init_amd_bd`](https://github.com/torvalds/linux/blob/5af6ce7049365952f7f023155234fe091693ead1/arch/x86/kernel/cpu/amd.c#L855-L860) and [`init_amd_jg`](https://github.com/torvalds/linux/blob/5af6ce7049365952f7f023155234fe091693ead1/arch/x86/kernel/cpu/amd.c#L832-L837)
- Given that families older than 0x15 didn't even have RDRAND, it's fine to just check `is_amd && family < 0x17`.
- When doing the CPU checks in init, also run a small collision test to make sure we aren't repeating values
- Linux implementation in [`x86_init_rdrand`](https://github.com/torvalds/linux/blob/5af6ce7049365952f7f023155234fe091693ead1/arch/x86/kernel/cpu/rdrand.c#L33-L42)
- Don't check/bias the output when doing the normal buffer fills as part of `getrandom_inner`. This should avoid any issues around bias (either on 32-bit or 64-bit platforms). It also happens to make the generated code smaller and easier to inline.
This would also make our code _almost_ match that in BoringSSL as well, except for them disabling RDRAND on `family 0x17, models 0x70–0x7f`, as @briansmith noted in https://github.com/rust-random/getrandom/issues/228#issue-1012707302. This change was added in [BoringSSL change 37604](https://boringssl-review.googlesource.com/c/boringssl/+/37604), and I did some internal and external digging to figure out _why_ ths change was added.
It turns out it was added in response to the Zen 2 RDRAND issues ([Phoronix](https://www.phoronix.com/news/Ryzen-3K-RdRand-Systemd-Maybe), [Reddit post](https://www.reddit.com/r/crypto/comments/dp0pr2/rdrand_on_unptached_zen_2_always_returns_0xffff/)). As far as I can tell, a bad BIOS caused RDRAND to always _fail_, but still signal failure correctly via `CF`. On BoringSSL, this would be an issue, so the feature is disabled. However, for this library, we will just (always) return an error, so no blacklisting for that family/model is needed. | diff --git a/src/rdrand.rs b/src/rdrand.rs
--- a/src/rdrand.rs
+++ b/src/rdrand.rs
@@ -5,10 +5,11 @@
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
-//! Implementation for SGX using RDRAND instruction
-use crate::{util::slice_as_uninit, Error};
-use core::mem::{self, MaybeUninit};
+use crate::{
+ util::{slice_as_uninit, LazyBool},
+ Error,
+};
+use core::mem::{size_of, MaybeUninit};
cfg_if! {
if #[cfg(target_arch = "x86_64")] {
| 0.2 | 2023-02-02T22:21:24Z | 9ceb7e56ec88cdb3b63076bcbe744f6927d48387 | 335 | RDRAND-based output is (too) biased
See https://github.com/rust-random/getrandom/blob/30308ae845b0bf3839e5a92120559eaf56048c28/src/rdrand.rs#L33-L42, merged from PR #48:
```
if rdrand_step(&mut el) == 1 {
// AMD CPUs from families 14h to 16h (pre Ryzen) sometimes fail to
// set CF on bogus random data, so we check these values explicitly.
// See https://github.com/systemd/systemd/issues/11810#issuecomment-489727505
// We perform this check regardless of target to guard against
// any implementation that incorrectly fails to set CF.
if el != 0 && el != !0 {
return Ok(el.to_ne_bytes());
}
// Keep looping in case this was a false positive.
}
```
The condition `if el != 0 && el != !0` is testing that the value returned by RDRAND, after it reports success, is not zero or all-one bits, i.e. never `usize::MIN` or `usize::MAX`. Consequently, `getrandom::getrandom` will never return a result where there a single word is zero or all-one bits, where as word is a 4-byte chunk on 32-bit x86 or a 8-byte chunk on 64-bit x86, when the RDRAND implementation is being used. Such values are expected to occur every 2/2^N words on average. As a result, any use of `getrandom::getrandom` returns results that are wrongly biased; 2/2^N values are rejected on an N-bit platform.
32-bit x86 support for the RDRAND feature was added in PR #134, after PR #48. The analysis on the bias when the code was implemented was based on the probability 2/2^64 which is correct when this code runs on a 64-bit CPU, but not for when it runs on a 32-bit CPU. I suspect that when PR #134 was under consideration, the difference in the bias was perhaps overlooked. The bias is notably worse on 32-bit platforms since 2/2^32 is much more likely than 2/2^64.
Outside of cryptography, I find the present solution particularly unfortunate because if getrandom's output is used for randomized testing of a 64-bit/32-bit function on x86_64/x86 on a target for which the RDRAND implementation is used, the important boundary conditions of the values `usize::MIN` and `usize::MAX` will never be reached, ever!
In the context of implementing cryptographic functions, and especially keygen and nonce generation, I suspect any user of this crate is likely to get pestered about this bias and will have to address it in some way.
In any case, I think the present solution is weird enough that it is worth having more eyes on it and more discussion, and also I hope we could find a better solution.
Incidentally, BoringSSL's code has this to say:
```
// Also disable for family 0x17, models 0x70–0x7f, due to possible RDRAND
// failures there too.
```
It seems like Google has reason to believe that some family 0x17 models may also be bad. So the comment indicating the problem is only with families 14h-16h may be worth updating, at least.
| rust-random/getrandom | rust-random__getrandom-335 | 2023-02-09T00:24:48Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"289"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -208,7 +208,9 @@ jobs:
usesh: true
prepare: |
/usr/sbin/pkg_add rust
- run: cargo test
+ run: |
+ cargo test
+ RUSTFLAGS="--cfg getrandom_test_netbsd_fallback -D warnings" cargo test
# This job currently fails:
# https://github.com/rust-random/getrandom/actions/runs/11405005618/job/31735653874?pr=528
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -83,6 +83,7 @@ check-cfg = [
'cfg(getrandom_sanitize)',
'cfg(getrandom_browser_test)',
'cfg(getrandom_test_linux_fallback)',
+ 'cfg(getrandom_test_netbsd_fallback)',
]
[package.metadata.docs.rs]
diff --git a/src/backends/netbsd.rs b/src/backends/netbsd.rs
--- a/src/backends/netbsd.rs
+++ b/src/backends/netbsd.rs
@@ -53,7 +49,7 @@ fn init() -> *mut c_void {
static NAME: &[u8] = b"getrandom\0";
let name_ptr = NAME.as_ptr().cast::<libc::c_char>();
let mut ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name_ptr) };
- if ptr.is_null() {
+ if ptr.is_null() || cfg!(getrandom_test_netbsd_fallback) {
// Verify `polyfill_using_kern_arand` has the right signature.
const POLYFILL: GetRandomFn = polyfill_using_kern_arand;
ptr = POLYFILL as *mut c_void;
| I agree that this testing will be challenging for Platforms that aren't Tier 1, but I think we should look into it for Linux and MacOS. Maybe using LD_PRELOAD shenanigans with an older libc could work?
For the syscall vs file fallback, it would be interesting if we could get a ptrace-based test to work.
>Maybe using LD_PRELOAD shenanigans with an older libc could work?
Using just older `libc` will not help since we use `libc::syscall`. It may be worth to change code of `getrandom_test_linux_fallback` to use `dlopen` instead. | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Memory sanitizer support gated behind `getrandom_sanitize` configuration flag [#521]
- `u32` and `u64` functions for generating random values of the respective type [#544]
+### Fixed
+- NetBSD fallback code based on `KERN_ARND` [#555]
+
[#415]: https://github.com/rust-random/getrandom/pull/415
[#440]: https://github.com/rust-random/getrandom/pull/440
[#442]: https://github.com/rust-random/getrandom/pull/442
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +57,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#542]: https://github.com/rust-random/getrandom/pull/542
[#544]: https://github.com/rust-random/getrandom/pull/544
[#554]: https://github.com/rust-random/getrandom/pull/554
+[#555]: https://github.com/rust-random/getrandom/pull/555
## [0.2.15] - 2024-05-06
### Added
diff --git a/src/backends/netbsd.rs b/src/backends/netbsd.rs
--- a/src/backends/netbsd.rs
+++ b/src/backends/netbsd.rs
@@ -30,17 +30,13 @@ unsafe extern "C" fn polyfill_using_kern_arand(
// NetBSD will only return up to 256 bytes at a time, and
// older NetBSD kernels will fail on longer buffers.
let mut len = cmp::min(buflen, 256);
- let expected_ret = libc::c_int::try_from(len).expect("len is bounded by 256");
-
let ret = unsafe { libc::sysctl(MIB.as_ptr(), MIB_LEN, buf, &mut len, ptr::null(), 0) };
- if ret == expected_ret {
- libc::ssize_t::try_from(ret).expect("len is bounded by 256")
- } else if ret == -1 {
- -1
- } else {
+ match ret {
+ 0 if len <= 256 => libc::ssize_t::try_from(len).expect("len is in the range of 0..=256"),
+ -1 => -1,
// Zero return result will be converted into `Error::UNEXPECTED` by `sys_fill_exact`
- 0
+ _ => 0,
}
}
| 0.2 | 2024-12-04T14:01:24Z | 584926ef40fd69a6c4b64dd7acca997e5c16330b | 555 | For platforms that implement runtime fallback logic, all paths should be tested
Consider the case of Linux. We hope to use the `getrandom` syscall and then if that fails, we fall back to doing file I/O. We should test at least the following scenerios:
* Linux returns `ENOSYS`, which should trigger the fallback to file I/O.
* Linux returns `EPERM`, which is presently expected to do the same fallback, though there's an issue on file to change this.
* The syscall succeeds.
This type of exhaustive testing might not be practical on all targets. However, BoringSSL has shown how to do it on Linux; see https://boringssl.googlesource.com/boringssl/+/refs/heads/master/crypto/fipsmodule/rand/urandom_test.cc.
Backends with runtime fallback logic:
- [x] `linux_android_with_fallback` (fallack to `/dev/urandom`, [tested](https://github.com/rust-random/getrandom/blob/master/.github/workflows/tests.yml#L62-L64) using the `getrandom_test_linux_fallback` configuration flag)
- [x] `netbsd` (fallback to `KERN_ARND`, tested using the `getrandom_test_netbsd_fallback` configuration flag)
- [x] `wasm_js` (runtime selection between Web and Node.js APIs, [tested](https://github.com/rust-random/getrandom/blob/master/.github/workflows/tests.yml#L229-L272) in CI)
| rust-random/getrandom | rust-random__getrandom-555 | 2024-12-04T15:03:54Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"424"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -71,6 +71,9 @@ jobs:
- env:
RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_getrandom"
run: cargo test ${{ matrix.cargo_test_opts }} --target=${{ matrix.target }} --features=std
+ - env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_rustix"
+ run: cargo test ${{ matrix.cargo_test_opts }} --target=${{ matrix.target }} --features=std
- env:
RUSTFLAGS: -Dwarnings --cfg getrandom_test_linux_fallback
run: cargo test --features=std
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,23 +18,60 @@ cfg-if = "1"
compiler_builtins = { version = "0.1", optional = true }
core = { version = "1.0", optional = true, package = "rustc-std-workspace-core" }
-[target.'cfg(unix)'.dependencies]
+# linux_android / linux_android_with_fallback
+[target.'cfg(all(any(target_os = "linux", target_os = "android"), not(any(target_env = "", getrandom_backend = "linux_rustix", getrandom_backend = "custom"))))'.dependencies]
libc = { version = "0.2.154", default-features = false }
+# linux_rustix
+[target.'cfg(all(any(target_os = "linux", target_os = "android"), any(target_env = "", getrandom_backend = "linux_rustix")))'.dependencies]
+rustix = { version = "0.38", default-features = false, features = ["rand"] }
+
+# apple-other
+[target.'cfg(any(target_os = "ios", target_os = "visionos", target_os = "watchos", target_os = "tvos"))'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# getentropy
+[target.'cfg(any(target_os = "macos", target_os = "openbsd", target_os = "vita", target_os = "emscripten"))'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# getrandom
+[target.'cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "hurd", target_os = "illumos", all(target_os = "horizon", target_arch = "arm")))'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# netbsd
+[target.'cfg(target_os = "netbsd")'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# solaris
+[target.'cfg(target_os = "solaris")'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# use_file
+[target.'cfg(any(target_os = "haiku", target_os = "redox", target_os = "nto", target_os = "aix"))'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# vxworks
+[target.'cfg(target_os = "vxworks")'.dependencies]
+libc = { version = "0.2.154", default-features = false }
+
+# wasi (0.2 only)
[target.'cfg(all(target_arch = "wasm32", target_os = "wasi", target_env = "p2"))'.dependencies]
wasi = { version = "0.13", default-features = false }
+# windows7
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
windows-targets = "0.52"
+# wasm_js
[target.'cfg(all(getrandom_backend = "wasm_js", any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dependencies]
wasm-bindgen = { version = "0.2.89", default-features = false }
js-sys = "0.3"
-[target.'cfg(all(getrandom_backend = "wasm_js", getrandom_browser_test, any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dev-dependencies]
+[target.'cfg(all(getrandom_backend = "wasm_js", getrandom_browser_test, target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies]
wasm-bindgen-test = "0.3.39"
[features]
-# Implement std-only traits for getrandom::Error
+# Implement std::error::Error for getrandom::Error and
+# use std to retrieve OS error descriptions
std = []
# Unstable feature to support being a libstd dependency
rustc-dep-of-std = ["compiler_builtins", "core"]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -42,7 +79,7 @@ rustc-dep-of-std = ["compiler_builtins", "core"]
[lints.rust.unexpected_cfgs]
level = "warn"
check-cfg = [
- 'cfg(getrandom_backend, values("custom", "rdrand", "rndr", "linux_getrandom", "wasm_js", "esp_idf"))',
+ 'cfg(getrandom_backend, values("custom", "rdrand", "rndr", "linux_getrandom", "linux_rustix", "wasm_js", "esp_idf"))',
'cfg(getrandom_browser_test)',
'cfg(getrandom_test_linux_fallback)',
]
| I think #401 is relevant here. We need a way of doing raw syscalls for this. Ideally, it would be handled by the [`linux-raw-sys`](https://github.com/sunfishcode/linux-raw-sys) crate, but @sunfishcode is [hesitant](https://github.com/bytecodealliance/rustix/issues/1055) to add raw syscall functions to it.
I think if we want to support this target, we should just write the inline assembly to invoke the `x86_64` `syscall` instruction, and hardcode the raw syscall number (318).
I agre with @sunfishcode that supporting a general mechanism for invoking _any_ syscall on _any_ Linux CPU architecture is _very_ complicated (vDSO, some syscalls may or may not return, `vfork`, inline assembly isn't stable on all architectures supported by Rust, etc...).
But the situation for `getrandom(2) + x86_64` specifically is _much_ simpler, Linux only uses `syscall` on `x86_64`, and `x86_64` inline assembly is stable. So the implementation can just be:
```rust
const NR_GETRANDOM: u32 = 318;
pub fn getrandom_syscall(buf: &mut [MaybeUninit<u8>], flags: u32) -> isize {
unsafe {
let ret;
asm!(
"syscall",
inlateout("rax") NR_GETRANDOM as isize => ret,
in("rdi") buf.as_mut_ptr(),
in("rsi") buf.len(),
in("rdx") flags,
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
ret
}
}
```
@josephlr
Hm, you are right. If the raw target is limited to x86-64 it would be the easiest way to do this.
We probably can do it for other target arches as well (on x86 we can just use `int 0x80` for simplicity) and gate it behind a hypothetical `linux_raw_syscall` feature.
In [the PR](https://github.com/rust-lang/rust/pull/125023), @morr0ne said that x86_64-unknown-linux-none won't have libc, so it's likely that many crates will use rustix for I/O on `*-linux-none`, so rustix will often be in people's dependency trees already. Perhaps that makes it feasible for getrandom to just use `rustix::rand::getrandom_uninit` on x86_64-unknown-linux-none.
If it were just getrandom it may seem ok to hard-code a little bit of `asm`, but if other crates start following this example and we end up with many crates doing their own syscall `asm`s, I think that would be unfortunate. And, it's reasonable to anticipate more `linux-none` targets than just x86_64.
> In [the PR](https://github.com/rust-lang/rust/pull/125023), @morr0ne said that x86_64-unknown-linux-none won't have libc, so it's likely that many crates will use rustix for I/O on `*-linux-none`, so rustix will often be in people's dependency trees already. Perhaps that makes it feasible for getrandom to just use `rustix::rand::getrandom_uninit` on x86_64-unknown-linux-none.
The *-linux-none targets heavily rely on something like rustix to work; at the moment its basically guaranteed that rustix will already be in the dependency tree.
> If it were just getrandom it may seem ok to hard-code a little bit of `asm`, but if other crates start following this example and we end up with many crates doing their own syscall `asm`s, I think that would be unfortunate. And, it's reasonable to anticipate more `linux-none` targets than just x86_64.
The x86_64-unknown-linux-none target is just the first of other *-linux-none targets. I plan to implement at the very least aarch64 and riscv64gc targets. Using asm here would mean having to implement such syscall manually for each potential target.
`rustix` does a lot of things and it's a relatively big dependency (42k LoCs in `src/` according to `tokei`). As I wrote in the other issue, I like `rustix` and use it in my projects, but it's often prohibitively big for certain things. `getrandom` is just one of the examples. Another example is the `io-uring` crate, it needs only 3 syscalls and it handles associated types by itself.
This is why I would strongly prefer to have raw syscalls in the `linux-raw-sys` crate. In my opinion, the safety arguments against it just don't hold water in the light of the `libc::sycall` existence. Yes, it's an extremely dangerous `unsafe` tool and most people should use `rustix`, but it does not mean it should not be exposed. Arguably, it's similar to how we often expose `*-sys` crates, while users are directed toward safe wrappers.
If raw syscalls will not be added to `linux-raw-sys`, then our next best option is to define raw syscalls by ourselves as proposed by @josephlr above. Outside of the x86 targets (if we do not want to use `int 0x80`), it's a relatively straightforward piece of code.
@josephlr wrote:
> I think if we want to support this target, we should just write the inline assembly to invoke the x86_64 syscall instruction, and hardcode the raw syscall number (318).
I agree with this suggestion, and this is what I'm planning to do in *ring* for all `x86_64-*-linux-*` targets.
getrandom shouldn't add rustix as a dependency for this.
At the most, we could have a feature flag to use rustix instead of the inline assembly support. I suspect there are reason why some rustix users would prefer this, e.g. if they are using rustix to port to a non-Linux OS. But there's a separate issue for rustix already, to track this.
If getrandom is going to have the inline assembly, it should use the inline assembly for all `x86_64-*-linux-*` targets and eliminate the libc dependency for these targets, so that it gets tested continuously.
> This is why I would strongly prefer to have raw syscalls in the linux-raw-sys crate.
I would rather not have getrandom depend on `linux-raw-sys crate`. Chances are high that there will be bugs in `linux-raw-sys crate` that will not affect `getrandom` but which would trigger dependency management tools, causing a lot of churn and wasted effort.
>Chances are high that there will be bugs in linux-raw-sys crate that will not affect getrandom but which would trigger dependency management tools, causing a lot of churn and wasted effort.
I don't think it's likely. The crate is a largely automatic conversion of the Linux headers and has almost no issues in its tracker despite being used actively (mostly through `rustix`). Comparatively, `libc` is a more problematic dependency and it has caused several breakages in `getrandom` for various reasons.
I think that maintaining inline assembly for syscalls and syscall numbers (rant: I wish Linux had stable syscall numbers across targets...) for various targets should be outside of the `getrandom`'s area of responsibility. Ideally, we need THE crate for doing raw Linux syscall stuff, which would be used across the crates ecosystem. `linux-raw-sys` looks like the best candidate for this right now.
What are the practical problems with using rustix for just *-linux-none, and leaving the rest of getrandom as-is?
@josephlr wrote:
> But the situation for getrandom(2) + x86_64 specifically is much simpler, Linux only uses syscall on x86_64, and x86_64 inline assembly is stable. So the implementation can just be:
That would support the target when the `dev/urandom` fallback is disabled. When they added this target, I asked them to commit to a minimum kernel version that would include the `getrandom` syscall, but they didn't want to. Thus, the minimum kernel version should be assumed to be the same as the Rust project's minimum in general for x86_64-linux; i.e. a `dev/urandom` fallback would be needed for this target as well.
FYI: In *ring*, for `*-*-linux-*`, I am considering requiring the user to opt into a libstd dependency for the `dev/urandom` fallback, and implementing the syscall much like @josephlr proposed. I would be willing to help `getrandom` maintain a standalone syscall wrapper.
> What are the practical problems with using rustix for just *-linux-none, and leaving the rest of getrandom as-is?
At least for me (*ring*), I don't want to (in some sense, can't) have divergent codepaths for the `x86_64-*-linux-*` targets (in configurations for which the `dev/urandom` fallback is disabled). I expect there will be many rustix-like things in the next few years, unless/until rustix becomes a rust-lang project.
> At least for me (_ring_), I don't want to (in some sense, can't) have divergent codepaths for the `x86_64-*-linux-*` targets. I expect there will be many rustix-like things in the next few years, unless/until rustix becomes a rust-lang project.
I'm not familiar with ring. What are the practical considerations around using different codepaths for the `x86_64-*-linux-*` targets?
> I expect there will be many rustix-like things in the next few years, unless/until rustix becomes a rust-lang project.
If we only used rustix for `*-linux-none`, which very few people are using today, how much of a practical concern is this?
>What are the practical problems with using rustix for just *-linux-none, and leaving the rest of getrandom as-is?
1) Complexity and general size. It increases compilation times and makes it harder to review code in security-sensitive settings.
2) It increases chances of accidentally pulling `libc` (e.g. by enabling features). You could `cfg` this out for `*-linux-none` targets, but it will make `rustix` less consistent (e.g. it will be strange if the `use-libc` feature will have no effect).
3) It has a relatively high MSRV, which is likely to be bumped in future. (This point will be no longer relevant after wide adoption of the MSRV-aware resolver)
4) It evolves faster than `linux-raw-sys` and has a much bigger API surface, which increases downstream maintenance burden and probability of introducing new bugs.
I will reverse the question: what are the practical problems with exposing raw syscall functions in `linux-raw-sys`? As I wrote above and in the `rustix` issue, I don't consider the safety argument valid. The only stumbling block which I see is the vDSO stuff on x86 targets. One potential solution for this is to use `int 0x80` (or potentially `sysenter`) in `linux-raw-sys` and implement vDSO-based syscalls in a separate crate or leave it in `rustix`.
> If we only used rustix for `*-linux-none`, which very few people are using today, how much of a practical concern is this?
I am using `*-linux-none` without rustix for *ring* specifically for unspecified reasons.
> That would support the target when the `dev/urandom` fallback is disabled. When they added this target, I asked them to commit to a minimum kernel version that would include the `getrandom` syscall, but they didn't want to. Thus, the minimum kernel version should be assumed to be the same as the Rust project's minimum in general for x86_64-linux; i.e. a `dev/urandom` fallback would be needed for this target as well.
When adding the target I specifically did not want to add a minimum version because I felt it was too soon considering I was the only user of the target. Seeing there is interest in adding support for the *-linux-none target(s) in getrandom then it is reasonable to bump the minimum kernel version to support the required syscall.
Regarding the rustix/linux-raw-sys argument I believe we are missing some in-between crate.
Currently rustix bridges the gap between libc and libc-less targets by having both a linux-raw-sys backend and a libc backend. However the linux-raw-sys backend isn't truly a "backend" since it only provides raw definition to kernel headers.
I think a proper solution would be to have a "linux-syscall" crate that depends on linux-raw-sys and provides access to linux syscalls; rustix could then depend on both this new crate and libc to provide a unified api like it does today. Projects like getrandom that cannot or do not want to depend on rustix can depend directly on the new "linux-syscall" crate to talk to the kernel.
>However the linux-raw-sys backend isn't truly a "backend" since it only provides raw definition to kernel headers.
This is why I created https://github.com/sunfishcode/linux-raw-sys/pull/116.
>I think a proper solution would be to have a "linux-syscall" crate that depends on linux-raw-sys and provides access to linux syscalls
I don't think it makes much sense to introduce a separate crate. You wrote yourself that this hypothetical crate would need to depend on `linux-raw-sys` and I don't see much use for `linux-raw-sys` in its current form without syscall functions. It's just that the syscall functions reside in `rustix` and not exposed in public API. So why not keep them directly in `linux-raw-sys`?
Drawing parallels with the classic `*-sys` crates, they provide not only type definitions, but also functions which work with those types. As I see it, the only difference with `linux-raw-sys` is that instead of wrapping (shared) library functions it should wrap syscall "functions".
> I don't think it makes much sense to introduce a separate crate. You wrote yourself that this hypothetical crate would need to depend on `linux-raw-sys` and I don't see much use for `linux-raw-sys` in its current form without syscall functions. It's just that the syscall functions reside in `rustix` and not exposed in public API. So why not keep them directly in `linux-raw-sys`?
>
> Drawing parallels with the classic `*-sys` crates, they provide not only type definitions, but also functions which work with those types. As I see it, the only difference with `linux-raw-sys` is that instead of wrapping (shared) library functions it should wrap syscall "functions".
The linux-raw-sys crate cannot provide a syscall function because such a function does not exist. Currently the api is generated from the kernel userspace api in the same way *-sys crates are generated from C headers. The kernel does not provide any function to call syscalls but just the appropriate definition to create a wrapper manually. Such a wrapper would be outside the scope of a *-sys crate
>The linux-raw-sys crate cannot provide a syscall function because such a function does not exist.
>Such a wrapper would be outside the scope of a *-sys crate
I disagree. For most practical intents and purposes syscalls are functions, they just have a "weird" ABI, which can not be properly described in C headers (well, I guess technically you could do it? but historically people don't do it for various reasons). The items defined in the Linux headers are intended to by used with syscalls, so, arguably, it makes sense to have them in one crate.
That said, I am fine with having a separate syscall crate when compared to the current status quo. I guess such crate could be relatively stable, while `linux-raw-sys` may need new releases on future Linux kernel releases which introduce new stuff in public API.
> I disagree. For most practical intents and purposes syscalls are functions, they just have a "weird" ABI, which can not be properly described in C headers (well, I guess technically you could do it? but historically people don't do it for various reasons). The items defined in the Linux headers are intended to by used with syscalls, so, arguably, it makes sense to have them in one crate.
Perhaps I didn't explain myself properly. What I mean to say is that syscalls are not something we can automatically generate but need to be manually implemented. linux-raw-sys is fully generated code.
> That said, I am fine with having a separate syscall crate when compared to the current status quo. I guess such crate could be relatively stable, while `linux-raw-sys` may need new releases on future Linux kernel releases which introduce new stuff in public API.
That is somewhat the idea however we really need @sunfishcode input on this
> Perhaps I didn't explain myself properly. What I mean to say is that syscalls are not something we can automatically generate but need to be manually implemented. linux-raw-sys is fully generated code.
I think it would be _possible_ for the `linux-raw-sys` crate to generate the syscall wrapper functions, as all their information is present in the various Linux headers, so they could (in theory) be auto-generated. For example:
- `include/uapi/asm-generic/unistd.h` (and arch-specific files) defines `__NR_getrandom` and references `sys_getrandom`
```c
#define __NR_getrandom 278
__SYSCALL(__NR_getrandom, sys_getrandom)
```
- `include/linux/syscalls.h` defines the prototype for `sys_getrandom`
```c
asmlinkage long sys_getrandom(char __user *buf, size_t count, unsigned int flags);
```
- `linux_raw_sys::general::__NR_getrandom` would still exist as a constant
- `linux_raw_sys::syscalls::sys_getrandom` would be a function whose implementation could be generated based on the "ABI" value in the syscall table:
```rust
#[inline]
pub unsafe fn sys_getrandom(buf: *mut c_char, count: c_size_t, flags: c_uint) -> c_long
```
- There would not be a generic `syscall()` function. I agree with the above points that a function which can invoke _any_ syscall is impossible to implement reliably.
However, I definitely recognize that such auto-generation is quite complex, compared to what `linux-raw-sys` currently does.
Zooming out, I think it would be fine for this crate to depend on `rustix`/`linux-raw-sys` on either all Linux targets or just the `linux-none` targets, provided that adoption is sufficiently widespread. A good litmus test for this would be `libstd` itself depending on `rustix`/`linux-raw-sys` on some/all Linux targets.
Until that point, having our own syscall wrapper seems like the least bad option. It will work with our without rustix, and we can always move to `rustix`/`linux-raw-sys` when there is consensus.
> Zooming out, I think it would be fine for this crate to depend on rustix/linux-raw-sys on either all Linux targets or just the linux-none targets, provided that adoption is sufficiently widespread. A good litmus test for this would be libstd itself depending on rustix/linux-raw-sys on some/all Linux targets.
>
> Until that point, having our own syscall wrapper seems like the least bad option. It will work with our without rustix, and we can always move to rustix/linux-raw-sys when there is consensus.
I agree with this.
One question is, how will we test this? My understanding is that `libtest` and the other things we use in our tests aren't available for this target (yet?). If that is true, then we may need to get a little creative.
I propose the following:
* We use the exact same code paths in all cases for `all(target_os = "linux", any(target_env = "none", all(feature = "linux_disable_fallback", not(feature = "std")))`.
* We rely on the `cargo test --features=linux_disable_fallback` without `--features=std` to approximate this target.
The implication here is we'd need to remove all the libc usage from the `all(target_os = "linux", feature = "linux_disable_fallback", not(feature = "std"))` case.
Ideally, we'd change Cargo.toml so that libc isn't a dependency for `target_os = "linux"` at all, or at least when the `linux_disable_fallback` feature is activated. But, I think that would require us to reverse in this sense:
```tom
- linux_disable_fallback = []
+ linux_enable_dev_urandom_fallback = ["libc"]
```
(The use_file implementation uses `util_libc::{open_readonly, sys_fill_exact}`; libc_util uses, of course, many things from `libc` including `libc::open`.)
> I propose the following:
>
> * We use the exact same code paths in all cases for `all(target_os = "linux", any(target_env = "none", all(feature = "linux_disable_fallback", not(feature = "std")))`.
>
> * We rely on the `cargo test --features=linux_disable_fallback` without `--features=std` to approximate this target.
That testing strategy sounds good to me. I think that provided we don't explicitly check for `target_env = "none"` in the code and `x86_64-unknown-linux-none` builds, we can be reasonably sure the implementation is properly tested.
> The implication here is we'd need to remove all the libc usage from the `all(target_os = "linux", feature = "linux_disable_fallback", not(feature = "std"))` case.
The main other uses of `libc` on Linux are:
- The `errno` constants (needed for checking `libc::EINTR`)
- The use of `last_os_error()` inside of `sys_fill_exact`
The ideal approach might be to have the main looping functionality of `sys_fill_exact` be moved to `util.rs` or `lib.rs`.
My opinion is that we should add new `linux_raw` feature which would imply `linux_disable_fallback`. It would use the same backend as the `none` targets. It would make testing easier and would allows using raw `getrandom` syscall on the "classic" Linux targets.
Does anybody want to take a stab at the inline assembly for invoking the syscall?
> The errno constants (needed for checking libc::EINTR)
It looks like it doesn't vary by architecture; it's always 4; https://github.com/torvalds/linux/blob/2df0193e62cf887f373995fb8a91068562784adc/include/uapi/asm-generic/errno-base.h#L8. Though it would be good to find a definitive promise of that.
> The use of last_os_error() inside of sys_fill_exact
We could change the signature of `sys_fill_exact` like so:
```diff
- sys_fill: impl Fn(&mut [MaybeUninit<u8>]) -> libc::ssize_t,
+ sys_fill: impl Fn(&mut [MaybeUninit<u8>]) -> Result<usize, Error>
```
where any short read, including now `Ok(0)`, indicates that we should keep going. Then the raw syscall code can do something like:
```rust
usize::try_from(res).map_err(|_| res.unsigned_abs())
```
Regardless, I think it is manageable.
> My opinion is that we should add new linux_raw feature which would imply linux_disable_fallback. It would use the same backend as the none targets. It would make testing easier and would allows using raw getrandom syscall on the "classic" Linux targets.
Why would we want to keep the current code path for using `libc::syscall` though? I think we should use the same backend for all linux targets, since that will ensure that it gets the most testing and review.
> Does anybody want to take a stab at the inline assembly for invoking the syscall?
nvm. Giving it a go now.
OK, there is now a sketch of this, including building for `--target=x86_64-unknown-linux-none`, and also ensuring the `feature="linux_disable_fallback"` and `target_env=""` share a code path, in PR #46.
>Why would we want to keep the current code path for using libc::syscall though? I think we should use the same backend for all linux targets, since that will ensure that it gets the most testing and review.
Personally, I would be fine with unconditionally using raw syscalls for calling `getrandom`, but it may be controversial with some users. Though we already use `libc::syscall`, so it's probably less of an issue if we were using `libc::getrandom`.
Out of curiosity, I was trying to figure out if it would work to only use either `libc::getrandom` or directly invoke a syscall via `asm!`, avoiding any use of `libc::syscall`. This would make our logic simpler and consistent:
```
if has libc::getrandom:
call libc::getrandom
else:
raw syscall
```
`x86-64-unknown-linux-none` then just becomes a target where `has libc::getrandom` is always false. This approch would only require `asm!` support for targets that either lack a `libc` or have an old minimum `libc` version. Using `libc::getrandom` would also allow us to avoid needing `unpoision` calls as part of #463 (by basically saying "use a not-ancient libc if you want to use sanitizers" which is fine for me).
Looking at [the supported Android/Linux targets](https://doc.rust-lang.org/rustc/platform-support.html):
- All MUSL targets are fine
- `libc::getrandom` added in [MUSL 1.1.20 (2018)](https://git.musl-libc.org/cgit/musl/tree/WHATSNEW#n1912)
- Rust updated to MUSL 1.1.20 in https://github.com/rust-lang/rust/pull/54430 for Rust 1.31
- uClibc has `libc::getrandom` since [v1.0.2 (2015)](https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/commit/?id=09ff424905d5de0b2a21a3960d9756a90b07ba26) (before glibc)
- A minimum version isn't specified for the targets, but I'd be fine assuming we are good here.
- OHOS seems to have it in [all publicly available releases (3.0 - 4.1)](https://gitee.com/openharmony/docs/tree/OpenHarmony-4.1-Release/en/release-notes)
- Added in Android API Level 28 (Android 9 / Android P / Andorid Pie)
- Rust supports NDK 25 (soon to be 26), so has a min API Level of 19 (soon to be 21)
- So we need direct syscalls on `aarch64, arm, x86, x86_64`, all of which have stable inline asm.
- It's not clear if Android Apps are permitted to make raw system calls (my guess is yes but I can check at work).
- Added in [glibc 2.25](https://sourceware.org/legacy-ml/libc-alpha/2017-02/msg00079.html) (see https://lwn.net/Articles/711013/)
- Rust supports a min glibc of 2.17 on `aarch64, arm, powerpc, powerpc64, powerpc64le, s390x, x86, x86_64`
- Rust supports a min glibc of 2.23 on `armv5te, sparc64, thumbv7neon, mips, mipsel, mips64, mips64el`
- We would need direct syscalls on all these architectures.
Given this, it's probably not possible to remove use of `libc::syscall` for quite some time. | diff --git a/.github/workflows/nopanic.yaml b/.github/workflows/nopanic.yaml
--- a/.github/workflows/nopanic.yaml
+++ b/.github/workflows/nopanic.yaml
@@ -40,6 +40,14 @@ jobs:
- name: Check (linux_android.rs)
run: ret=$(grep panic target/release/libgetrandom_wrapper.so; echo $?); [ $ret -eq 1 ]
+ # TODO: re-enable after https://github.com/bytecodealliance/rustix/pull/1184 is released
+ # - name: Build (linux_rustix.rs)
+ # env:
+ # RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_rustix"
+ # run: cargo build --release
+ # - name: Check (linux_rustix.rs)
+ # run: ret=$(grep panic target/release/libgetrandom_wrapper.so; echo $?); [ $ret -eq 1 ]
+
- name: Build (rdrand.rs)
env:
RUSTFLAGS: -Dwarnings --cfg getrandom_backend="rdrand"
diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -53,6 +53,10 @@ jobs:
env:
RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_getrandom"
run: cargo clippy --target x86_64-unknown-linux-gnu
+ - name: Linux (linux_rustix.rs)
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_rustix"
+ run: cargo clippy --target x86_64-unknown-linux-gnu
- name: Linux (linux_android_with_fallback.rs)
run: cargo clippy --target x86_64-unknown-linux-gnu
- name: NetBSD (netbsd.rs)
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,7 +28,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `wasm32-wasip1` and `wasm32-wasip2` support [#499]
- `getrandom_backend` configuration flag for selection of opt-in backends [#504]
- `Error::new_custom` method [#507]
-- AArch64 RNDR register opt-in backend [#512]
+- `rndr` opt-in backend [#512]
+- `linux_rustix` opt-in backend [#520]
[#415]: https://github.com/rust-random/getrandom/pull/415
[#440]: https://github.com/rust-random/getrandom/pull/440
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#504]: https://github.com/rust-random/getrandom/pull/504
[#507]: https://github.com/rust-random/getrandom/pull/507
[#512]: https://github.com/rust-random/getrandom/pull/512
+[#520]: https://github.com/rust-random/getrandom/pull/520
## [0.2.15] - 2024-05-06
### Added
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -6,14 +6,14 @@
//! | ------------------ | ------------------ | --------------
//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
//! | Windows 10+ | `*‑windows‑*` | [`ProcessPrng`]
-//! | Windows 7 and 8 | `*-win7‑windows‑*` | [`RtlGenRandom`]
+//! | Windows 7, 8 | `*-win7‑windows‑*` | [`RtlGenRandom`]
//! | macOS | `*‑apple‑darwin` | [`getentropy`][3]
//! | iOS, tvOS, watchOS | `*‑apple‑ios`, `*-apple-tvos`, `*-apple-watchos` | [`CCRandomGenerateBytes`]
//! | FreeBSD | `*‑freebsd` | [`getrandom`][5]
//! | OpenBSD | `*‑openbsd` | [`getentropy`][7]
//! | NetBSD | `*‑netbsd` | [`getrandom`][16] if available, otherwise [`kern.arandom`][8]
//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9]
-//! | Solaris | `*‑solaris` | [`getrandom`][11] (with `GRND_RANDOM`)
+//! | Solaris | `*‑solaris` | [`getrandom`][11] with `GRND_RANDOM`
//! | illumos | `*‑illumos` | [`getrandom`][12]
//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
//! | Redox | `*‑redox` | `/dev/urandom`
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -41,6 +41,7 @@
//! | Backend name | Target | Target Triple | Implementation
//! | ----------------- | -------------------- | -------------------- | --------------
//! | `linux_getrandom` | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call (without `/dev/urandom` fallback). Bumps minimum supported Linux kernel version to 3.17 and Android API level to 23 (Marshmallow).
+//! | `linux_rustix` | Linux, Android | `*‑linux‑*` | Same as `linux_getrandom`, but uses [`rustix`] instead of `libc`.
//! | `rdrand` | x86, x86-64 | `x86_64-*`, `i686-*` | [`RDRAND`] instruction
//! | `rndr` | AArch64 | `aarch64-*` | [`RNDR`] register
//! | `esp_idf` | ESP-IDF | `*‑espidf` | [`esp_fill_random`]. WARNING: can return low quality entropy without proper hardware configuration!
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -243,6 +244,7 @@
//! [platform-support]: https://doc.rust-lang.org/stable/rustc/platform-support.html
//! [WASI]: https://github.com/CraneStation/wasi
//! [Emscripten]: https://www.hellorust.com/setup/emscripten/
+//! [`rustix`]: https://docs.rs/rustix
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -295,6 +297,8 @@ cfg_if! {
} else if #[cfg(getrandom_backend = "linux_getrandom")] {
mod util_libc;
#[path = "linux_android.rs"] mod imp;
+ } else if #[cfg(getrandom_backend = "linux_rustix")] {
+ #[path = "linux_rustix.rs"] mod imp;
} else if #[cfg(getrandom_backend = "rdrand")] {
mod lazy;
#[path = "rdrand.rs"] mod imp;
diff --git /dev/null b/src/linux_rustix.rs
new file mode 100644
--- /dev/null
+++ b/src/linux_rustix.rs
@@ -0,0 +1,30 @@
+//! Implementation for Linux / Android without `/dev/urandom` fallback
+use crate::{Error, MaybeUninit};
+use rustix::rand::{getrandom_uninit, GetRandomFlags};
+
+#[cfg(not(any(target_os = "android", target_os = "linux")))]
+compile_error!("`linux_rustix` backend can be enabled only for Linux/Android targets!");
+
+pub fn getrandom_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
+ loop {
+ let res = getrandom_uninit(dest, GetRandomFlags::empty()).map(|(res, _)| res.len());
+ match res {
+ Ok(0) => return Err(Error::UNEXPECTED),
+ Ok(res_len) => {
+ dest = dest.get_mut(res_len..).ok_or(Error::UNEXPECTED)?;
+ if dest.is_empty() {
+ return Ok(());
+ }
+ }
+ Err(rustix::io::Errno::INTR) => continue,
+ Err(err) => {
+ let code = err
+ .raw_os_error()
+ .wrapping_neg()
+ .try_into()
+ .map_err(|_| Error::UNEXPECTED)?;
+ return Err(Error::from_os_error(code));
+ }
+ }
+ }
+}
| 0.2 | 2024-10-16T03:48:29Z | ce35c6704bffbbacec2e5034a945d9c372cf46bf | 520 | Support `x86_64-unknown-linux-none`
The target was added in https://github.com/rust-lang/rust/pull/125023 and is available in the latest Nightly builds. Use `cargo +nightly build --target=x86_64-unknown-linux-none -Zbuild-std`.
The `libc` crate does NOT support this target, so `libc::syscall` and `libc::getrandom` cannot be used on this target.
I am planning to support this target in *ring* soon.
| rust-random/getrandom | rust-random__getrandom-520 | 2024-10-16T05:26:26Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"226"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -44,7 +44,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
- toolchain: [nightly, beta, stable, 1.34]
+ toolchain: [nightly, beta, stable, 1.36]
# Only Test macOS on stable to reduce macOS CI jobs
include:
- os: macos-latest
diff --git a/benches/mod.rs b/benches/mod.rs
--- a/benches/mod.rs
+++ b/benches/mod.rs
@@ -1,94 +1,64 @@
#![feature(test)]
-extern crate test;
-
-use std::{
- alloc::{alloc_zeroed, dealloc, Layout},
- ptr::NonNull,
-};
-
-// AlignedBuffer is like a Box<[u8; N]> except that it is always N-byte aligned
-struct AlignedBuffer<const N: usize>(NonNull<[u8; N]>);
+#![feature(maybe_uninit_as_bytes)]
-impl<const N: usize> AlignedBuffer<N> {
- fn layout() -> Layout {
- Layout::from_size_align(N, N).unwrap()
- }
-
- fn new() -> Self {
- let p = unsafe { alloc_zeroed(Self::layout()) } as *mut [u8; N];
- Self(NonNull::new(p).unwrap())
- }
-
- fn buf(&mut self) -> &mut [u8; N] {
- unsafe { self.0.as_mut() }
- }
-}
+extern crate test;
-impl<const N: usize> Drop for AlignedBuffer<N> {
- fn drop(&mut self) {
- unsafe { dealloc(self.0.as_ptr() as *mut u8, Self::layout()) }
- }
-}
+use std::mem::MaybeUninit;
// Used to benchmark the throughput of getrandom in an optimal scenario.
// The buffer is hot, and does not require initialization.
#[inline(always)]
-fn bench<const N: usize>(b: &mut test::Bencher) {
- let mut ab = AlignedBuffer::<N>::new();
- let buf = ab.buf();
+fn bench_getrandom<const N: usize>(b: &mut test::Bencher) {
+ b.bytes = N as u64;
b.iter(|| {
+ let mut buf = [0u8; N];
getrandom::getrandom(&mut buf[..]).unwrap();
- test::black_box(&buf);
+ test::black_box(buf);
});
- b.bytes = N as u64;
}
// Used to benchmark the throughput of getrandom is a slightly less optimal
// scenario. The buffer is still hot, but requires initialization.
#[inline(always)]
-fn bench_with_init<const N: usize>(b: &mut test::Bencher) {
- let mut ab = AlignedBuffer::<N>::new();
- let buf = ab.buf();
+fn bench_getrandom_uninit<const N: usize>(b: &mut test::Bencher) {
+ b.bytes = N as u64;
b.iter(|| {
- for byte in buf.iter_mut() {
- *byte = 0;
- }
- getrandom::getrandom(&mut buf[..]).unwrap();
- test::black_box(&buf);
+ let mut buf: MaybeUninit<[u8; N]> = MaybeUninit::uninit();
+ let _ = getrandom::getrandom_uninit(buf.as_bytes_mut()).unwrap();
+ let buf: [u8; N] = unsafe { buf.assume_init() };
+ test::black_box(buf)
});
- b.bytes = N as u64;
}
-// 32 bytes (256-bit) is the seed sized used for rand::thread_rng
-const SEED: usize = 32;
-// Common size of a page, 4 KiB
-const PAGE: usize = 4096;
-// Large buffer to get asymptotic performance, 2 MiB
-const LARGE: usize = 1 << 21;
+macro_rules! bench {
+ ( $name:ident, $size:expr ) => {
+ pub mod $name {
+ #[bench]
+ pub fn bench_getrandom(b: &mut test::Bencher) {
+ super::bench_getrandom::<{ $size }>(b);
+ }
-#[bench]
-fn bench_seed(b: &mut test::Bencher) {
- bench::<SEED>(b);
-}
-#[bench]
-fn bench_seed_init(b: &mut test::Bencher) {
- bench_with_init::<SEED>(b);
+ #[bench]
+ pub fn bench_getrandom_uninit(b: &mut test::Bencher) {
+ super::bench_getrandom_uninit::<{ $size }>(b);
+ }
+ }
+ };
}
-#[bench]
-fn bench_page(b: &mut test::Bencher) {
- bench::<PAGE>(b);
-}
-#[bench]
-fn bench_page_init(b: &mut test::Bencher) {
- bench_with_init::<PAGE>(b);
-}
+// 16 bytes (128 bits) is the size of an 128-bit AES key/nonce.
+bench!(aes128, 128 / 8);
-#[bench]
-fn bench_large(b: &mut test::Bencher) {
- bench::<LARGE>(b);
-}
-#[bench]
-fn bench_large_init(b: &mut test::Bencher) {
- bench_with_init::<LARGE>(b);
-}
+// 32 bytes (256 bits) is the seed sized used for rand::thread_rng
+// and the `random` value in a ClientHello/ServerHello for TLS.
+// This is also the size of a 256-bit AES/HMAC/P-256/Curve25519 key
+// and/or nonce.
+bench!(p256, 256 / 8);
+
+// A P-384/HMAC-384 key and/or nonce.
+bench!(p384, 384 / 8);
+
+// Initializing larger buffers is not the primary use case of this library, as
+// this should normally be done by a userspace CSPRNG. However, we have a test
+// here to see the effects of a lower (amortized) syscall overhead.
+bench!(page, 4096);
diff --git a/src/espidf.rs b/src/espidf.rs
--- a/src/espidf.rs
+++ b/src/espidf.rs
@@ -8,13 +8,13 @@
//! Implementation for ESP-IDF
use crate::Error;
-use core::ffi::c_void;
+use core::{ffi::c_void, mem::MaybeUninit};
extern "C" {
fn esp_fill_random(buf: *mut c_void, len: usize) -> u32;
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Not that NOT enabling WiFi, BT, or the voltage noise entropy source (via `bootloader_random_enable`)
// will cause ESP-IDF to return pseudo-random numbers based on the voltage noise entropy, after the initial boot process:
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -283,9 +290,40 @@ cfg_if! {
/// In general, `getrandom` will be fast enough for interactive usage, though
/// significantly slower than a user-space CSPRNG; for the latter consider
/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
+#[inline]
pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
- if dest.is_empty() {
- return Ok(());
- }
- imp::getrandom_inner(dest)
+ // SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape, and
+ // `getrandom_uninit` guarantees it will never de-initialize any part of
+ // `dest`.
+ getrandom_uninit(unsafe { slice_as_uninit_mut(dest) })?;
+ Ok(())
+}
+
+/// Version of the `getrandom` function which fills `dest` with random bytes
+/// returns a mutable reference to those bytes.
+///
+/// On successful completion this function is guaranteed to return a slice
+/// which points to the same memory as `dest` and has the same length.
+/// In other words, it's safe to assume that `dest` is initialized after
+/// this function has returned `Ok`.
+///
+/// No part of `dest` will ever be de-initialized at any point, regardless
+/// of what is returned.
+///
+/// # Examples
+///
+/// ```ignore
+/// # // We ignore this test since `uninit_array` is unstable.
+/// #![feature(maybe_uninit_uninit_array)]
+/// # fn main() -> Result<(), getrandom::Error> {
+/// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>();
+/// let buf: &mut [u8] = getrandom::getrandom_uninit(&mut buf)?;
+/// # Ok(()) }
+/// ```
+#[inline]
+pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> {
+ imp::getrandom_inner(dest)?;
+ // SAFETY: `dest` has been fully initialized by `imp::getrandom_inner`
+ // since it returned `Ok`.
+ Ok(unsafe { slice_assume_init_mut(dest) })
}
diff --git a/tests/rdrand.rs b/tests/rdrand.rs
--- a/tests/rdrand.rs
+++ b/tests/rdrand.rs
@@ -11,5 +11,10 @@ mod rdrand;
#[path = "../src/util.rs"]
mod util;
-use rdrand::getrandom_inner as getrandom_impl;
+// The rdrand implementation has the signature of getrandom_uninit(), but our
+// tests expect getrandom_impl() to have the signature of getrandom().
+fn getrandom_impl(dest: &mut [u8]) -> Result<(), Error> {
+ rdrand::getrandom_inner(unsafe { util::slice_as_uninit_mut(dest) })?;
+ Ok(())
+}
mod common;
| I've seen this type of request a couple of times before, with the rand project, but have never been convinced that this optimisation would be worth the effort. This is even more true of `getrandom` where a slow system call is required to get the random bytes.
If a crate is depending on `getrandom()` and it wants to expose an interface where it fills a `MaybeUninit<u8>` slice then it would be good to be able to fill the part of that slice that needs the random bytes using `getrandom` directly, instead of needing to fill a temporary `&[u8]` and then copying that temporary `&[u8]` to the `&[MaybeUninit<u8>]`.
In particular, for security reasons, one may wish to ensure (to the extent Rust allows) that the generated random bytes are never copied anywhere except the target buffer.
> It is inefficient to zero-fill a large byte buffer before actually being initialized with random bytes.
@bdbai do you have any benchmarks on this? Do we know if there's a performance difference between:
- Zeroing a buffer then calling `getrandom`
- Calling `getrandom` on uninitialized bytes
It would be fine to do a comparison in C if getting benchmarks in Rust might be overly complex.
> instead of needing to fill a temporary `&[u8]` and then copying that temporary `&[u8]` to the `&[MaybeUninit<u8>]`.
> In particular, for security reasons, one may wish to ensure (to the extent Rust allows) that the generated random bytes are never copied anywhere except the target buffer.
@briansmith I'm more sensitive to the security concern here (we definitely want it to be possible to initialize random buffers in-place). However, why wouldn't it be possible to just zero the `&mut [MaybeUninit<u8>]`, get a `&mut [u8]` to the same buffer, and then pass the buffer to `getrandom`? That should avoid copying secret data or needing a temporary buffer.
In general, I wouldn't be totally opposed to adding such an API, but we would probably want to wait for https://github.com/rust-lang/rfcs/pull/2930 to be implemented (tracked in https://github.com/rust-lang/rust/issues/78485), before adding an API.
I don't want to invent our own API for dealing with uninitialized buffers. If we add this, we would want to use the `ReadBuf` type and something like:
```rust
pub fn getrandom_readbuf(dest: &mut ReadBuf<'_>) -> Result<(), Error> {
// Our implementation dealing with [MaybeUninit<u8>]
}
```
Initially, this would need to be behind an unstable feature gate (like `"read_buf"`) until the RFC is stabilized.
One advantage of this sort of API is that it might allow for partial reads from the underlying RNG to not be wasted. However, this is a very slight benefit as if the RNG succeeds once, it virtually always succeeds for all future calls.
Hopefully we could see readbuf hit nightly soon.
> I don't want to invent our own API for dealing with uninitialized buffers. If we add this, we would want to use the `ReadBuf` type and something like:
`ReadBuf` is planned to be in `std::io` so it can't be used by getrandom in general, right? Perhaps we should provide feedback that it should be moved to libcore and avoid using `std::io::Error`.
However, I think `ReadBuf` is more than what is needed, because it tries to keep track of the intermediate state of a partially-filled/initialized buffer, which isn't applicable here.
> @briansmith I'm more sensitive to the security concern here (we definitely want it to be possible to initialize random buffers in-place). However, why wouldn't it be possible to just zero the `&mut [MaybeUninit<u8>]`, get a `&mut [u8]` to the same buffer, and then pass the buffer to `getrandom`? That should avoid copying secret data or needing a temporary buffer.
Of course that does work. OTOH, if that's going to be a common pattern then why not encapsulate it within `getrandom` by adding such an API? And then we could (later) optimize the implementation to avoid the initial zeroing.
> `ReadBuf` is planned to be in `std::io` so it can't be used by getrandom in general, right? Perhaps we should provide feedback that it should be moved to libcore and avoid using `std::io::Error`.
`getrandom` has a `"std"` feature, so we could just gate `getrandom_readbuf` behind that feature. Looking at [the API for `ReadBuf`](https://github.com/rust-lang/rfcs/blob/master/text/2930-read-buf.md#reference-level-explanation), it seems that nothing in its API requires it to be in `libstd`, so it could be in `libcore`. I would encourage people to raise this point in [the `ReadBuf` tracking issue](https://github.com/rust-lang/rust/issues/78485).
> OTOH, if that's going to be a common pattern then why not encapsulate it within `getrandom` by adding such an API?
It's mostly due a desire to keep the functionality of this crate minimal to reduce our maintenance burden, so I would actually want to know that this is a common pattern across many crates before we commit to supporting it in the long-term. However, if adding this API increases ergonomics for folks, I would support adding it. This would be true even if the *only* benefit is ergonomics (e.g. if there is no significant performance difference).
> However, I think `ReadBuf` is more than what is needed, because it tries to keep track of the intermediate state of a partially-filled/initialized buffer, which isn't applicable here.
If the main reason for adding this change is ergonomics (i.e. handling common patterns), I would want `getrandom` to integrate well with those common patterns. It looks like `ReadBuf` is going to be "standard way" to express this pattern in Rust, so we would probably want to use that rather than inventing our own API.
The latest revision of the PR #279 implements this.
Regarding the `ReadBuf` idea, I think that should be a separate proposal with its own issue. It looks like `ReadBuf` is dead, based on https://github.com/rust-lang/rust/pull/97015, and it looks like it might be a while before all that stuff is resolved. And, it isn't clear the resolution will be no_std-compatible. A lot of things need/want a no_std-compatible interface and a `std::io::*`-based one is a non-starter.
@bdbai This issue shouldn't be closed yet, since PR #279 hasn't been approved/merged yet, and might not be. | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## Unreleased
+### Added
+- `getrandom_uninit` [#291]
+
+### Breaking Changes
+- Update MSRV to 1.36 [#291]
+
+[#291]: https://github.com/rust-random/getrandom/pull/291
+
## [0.2.8] - 2022-10-20
### Changed
- The [Web Cryptography API] will now be preferred on `wasm32-unknown-unknown`
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ crate features, WASM support and Custom RNGs see the
## Minimum Supported Rust Version
-This crate requires Rust 1.34.0 or later.
+This crate requires Rust 1.36.0 or later.
# License
diff --git a/src/3ds.rs b/src/3ds.rs
--- a/src/3ds.rs
+++ b/src/3ds.rs
@@ -9,8 +9,9 @@
//! Implementation for Nintendo 3DS
use crate::util_libc::sys_fill_exact;
use crate::Error;
+use core::mem::MaybeUninit;
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
sys_fill_exact(dest, |buf| unsafe {
libc::getrandom(buf.as_mut_ptr() as *mut libc::c_void, buf.len(), 0)
})
diff --git a/src/bsd_arandom.rs b/src/bsd_arandom.rs
--- a/src/bsd_arandom.rs
+++ b/src/bsd_arandom.rs
@@ -8,9 +8,9 @@
//! Implementation for FreeBSD and NetBSD
use crate::{util_libc::sys_fill_exact, Error};
-use core::ptr;
+use core::{mem::MaybeUninit, ptr};
-fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
+fn kern_arnd(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t {
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
let mut len = buf.len();
let ret = unsafe {
diff --git a/src/bsd_arandom.rs b/src/bsd_arandom.rs
--- a/src/bsd_arandom.rs
+++ b/src/bsd_arandom.rs
@@ -30,7 +30,7 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
}
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0
#[cfg(target_os = "freebsd")]
{
diff --git a/src/bsd_arandom.rs b/src/bsd_arandom.rs
--- a/src/bsd_arandom.rs
+++ b/src/bsd_arandom.rs
@@ -41,7 +41,9 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
if let Some(fptr) = GETRANDOM.ptr() {
let func: GetRandomFn = unsafe { core::mem::transmute(fptr) };
- return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) });
+ return sys_fill_exact(dest, |buf| unsafe {
+ func(buf.as_mut_ptr() as *mut u8, buf.len(), 0)
+ });
}
}
// Both FreeBSD and NetBSD will only return up to 256 bytes at a time, and
diff --git a/src/custom.rs b/src/custom.rs
--- a/src/custom.rs
+++ b/src/custom.rs
@@ -7,8 +7,8 @@
// except according to those terms.
//! An implementation which calls out to an externally defined function.
-use crate::Error;
-use core::num::NonZeroU32;
+use crate::{util::uninit_slice_fill_zero, Error};
+use core::{mem::MaybeUninit, num::NonZeroU32};
/// Register a function to be invoked by `getrandom` on unsupported targets.
///
diff --git a/src/custom.rs b/src/custom.rs
--- a/src/custom.rs
+++ b/src/custom.rs
@@ -90,10 +90,16 @@ macro_rules! register_custom_getrandom {
}
#[allow(dead_code)]
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
extern "C" {
fn __getrandom_custom(dest: *mut u8, len: usize) -> u32;
}
+ // Previously we always passed a valid, initialized slice to
+ // `__getrandom_custom`. Ensure `dest` has been initialized for backward
+ // compatibility with implementations that rely on that (e.g. Rust
+ // implementations that construct a `&mut [u8]` slice from `dest` and
+ // `len`).
+ let dest = uninit_slice_fill_zero(dest);
let ret = unsafe { __getrandom_custom(dest.as_mut_ptr(), dest.len()) };
match NonZeroU32::new(ret) {
None => Ok(()),
diff --git a/src/dragonfly.rs b/src/dragonfly.rs
--- a/src/dragonfly.rs
+++ b/src/dragonfly.rs
@@ -12,8 +12,9 @@ use crate::{
util_libc::{sys_fill_exact, Weak},
Error,
};
+use std::mem::MaybeUninit;
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
diff --git a/src/fuchsia.rs b/src/fuchsia.rs
--- a/src/fuchsia.rs
+++ b/src/fuchsia.rs
@@ -8,13 +8,14 @@
//! Implementation for Fuchsia Zircon
use crate::Error;
+use core::mem::MaybeUninit;
#[link(name = "zircon")]
extern "C" {
fn zx_cprng_draw(buffer: *mut u8, length: usize);
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
- unsafe { zx_cprng_draw(dest.as_mut_ptr(), dest.len()) }
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
+ unsafe { zx_cprng_draw(dest.as_mut_ptr() as *mut u8, dest.len()) }
Ok(())
}
diff --git a/src/ios.rs b/src/ios.rs
--- a/src/ios.rs
+++ b/src/ios.rs
@@ -8,16 +8,16 @@
//! Implementation for iOS
use crate::Error;
-use core::{ffi::c_void, ptr::null};
+use core::{ffi::c_void, mem::MaybeUninit, ptr::null};
#[link(name = "Security", kind = "framework")]
extern "C" {
fn SecRandomCopyBytes(rnd: *const c_void, count: usize, bytes: *mut u8) -> i32;
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Apple's documentation guarantees kSecRandomDefault is a synonym for NULL.
- let ret = unsafe { SecRandomCopyBytes(null(), dest.len(), dest.as_mut_ptr()) };
+ let ret = unsafe { SecRandomCopyBytes(null(), dest.len(), dest.as_mut_ptr() as *mut u8) };
// errSecSuccess (from SecBase.h) is always zero.
if ret != 0 {
Err(Error::IOS_SEC_RANDOM)
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -5,10 +5,10 @@
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use crate::Error;
+use crate::{util::uninit_slice_fill_zero, Error};
extern crate std;
-use std::thread_local;
+use std::{mem::MaybeUninit, thread_local};
use js_sys::{global, Function, Uint8Array};
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -28,12 +28,16 @@ thread_local!(
static RNG_SOURCE: Result<RngSource, Error> = getrandom_init();
);
-pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub(crate) fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
RNG_SOURCE.with(|result| {
let source = result.as_ref().map_err(|&e| e)?;
match source {
RngSource::Node(n) => {
+ // XXX(perf): `random_fill_sync` requires a `&mut [u8]` so we
+ // have to ensure the memory in `dest` is initialized.
+ let dest = uninit_slice_fill_zero(dest);
+
if n.random_fill_sync(dest).is_err() {
return Err(Error::NODE_RANDOM_FILL_SYNC);
}
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -49,7 +53,9 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
if crypto.get_random_values(&sub_buf).is_err() {
return Err(Error::WEB_GET_RANDOM_VALUES);
}
- sub_buf.copy_to(chunk);
+
+ // SAFETY: `sub_buf`'s length is the same length as `chunk`
+ unsafe { sub_buf.raw_copy_to_ptr(chunk.as_mut_ptr() as *mut u8) };
}
}
};
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -186,6 +186,9 @@
#[macro_use]
extern crate cfg_if;
+use crate::util::{slice_as_uninit_mut, slice_assume_init_mut};
+use core::mem::MaybeUninit;
+
mod error;
mod util;
// To prevent a breaking change when targets are added, we always export the
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -199,7 +202,11 @@ pub use crate::error::Error;
// System-specific implementations.
//
-// These should all provide getrandom_inner with the same signature as getrandom.
+// These should all provide getrandom_inner with the signature
+// `fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`.
+// The function MUST fully initialize `dest` when `Ok(())` is returned.
+// The function MUST NOT ever write uninitialized bytes into `dest`,
+// regardless of what value it returns.
cfg_if! {
if #[cfg(any(target_os = "emscripten", target_os = "haiku",
target_os = "redox"))] {
diff --git a/src/linux_android.rs b/src/linux_android.rs
--- a/src/linux_android.rs
+++ b/src/linux_android.rs
@@ -12,8 +12,9 @@ use crate::{
util_libc::{last_os_error, sys_fill_exact},
{use_file, Error},
};
+use core::mem::MaybeUninit;
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getrandom(2) was introduced in Linux 3.17
static HAS_GETRANDOM: LazyBool = LazyBool::new();
if HAS_GETRANDOM.unsync_init(is_getrandom_available) {
diff --git a/src/macos.rs b/src/macos.rs
--- a/src/macos.rs
+++ b/src/macos.rs
@@ -12,17 +12,17 @@ use crate::{
util_libc::{last_os_error, Weak},
Error,
};
-use core::mem;
+use core::mem::{self, MaybeUninit};
type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int;
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getentropy(2) was added in 10.12, Rust supports 10.7+
static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") };
if let Some(fptr) = GETENTROPY.ptr() {
let func: GetEntropyFn = unsafe { mem::transmute(fptr) };
for chunk in dest.chunks_mut(256) {
- let ret = unsafe { func(chunk.as_mut_ptr(), chunk.len()) };
+ let ret = unsafe { func(chunk.as_mut_ptr() as *mut u8, chunk.len()) };
if ret != 0 {
return Err(last_os_error());
}
diff --git a/src/openbsd.rs b/src/openbsd.rs
--- a/src/openbsd.rs
+++ b/src/openbsd.rs
@@ -9,7 +9,7 @@
//! Implementation for OpenBSD
use crate::{util_libc::last_os_error, Error};
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally.
for chunk in dest.chunks_mut(256) {
let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) };
diff --git a/src/rdrand.rs b/src/rdrand.rs
--- a/src/rdrand.rs
+++ b/src/rdrand.rs
@@ -7,8 +7,8 @@
// except according to those terms.
//! Implementation for SGX using RDRAND instruction
-use crate::Error;
-use core::mem;
+use crate::{util::slice_as_uninit, Error};
+use core::mem::{self, MaybeUninit};
cfg_if! {
if #[cfg(target_arch = "x86_64")] {
diff --git a/src/rdrand.rs b/src/rdrand.rs
--- a/src/rdrand.rs
+++ b/src/rdrand.rs
@@ -69,7 +69,7 @@ fn is_rdrand_supported() -> bool {
HAS_RDRAND.unsync_init(|| unsafe { (arch::__cpuid(1).ecx & FLAG) != 0 })
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
if !is_rdrand_supported() {
return Err(Error::NO_RDRAND);
}
diff --git a/src/rdrand.rs b/src/rdrand.rs
--- a/src/rdrand.rs
+++ b/src/rdrand.rs
@@ -80,18 +80,18 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
}
#[target_feature(enable = "rdrand")]
-unsafe fn rdrand_exact(dest: &mut [u8]) -> Result<(), Error> {
+unsafe fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// We use chunks_exact_mut instead of chunks_mut as it allows almost all
// calls to memcpy to be elided by the compiler.
let mut chunks = dest.chunks_exact_mut(WORD_SIZE);
for chunk in chunks.by_ref() {
- chunk.copy_from_slice(&rdrand()?);
+ chunk.copy_from_slice(slice_as_uninit(&rdrand()?));
}
let tail = chunks.into_remainder();
let n = tail.len();
if n > 0 {
- tail.copy_from_slice(&rdrand()?[..n]);
+ tail.copy_from_slice(slice_as_uninit(&rdrand()?[..n]));
}
Ok(())
}
diff --git a/src/solaris_illumos.rs b/src/solaris_illumos.rs
--- a/src/solaris_illumos.rs
+++ b/src/solaris_illumos.rs
@@ -29,7 +29,7 @@ type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) ->
#[cfg(target_os = "solaris")]
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int;
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getrandom(2) was introduced in Solaris 11.3 for Illumos in 2015.
static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
if let Some(fptr) = GETRANDOM.ptr() {
diff --git a/src/solid.rs b/src/solid.rs
--- a/src/solid.rs
+++ b/src/solid.rs
@@ -8,14 +8,14 @@
//! Implementation for SOLID
use crate::Error;
-use core::num::NonZeroU32;
+use core::{mem::MaybeUninit, num::NonZeroU32};
extern "C" {
pub fn SOLID_RNG_SampleRandomBytes(buffer: *mut u8, length: usize) -> i32;
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
- let ret = unsafe { SOLID_RNG_SampleRandomBytes(dest.as_mut_ptr(), dest.len()) };
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
+ let ret = unsafe { SOLID_RNG_SampleRandomBytes(dest.as_mut_ptr() as *mut u8, dest.len()) };
if ret >= 0 {
Ok(())
} else {
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -14,6 +14,7 @@ use crate::{
};
use core::{
cell::UnsafeCell,
+ mem::MaybeUninit,
sync::atomic::{AtomicUsize, Ordering::Relaxed},
};
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -29,9 +30,11 @@ const FILE_PATH: &str = "/dev/random\0";
#[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))]
const FILE_PATH: &str = "/dev/urandom\0";
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
let fd = get_rng_fd()?;
- let read = |buf: &mut [u8]| unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) };
+ let read = |buf: &mut [MaybeUninit<u8>]| unsafe {
+ libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len())
+ };
if cfg!(target_os = "emscripten") {
// `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes.
diff --git a/src/util.rs b/src/util.rs
--- a/src/util.rs
+++ b/src/util.rs
@@ -6,7 +6,11 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
-use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
+use core::{
+ mem::MaybeUninit,
+ ptr,
+ sync::atomic::{AtomicUsize, Ordering::Relaxed},
+};
// This structure represents a lazily initialized static usize value. Useful
// when it is preferable to just rerun initialization instead of locking.
diff --git a/src/util.rs b/src/util.rs
--- a/src/util.rs
+++ b/src/util.rs
@@ -62,3 +66,36 @@ impl LazyBool {
self.0.unsync_init(|| init() as usize) != 0
}
}
+
+/// Polyfill for `maybe_uninit_slice` feature's
+/// `MaybeUninit::slice_assume_init_mut`. Every element of `slice` must have
+/// been initialized.
+#[inline(always)]
+pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
+ // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`.
+ &mut *(slice as *mut [MaybeUninit<T>] as *mut [T])
+}
+
+#[inline]
+pub fn uninit_slice_fill_zero(slice: &mut [MaybeUninit<u8>]) -> &mut [u8] {
+ unsafe { ptr::write_bytes(slice.as_mut_ptr(), 0, slice.len()) };
+ unsafe { slice_assume_init_mut(slice) }
+}
+
+#[inline(always)]
+pub fn slice_as_uninit<T>(slice: &[T]) -> &[MaybeUninit<T>] {
+ // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`.
+ // There is no risk of writing a `MaybeUninit<T>` into the result since
+ // the result isn't mutable.
+ unsafe { &*(slice as *const [T] as *const [MaybeUninit<T>]) }
+}
+
+/// View an mutable initialized array as potentially-uninitialized.
+///
+/// This is unsafe because it allows assigning uninitialized values into
+/// `slice`, which would be undefined behavior.
+#[inline(always)]
+pub unsafe fn slice_as_uninit_mut<T>(slice: &mut [T]) -> &mut [MaybeUninit<T>] {
+ // SAFETY: `MaybeUninit<T>` is guaranteed to be layout-compatible with `T`.
+ &mut *(slice as *mut [T] as *mut [MaybeUninit<T>])
+}
diff --git a/src/util_libc.rs b/src/util_libc.rs
--- a/src/util_libc.rs
+++ b/src/util_libc.rs
@@ -8,6 +8,7 @@
#![allow(dead_code)]
use crate::Error;
use core::{
+ mem::MaybeUninit,
num::NonZeroU32,
ptr::NonNull,
sync::atomic::{fence, AtomicPtr, Ordering},
diff --git a/src/util_libc.rs b/src/util_libc.rs
--- a/src/util_libc.rs
+++ b/src/util_libc.rs
@@ -59,8 +60,8 @@ pub fn last_os_error() -> Error {
// - should return -1 and set errno on failure
// - should return the number of bytes written on success
pub fn sys_fill_exact(
- mut buf: &mut [u8],
- sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t,
+ mut buf: &mut [MaybeUninit<u8>],
+ sys_fill: impl Fn(&mut [MaybeUninit<u8>]) -> libc::ssize_t,
) -> Result<(), Error> {
while !buf.is_empty() {
let res = sys_fill(buf);
diff --git a/src/vxworks.rs b/src/vxworks.rs
--- a/src/vxworks.rs
+++ b/src/vxworks.rs
@@ -8,9 +8,12 @@
//! Implementation for VxWorks
use crate::{util_libc::last_os_error, Error};
-use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
+use core::{
+ mem::MaybeUninit,
+ sync::atomic::{AtomicBool, Ordering::Relaxed},
+};
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
static RNG_INIT: AtomicBool = AtomicBool::new(false);
while !RNG_INIT.load(Relaxed) {
let ret = unsafe { libc::randSecure() };
diff --git a/src/vxworks.rs b/src/vxworks.rs
--- a/src/vxworks.rs
+++ b/src/vxworks.rs
@@ -25,7 +28,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
// Prevent overflow of i32
for chunk in dest.chunks_mut(i32::max_value() as usize) {
- let ret = unsafe { libc::randABytes(chunk.as_mut_ptr(), chunk.len() as i32) };
+ let ret = unsafe { libc::randABytes(chunk.as_mut_ptr() as *mut u8, chunk.len() as i32) };
if ret != 0 {
return Err(last_os_error());
}
diff --git a/src/wasi.rs b/src/wasi.rs
--- a/src/wasi.rs
+++ b/src/wasi.rs
@@ -8,10 +8,10 @@
//! Implementation for WASI
use crate::Error;
-use core::num::NonZeroU32;
+use core::{mem::MaybeUninit, num::NonZeroU32};
use wasi::wasi_snapshot_preview1::random_get;
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
match unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) } {
0 => Ok(()),
err => Err(unsafe { NonZeroU32::new_unchecked(err as u32) }.into()),
diff --git a/src/windows.rs b/src/windows.rs
--- a/src/windows.rs
+++ b/src/windows.rs
@@ -7,7 +7,7 @@
// except according to those terms.
use crate::Error;
-use core::{ffi::c_void, num::NonZeroU32, ptr};
+use core::{ffi::c_void, mem::MaybeUninit, num::NonZeroU32, ptr};
const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002;
diff --git a/src/windows.rs b/src/windows.rs
--- a/src/windows.rs
+++ b/src/windows.rs
@@ -21,14 +21,14 @@ extern "system" {
) -> u32;
}
-pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Prevent overflow of u32
for chunk in dest.chunks_mut(u32::max_value() as usize) {
// BCryptGenRandom was introduced in Windows Vista
let ret = unsafe {
BCryptGenRandom(
ptr::null_mut(),
- chunk.as_mut_ptr(),
+ chunk.as_mut_ptr() as *mut u8,
chunk.len() as u32,
BCRYPT_USE_SYSTEM_PREFERRED_RNG,
)
| 0.2 | 2022-10-13T03:28:37Z | 5c1bb00b74a2c72ba182171b93d1c4b9d30c10c4 | 291 | Expose API interface for MaybeUninit<u8> slice
It is inefficient to zero-fill a large byte buffer before actually being initialized with random bytes. Thus, it would be better if getrandom exposes a function that takes a slice of `MaybeUninit<u8>` so that the user will not have to initialize the buffer.
| rust-random/getrandom | rust-random__getrandom-291 | 2022-10-21T06:56:11Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"435"
] | diff --git /dev/null b/.github/workflows/nopanic.yaml
new file mode 100644
--- /dev/null
+++ b/.github/workflows/nopanic.yaml
@@ -0,0 +1,72 @@
+name: No panic
+
+on:
+ push:
+ branches: master
+ pull_request:
+ branches: master
+
+permissions:
+ contents: read
+
+defaults:
+ run:
+ working-directory: nopanic_check
+
+env:
+ RUSTFLAGS: "-Dwarnings"
+
+jobs:
+ linux:
+ name: Linux
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ # We need Nightly for the rust-std component for wasm32-wasip2
+ toolchain: nightly-2024-10-14
+ targets: wasm32-wasip1, wasm32-wasip2
+
+ - name: Build (linux_android_with_fallback.rs)
+ run: cargo build --release
+ - name: Check (linux_android_with_fallback.rs)
+ run: ret=$(grep panic target/release/libgetrandom_wrapper.so; echo $?); [ $ret -eq 1 ]
+
+ - name: Build (linux_android.rs)
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_getrandom"
+ run: cargo build --release
+ - name: Check (linux_android.rs)
+ run: ret=$(grep panic target/release/libgetrandom_wrapper.so; echo $?); [ $ret -eq 1 ]
+
+ - name: Build (rdrand.rs)
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="rdrand"
+ run: cargo build --release
+ - name: Check (rdrand.rs)
+ run: ret=$(grep panic target/release/libgetrandom_wrapper.so; echo $?); [ $ret -eq 1 ]
+
+ - name: Build (wasi.rs, preview 1)
+ run: cargo build --release --target wasm32-wasip1
+ - name: Check (wasi.rs, preview 1)
+ run: ret=$(grep panic target/wasm32-wasip1/release/getrandom_wrapper.wasm; echo $?); [ $ret -eq 1 ]
+
+ - name: Build (wasi.rs, preview 2)
+ run: cargo build --release --target wasm32-wasip2
+ - name: Check (wasi.rs, preview 2)
+ run: ret=$(grep panic target/wasm32-wasip2/release/getrandom_wrapper.wasm; echo $?); [ $ret -eq 1 ]
+
+ macos:
+ name: macOS
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ toolchain: stable
+
+ - name: Build (getentropy.rs)
+ run: cargo build --release
+ - name: Check (getentropy.rs)
+ run: ret=$(grep panic target/release/libgetrandom_wrapper.so; echo $?); [ $ret -eq 1 ]
diff --git /dev/null b/nopanic_check/src/lib.rs
new file mode 100644
--- /dev/null
+++ b/nopanic_check/src/lib.rs
@@ -0,0 +1,18 @@
+// WASI preview 2 requires enabled std
+#![cfg_attr(not(all(target_arch = "wasm32", target_env = "p2")), no_std)]
+
+#[cfg(not(any(test, all(target_arch = "wasm32", target_env = "p2"))))]
+#[panic_handler]
+fn panic(_info: &core::panic::PanicInfo) -> ! {
+ extern "C" {
+ fn panic_nonexistent() -> !;
+ }
+ unsafe { panic_nonexistent() }
+}
+
+#[no_mangle]
+pub extern "C" fn getrandom_wrapper(buf_ptr: *mut u8, buf_len: usize) -> u32 {
+ let buf = unsafe { core::slice::from_raw_parts_mut(buf_ptr.cast(), buf_len) };
+ let res = getrandom::getrandom_uninit(buf).map(|_| ());
+ unsafe { core::mem::transmute(res) }
+}
| A slightly easier approach could be to check whether generated `rlib` file contains any strings with `panic`. It will not catch any potential panics in uninlined functions from our dependencies (I think `no-panic` is similar in this regard) and may break if in future we will add an item with "panic" in it (e.g. an error description), but it may be a bit friendlier to cross-compilation.
> A slightly easier approach could be to check whether generated `rlib` file contains any strings with `panic`.
One thing to look out for is that our current implementation [will emit references to `panic_in_cleanup`](https://rust.godbolt.org/z/Ydcdz4aGo) due to our use of `DropGuard`. This is because the compiler can't statically determine that `libc::close` and `libc::pthread_mutex_unlock` will not panic. [Replacing them with Rust stubs](https://rust.godbolt.org/z/xPea169Kd) removes the `panic_in_cleanup` references.
In general `panic_in_cleanup` is fine, as it will never _create_ a panic, it just aborts the process.
Eventually it would be good to eliminate all uses of the panic infrastructure (and runtime library in general), but use_file and the fallback logic is the least urgent, IMO. | diff --git /dev/null b/nopanic_check/Cargo.toml
new file mode 100644
--- /dev/null
+++ b/nopanic_check/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "nopanic_check"
+description = "Helper crate for checking that getrandom implementation does not contain potential panics"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[lib]
+name = "getrandom_wrapper"
+crate-type = ["cdylib"]
+
+[dependencies]
+getrandom = { path = ".." }
+
+[profile.release]
+panic = "abort"
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -195,6 +195,15 @@
//! on every call to `getrandom`, hence after the first successful call one
//! can be reasonably confident that no errors will occur.
//!
+//! ## Panic handling
+//!
+//! We strive to eliminate all potential panics from our implementation.
+//! In other words, when compiled with enabled optimizations, generated
+//! binary code for `getrandom` functions should not contain any panic
+//! branches. Even if platform misbiheaves and returns an unexpected
+//! result, our code should correctly handle it and return an error like
+//! [`Error::UNEXPECTED`].
+//!
//! [1]: https://manned.org/getrandom.2
//! [2]: https://manned.org/urandom.4
//! [3]: https://www.unix.com/man-page/mojave/2/getentropy/
| 0.2 | 2024-10-14T15:25:51Z | 7db82805bd22c75e97261df649fb391e1bc505db | 515 | Document and Test that `getrandom()` never panics.
Spun off of the review of #434
We should have a way to verify in the CI that our implementation (at least on easy-to-test architectures) does not panic. This could be done via the [`no-panic` crate](https://crates.io/crates/no-panic) as a dev-dependancy.
| rust-random/getrandom | rust-random__getrandom-515 | 2024-10-14T17:16:27Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"455"
] | diff --git a/tests/mod.rs b/tests/mod.rs
--- a/tests/mod.rs
+++ b/tests/mod.rs
@@ -102,6 +102,8 @@ fn test_multithreading() {
#[cfg(getrandom_backend = "custom")]
mod custom {
+ use getrandom::Error;
+
struct Xoshiro128PlusPlus {
s: [u32; 4],
}
diff --git a/tests/mod.rs b/tests/mod.rs
--- a/tests/mod.rs
+++ b/tests/mod.rs
@@ -146,13 +148,13 @@ mod custom {
//
// WARNING: this custom implementation is for testing purposes ONLY!
#[no_mangle]
- unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
+ unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error> {
use std::time::{SystemTime, UNIX_EPOCH};
assert_ne!(len, 0);
if len == 142 {
- return getrandom::Error::CUSTOM_START + 142;
+ return Err(Error::new_custom(142));
}
let dest_u32 = dest.cast::<u32>();
diff --git a/tests/mod.rs b/tests/mod.rs
--- a/tests/mod.rs
+++ b/tests/mod.rs
@@ -169,7 +171,7 @@ mod custom {
core::ptr::write_unaligned(dest.add(i), val as u8);
}
}
- 0
+ Ok(())
}
// Test that enabling the custom feature indeed uses the custom implementation
| I like this idea, having something like:
```rust
impl Error {
pub const fn from_os_error(i32) -> Self;
pub const fn raw_os_error(self) -> Option<i32>
pub const fn new_custom(u16) -> Self;
const fn new_internal(u16) -> Self;
}
```
seems reasonable to me. We may want to use `i32` consistently for OS errors as that's what libstd uses (and it's the return type of `errno`).
EDIT: Should we also remove the `Error::code` method? | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Breaking Changes
- Update MSRV to 1.60 [#472]
- Remove support of the `wasm32-wasi` target (use `wasm32-wasip1` or `wasm32-wasip2` instead) [#499]
+- Remove `impl From<NonZeroU32> for Error` and `Error::code` method [#507]
### Changed
- Switch to `futex` on Linux and to `nanosleep`-based wait loop on other targets
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,10 +17,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `wasm32-wasip1` and `wasm32-wasip2` support [#499]
+- `Error::new_custom` method [#507]
[#472]: https://github.com/rust-random/getrandom/pull/472
[#490]: https://github.com/rust-random/getrandom/pull/490
[#499]: https://github.com/rust-random/getrandom/pull/499
+[#507]: https://github.com/rust-random/getrandom/pull/507
## [0.2.15] - 2024-05-06
### Added
diff --git a/src/custom.rs b/src/custom.rs
--- a/src/custom.rs
+++ b/src/custom.rs
@@ -1,14 +1,10 @@
//! An implementation which calls out to an externally defined function.
use crate::Error;
-use core::{mem::MaybeUninit, num::NonZeroU32};
+use core::mem::MaybeUninit;
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
extern "Rust" {
- fn __getrandom_custom(dest: *mut u8, len: usize) -> u32;
- }
- let ret = unsafe { __getrandom_custom(dest.as_mut_ptr().cast(), dest.len()) };
- match NonZeroU32::new(ret) {
- None => Ok(()),
- Some(code) => Err(Error::from(code)),
+ fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error>;
}
+ unsafe { __getrandom_custom(dest.as_mut_ptr().cast(), dest.len()) }
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -20,44 +20,38 @@ use core::{fmt, num::NonZeroU32};
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Error(NonZeroU32);
-const fn internal_error(n: u16) -> Error {
- // SAFETY: code > 0 as INTERNAL_START > 0 and adding n won't overflow a u32.
- let code = Error::INTERNAL_START + (n as u32);
- Error(unsafe { NonZeroU32::new_unchecked(code) })
-}
-
impl Error {
/// This target/platform is not supported by `getrandom`.
- pub const UNSUPPORTED: Error = internal_error(0);
+ pub const UNSUPPORTED: Error = Self::new_internal(0);
/// The platform-specific `errno` returned a non-positive value.
- pub const ERRNO_NOT_POSITIVE: Error = internal_error(1);
+ pub const ERRNO_NOT_POSITIVE: Error = Self::new_internal(1);
/// Encountered an unexpected situation which should not happen in practice.
- pub const UNEXPECTED: Error = internal_error(2);
+ pub const UNEXPECTED: Error = Self::new_internal(2);
/// Call to [`CCRandomGenerateBytes`](https://opensource.apple.com/source/CommonCrypto/CommonCrypto-60074/include/CommonRandom.h.auto.html) failed
/// on iOS, tvOS, or waatchOS.
// TODO: Update this constant name in the next breaking release.
- pub const IOS_SEC_RANDOM: Error = internal_error(3);
+ pub const IOS_SEC_RANDOM: Error = Self::new_internal(3);
/// Call to Windows [`RtlGenRandom`](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom) failed.
- pub const WINDOWS_RTL_GEN_RANDOM: Error = internal_error(4);
+ pub const WINDOWS_RTL_GEN_RANDOM: Error = Self::new_internal(4);
/// RDRAND instruction failed due to a hardware issue.
- pub const FAILED_RDRAND: Error = internal_error(5);
+ pub const FAILED_RDRAND: Error = Self::new_internal(5);
/// RDRAND instruction unsupported on this target.
- pub const NO_RDRAND: Error = internal_error(6);
+ pub const NO_RDRAND: Error = Self::new_internal(6);
/// The environment does not support the Web Crypto API.
- pub const WEB_CRYPTO: Error = internal_error(7);
+ pub const WEB_CRYPTO: Error = Self::new_internal(7);
/// Calling Web Crypto API `crypto.getRandomValues` failed.
- pub const WEB_GET_RANDOM_VALUES: Error = internal_error(8);
+ pub const WEB_GET_RANDOM_VALUES: Error = Self::new_internal(8);
/// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized).
- pub const VXWORKS_RAND_SECURE: Error = internal_error(11);
+ pub const VXWORKS_RAND_SECURE: Error = Self::new_internal(11);
/// Node.js does not have the `crypto` CommonJS module.
- pub const NODE_CRYPTO: Error = internal_error(12);
+ pub const NODE_CRYPTO: Error = Self::new_internal(12);
/// Calling Node.js function `crypto.randomFillSync` failed.
- pub const NODE_RANDOM_FILL_SYNC: Error = internal_error(13);
+ pub const NODE_RANDOM_FILL_SYNC: Error = Self::new_internal(13);
/// Called from an ES module on Node.js. This is unsupported, see:
/// <https://docs.rs/getrandom#nodejs-es-module-support>.
- pub const NODE_ES_MODULE: Error = internal_error(14);
+ pub const NODE_ES_MODULE: Error = Self::new_internal(14);
/// Calling Windows ProcessPrng failed.
- pub const WINDOWS_PROCESS_PRNG: Error = internal_error(15);
+ pub const WINDOWS_PROCESS_PRNG: Error = Self::new_internal(15);
/// Codes below this point represent OS Errors (i.e. positive i32 values).
/// Codes at or above this point, but below [`Error::CUSTOM_START`] are
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -108,13 +102,18 @@ impl Error {
}
}
- /// Extract the bare error code.
- ///
- /// This code can either come from the underlying OS, or be a custom error.
- /// Use [`Error::raw_os_error()`] to disambiguate.
- #[inline]
- pub const fn code(self) -> NonZeroU32 {
- self.0
+ /// Creates a new instance of an `Error` from a particular custom error code.
+ pub const fn new_custom(n: u16) -> Error {
+ // SAFETY: code > 0 as CUSTOM_START > 0 and adding n won't overflow a u32.
+ let code = Error::CUSTOM_START + (n as u32);
+ Error(unsafe { NonZeroU32::new_unchecked(code) })
+ }
+
+ /// Creates a new instance of an `Error` from a particular internal error code.
+ const fn new_internal(n: u16) -> Error {
+ // SAFETY: code > 0 as INTERNAL_START > 0 and adding n won't overflow a u32.
+ let code = Error::INTERNAL_START + (n as u32);
+ Error(unsafe { NonZeroU32::new_unchecked(code) })
}
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -153,12 +152,6 @@ impl fmt::Display for Error {
}
}
-impl From<NonZeroU32> for Error {
- fn from(code: NonZeroU32) -> Self {
- Self(code)
- }
-}
-
fn internal_desc(error: Error) -> Option<&'static str> {
match error {
Error::UNSUPPORTED => Some("getrandom: this target is not supported"),
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -105,8 +105,10 @@
//! signature:
//!
//! ```
+//! use getrandom::Error;
+//!
//! #[no_mangle]
-//! unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
+//! unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error> {
//! todo!()
//! }
//! ```
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -126,9 +128,11 @@
//! it gets pulled nevertheless by one of your dependencies, then you can
//! use the following custom backend which always returns "unsupported" error:
//! ```
+//! use getrandom::Error;
+//!
//! #[no_mangle]
-//! unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
-//! getrandom::Error::UNSUPPORTED.code().get()
+//! unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error> {
+//! Err(Error::UNSUPPORTED)
//! }
//! ```
//!
| 0.2 | 2024-10-07T15:15:57Z | f0d2c3f66fd30f50ea701501f723dbea282232b1 | 507 | Deprecate and remove `impl From<NonZeroU32> for Error`.
The `From<NonZeroU32> for Error` implementation doesn't do any checking of its inputs; for example, it doesn't verify that an "internal" error code isn't being used, nor does it verify that any internal error code is actually a valid/known one.
I propose:
* Replace all internal uses of it; See #441 for some progress here.
* Add `pub const fn Error::new_custom(value: u16) -> Error`
* Add `pub const fn Error::new_os(u32) -> Error` with range checking, as done in #441, though #441 doesn't make it `pub`.
* Mark the `impl From<NonZeroU32> for Error` as `#[deprecated]` now.
* In a future SemVer-breaking release, remove the implementation.
This way, internal errors will eventually only be able to be constructed from within the crate.
| rust-random/getrandom | rust-random__getrandom-507 | 2024-10-09T13:06:33Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"383"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -327,6 +327,17 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo build -Z build-std=${{ contains(matrix.features, 'std') && 'std' || 'core'}} --target=${{ matrix.target }} --features="${{ join(matrix.features, ',') }}"
+ build-no-atomics:
+ name: No Atomics Build
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v3
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: riscv32i-unknown-none-elf
+ - uses: Swatinem/rust-cache@v2
+ - run: cargo build --features custom --target riscv32i-unknown-none-elf
+
clippy-fmt:
name: Clippy + rustfmt
runs-on: ubuntu-22.04
diff --git a/tests/rdrand.rs b/tests/rdrand.rs
--- a/tests/rdrand.rs
+++ b/tests/rdrand.rs
@@ -6,6 +6,8 @@
use getrandom::Error;
#[macro_use]
extern crate cfg_if;
+#[path = "../src/lazy.rs"]
+mod lazy;
#[path = "../src/rdrand.rs"]
mod rdrand;
#[path = "../src/util.rs"]
| diff --git /dev/null b/src/lazy.rs
new file mode 100644
--- /dev/null
+++ b/src/lazy.rs
@@ -0,0 +1,56 @@
+use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
+
+// This structure represents a lazily initialized static usize value. Useful
+// when it is preferable to just rerun initialization instead of locking.
+// Both unsync_init and sync_init will invoke an init() function until it
+// succeeds, then return the cached value for future calls.
+//
+// Both methods support init() "failing". If the init() method returns UNINIT,
+// that value will be returned as normal, but will not be cached.
+//
+// Users should only depend on the _value_ returned by init() functions.
+// Specifically, for the following init() function:
+// fn init() -> usize {
+// a();
+// let v = b();
+// c();
+// v
+// }
+// the effects of c() or writes to shared memory will not necessarily be
+// observed and additional synchronization methods with be needed.
+pub(crate) struct LazyUsize(AtomicUsize);
+
+impl LazyUsize {
+ pub const fn new() -> Self {
+ Self(AtomicUsize::new(Self::UNINIT))
+ }
+
+ // The initialization is not completed.
+ pub const UNINIT: usize = usize::max_value();
+
+ // Runs the init() function at least once, returning the value of some run
+ // of init(). Multiple callers can run their init() functions in parallel.
+ // init() should always return the same value, if it succeeds.
+ pub fn unsync_init(&self, init: impl FnOnce() -> usize) -> usize {
+ // Relaxed ordering is fine, as we only have a single atomic variable.
+ let mut val = self.0.load(Relaxed);
+ if val == Self::UNINIT {
+ val = init();
+ self.0.store(val, Relaxed);
+ }
+ val
+ }
+}
+
+// Identical to LazyUsize except with bool instead of usize.
+pub(crate) struct LazyBool(LazyUsize);
+
+impl LazyBool {
+ pub const fn new() -> Self {
+ Self(LazyUsize::new())
+ }
+
+ pub fn unsync_init(&self, init: impl FnOnce() -> bool) -> bool {
+ self.0.unsync_init(|| init() as usize) != 0
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -224,6 +224,7 @@ cfg_if! {
} else if #[cfg(any(target_os = "android", target_os = "linux"))] {
mod util_libc;
mod use_file;
+ mod lazy;
#[path = "linux_android.rs"] mod imp;
} else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
mod util_libc;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -272,9 +273,11 @@ cfg_if! {
mod util_libc;
#[path = "emscripten.rs"] mod imp;
} else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
+ mod lazy;
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "rdrand",
any(target_arch = "x86_64", target_arch = "x86")))] {
+ mod lazy;
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "js",
any(target_arch = "wasm32", target_arch = "wasm64"),
diff --git a/src/linux_android.rs b/src/linux_android.rs
--- a/src/linux_android.rs
+++ b/src/linux_android.rs
@@ -8,7 +8,7 @@
//! Implementation for Linux / Android
use crate::{
- util::LazyBool,
+ lazy::LazyBool,
util_libc::{last_os_error, sys_fill_exact},
{use_file, Error},
};
diff --git a/src/rdrand.rs b/src/rdrand.rs
--- a/src/rdrand.rs
+++ b/src/rdrand.rs
@@ -5,10 +5,7 @@
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use crate::{
- util::{slice_as_uninit, LazyBool},
- Error,
-};
+use crate::{lazy::LazyBool, util::slice_as_uninit, Error};
use core::mem::{size_of, MaybeUninit};
cfg_if! {
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -8,7 +8,6 @@
//! Implementations that just need to read from a file
use crate::{
- util::LazyUsize,
util_libc::{open_readonly, sys_fill_exact},
Error,
};
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -35,6 +34,7 @@ const FILE_PATH: &str = "/dev/random\0";
target_os = "nto",
))]
const FILE_PATH: &str = "/dev/urandom\0";
+const FD_UNINIT: usize = usize::max_value();
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
let fd = get_rng_fd()?;
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -47,10 +47,10 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// bytes. The file will be opened exactly once. All subsequent calls will
// return the same file descriptor. This file descriptor is never closed.
fn get_rng_fd() -> Result<libc::c_int, Error> {
- static FD: AtomicUsize = AtomicUsize::new(LazyUsize::UNINIT);
+ static FD: AtomicUsize = AtomicUsize::new(FD_UNINIT);
fn get_fd() -> Option<libc::c_int> {
match FD.load(Relaxed) {
- LazyUsize::UNINIT => None,
+ FD_UNINIT => None,
val => Some(val as libc::c_int),
}
}
diff --git a/src/use_file.rs b/src/use_file.rs
--- a/src/use_file.rs
+++ b/src/use_file.rs
@@ -75,8 +75,8 @@ fn get_rng_fd() -> Result<libc::c_int, Error> {
wait_until_rng_ready()?;
let fd = unsafe { open_readonly(FILE_PATH)? };
- // The fd always fits in a usize without conflicting with UNINIT.
- debug_assert!(fd >= 0 && (fd as usize) < LazyUsize::UNINIT);
+ // The fd always fits in a usize without conflicting with FD_UNINIT.
+ debug_assert!(fd >= 0 && (fd as usize) < FD_UNINIT);
FD.store(fd as usize, Relaxed);
Ok(fd)
diff --git a/src/util.rs b/src/util.rs
--- a/src/util.rs
+++ b/src/util.rs
@@ -6,66 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
-use core::{
- mem::MaybeUninit,
- ptr,
- sync::atomic::{AtomicUsize, Ordering::Relaxed},
-};
-
-// This structure represents a lazily initialized static usize value. Useful
-// when it is preferable to just rerun initialization instead of locking.
-// Both unsync_init and sync_init will invoke an init() function until it
-// succeeds, then return the cached value for future calls.
-//
-// Both methods support init() "failing". If the init() method returns UNINIT,
-// that value will be returned as normal, but will not be cached.
-//
-// Users should only depend on the _value_ returned by init() functions.
-// Specifically, for the following init() function:
-// fn init() -> usize {
-// a();
-// let v = b();
-// c();
-// v
-// }
-// the effects of c() or writes to shared memory will not necessarily be
-// observed and additional synchronization methods with be needed.
-pub struct LazyUsize(AtomicUsize);
-
-impl LazyUsize {
- pub const fn new() -> Self {
- Self(AtomicUsize::new(Self::UNINIT))
- }
-
- // The initialization is not completed.
- pub const UNINIT: usize = usize::max_value();
-
- // Runs the init() function at least once, returning the value of some run
- // of init(). Multiple callers can run their init() functions in parallel.
- // init() should always return the same value, if it succeeds.
- pub fn unsync_init(&self, init: impl FnOnce() -> usize) -> usize {
- // Relaxed ordering is fine, as we only have a single atomic variable.
- let mut val = self.0.load(Relaxed);
- if val == Self::UNINIT {
- val = init();
- self.0.store(val, Relaxed);
- }
- val
- }
-}
-
-// Identical to LazyUsize except with bool instead of usize.
-pub struct LazyBool(LazyUsize);
-
-impl LazyBool {
- pub const fn new() -> Self {
- Self(LazyUsize::new())
- }
-
- pub fn unsync_init(&self, init: impl FnOnce() -> bool) -> bool {
- self.0.unsync_init(|| init() as usize) != 0
- }
-}
+use core::{mem::MaybeUninit, ptr};
/// Polyfill for `maybe_uninit_slice` feature's
/// `MaybeUninit::slice_assume_init_mut`. Every element of `slice` must have
| 0.2 | 2023-11-08T05:47:04Z | baf2198d2a52e16e3c8a820ce9c47f2fe39cbe2d | 385 | Add support for targets without atomic operations
This crate cannot currently be built for targets that do not support atomic operations (e.g. riscv32im) due to `LazyBool/Usize` in https://github.com/rust-random/getrandom/blob/baf2198d2a52e16e3c8a820ce9c47f2fe39cbe2d/src/util.rs#L33, even though those are not used when providing a custom implementation.
Example error when compiling for riscv32im
```
error[E0432]: unresolved import `core::sync::atomic::AtomicUsize`
--> src/util.rs:12:20
|
12 | sync::atomic::{AtomicUsize, Ordering::Relaxed},
| ^^^^^^^^^^^ no `AtomicUsize` in `sync::atomic`
```
It would be nice to have this working there as well, a quick workaround could be to conditionally compile those additional structs only when atomics are available.
| rust-random/getrandom | rust-random__getrandom-385 | 2023-11-08T05:58:25Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 | |
[
"498"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -38,9 +38,8 @@ jobs:
toolchain: ${{ matrix.toolchain }}
- uses: Swatinem/rust-cache@v2
- run: cargo test
- # Make sure enabling the std and custom features don't break anything
- - run: cargo test --features=std,custom
- - run: cargo test --features=linux_disable_fallback
+ # Make sure enabling the std feature doesn't break anything
+ - run: cargo test --features=std
- if: ${{ matrix.toolchain == 'nightly' }}
run: cargo test --benches
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -69,6 +68,12 @@ jobs:
sudo apt-get install --no-install-recommends ${{ matrix.packages }}
- uses: Swatinem/rust-cache@v2
- run: cargo test ${{ matrix.cargo_test_opts }} --target=${{ matrix.target }} --features=std
+ - env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_getrandom"
+ run: cargo test ${{ matrix.cargo_test_opts }} --target=${{ matrix.target }} --features=std
+ - env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="rdrand"
+ run: cargo test --features=std
ios-tests:
name: iOS Simulator Test
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -242,21 +247,27 @@ jobs:
wasm-pack --version
- uses: Swatinem/rust-cache@v2
- name: Test (Node)
- run: wasm-pack test --node --features=js
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js"
+ run: wasm-pack test --node
- name: Test (Firefox)
- run: wasm-pack test --headless --firefox --features=js,test-in-browser
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js" --cfg getrandom_browser_test
+ run: wasm-pack test --headless --firefox
- name: Test (Chrome)
- run: wasm-pack test --headless --chrome --features=js,test-in-browser
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js" --cfg getrandom_browser_test
+ run: wasm-pack test --headless --chrome
- name: Test (Edge)
if: runner.os == 'Windows'
- run: wasm-pack test --headless --chrome --chromedriver $Env:EDGEWEBDRIVER\msedgedriver.exe --features=js,test-in-browser
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js" --cfg getrandom_browser_test
+ run: wasm-pack test --headless --chrome --chromedriver $Env:EDGEWEBDRIVER\msedgedriver.exe
- name: Test (Safari)
if: runner.os == 'macOS'
- run: wasm-pack test --headless --safari --features=js,test-in-browser
- - name: Test (custom getrandom)
- run: wasm-pack test --node --features=custom
- - name: Test (JS overrides custom)
- run: wasm-pack test --node --features=custom,js
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js" --cfg getrandom_browser_test
+ run: wasm-pack test --headless --safari
wasm64-tests:
name: wasm64 Build/Link
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -268,10 +279,12 @@ jobs:
components: rust-src
- uses: Swatinem/rust-cache@v2
- name: Build and Link tests (build-std)
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js" --cfg getrandom_browser_test
# This target is Tier 3, so we have to build libstd ourselves.
# We currently cannot run these tests because wasm-bindgen-test-runner
# does not yet support memory64.
- run: cargo test --no-run -Z build-std=std,panic_abort --target=wasm64-unknown-unknown --features=js
+ run: cargo test --no-run -Z build-std=std,panic_abort --target=wasm64-unknown-unknown
wasi-tests:
name: WASI Tests
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -325,24 +338,18 @@ jobs:
aarch64-kmc-solid_asp3,
armv6k-nintendo-3ds,
armv7-sony-vita-newlibeabihf,
- riscv32imc-esp-espidf,
aarch64-unknown-nto-qnx710,
]
+ # Supported tier 3 targets with libstd support
include:
- target: aarch64-unknown-nto-qnx710
features: ["std"]
- # Supported tier 3 targets with libstd support
- target: x86_64-unknown-openbsd
features: ["std"]
- target: x86_64-unknown-dragonfly
features: ["std"]
- target: x86_64-unknown-haiku
features: ["std"]
- # Unsupported tier 3 targets to test the rdrand feature
- - target: x86_64-unknown-uefi
- features: ["rdrand"]
- - target: x86_64-unknown-l4re-uclibc
- features: ["rdrand"]
- target: i686-unknown-hurd-gnu
features: ["std"]
steps:
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -353,6 +360,38 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo build -Z build-std=${{ contains(matrix.features, 'std') && 'std' || 'core'}} --target=${{ matrix.target }} --features="${{ join(matrix.features, ',') }}"
+ build-rdrand:
+ name: RDRAND Build
+ runs-on: ubuntu-22.04
+ strategy:
+ matrix:
+ target: [
+ x86_64-unknown-uefi,
+ x86_64-unknown-l4re-uclibc,
+ ]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@nightly # Required to build libcore
+ with:
+ components: rust-src
+ - uses: Swatinem/rust-cache@v2
+ - env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="rdrand"
+ run: cargo build -Z build-std=core --target=${{ matrix.target }}
+
+ build-esp-idf:
+ name: ESP-IDF Build
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@nightly # Required to build libcore
+ with:
+ components: rust-src
+ - uses: Swatinem/rust-cache@v2
+ - env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="esp_idf"
+ run: cargo build -Z build-std=core --target=riscv32imc-esp-espidf
+
build-no-atomics:
name: No Atomics Build
runs-on: ubuntu-22.04
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -362,4 +401,6 @@ jobs:
with:
targets: riscv32i-unknown-none-elf
- uses: Swatinem/rust-cache@v2
- - run: cargo build --features custom --target riscv32i-unknown-none-elf
+ - env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="custom"
+ run: cargo build --target riscv32i-unknown-none-elf
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -30,35 +30,27 @@ wasi = { version = "0.13", default-features = false }
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
windows-targets = "0.52"
-[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dependencies]
-wasm-bindgen = { version = "0.2.89", default-features = false, optional = true }
-js-sys = { version = "0.3", optional = true }
-[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dev-dependencies]
+[target.'cfg(all(getrandom_backend = "wasm_js", any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dependencies]
+wasm-bindgen = { version = "0.2.89", default-features = false }
+js-sys = "0.3"
+[target.'cfg(all(getrandom_backend = "wasm_js", getrandom_browser_test, any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dev-dependencies]
wasm-bindgen-test = "0.3.39"
[features]
# Implement std-only traits for getrandom::Error
std = []
-# Disable `/dev/urandom` fallback for Linux and Android targets.
-# Bumps minimum supported Linux kernel version to 3.17 and Android API level to 23 (Marshmallow).
-linux_disable_fallback = []
-# Feature to enable fallback RDRAND-based implementation on x86/x86_64
-rdrand = []
-# Feature to enable JavaScript bindings on wasm*-unknown-unknown
-js = ["wasm-bindgen", "js-sys"]
-# Feature to enable custom RNG implementations
-custom = []
# Unstable feature to support being a libstd dependency
rustc-dep-of-std = ["compiler_builtins", "core"]
-# Unstable/test-only feature to run wasm-bindgen tests in a browser
-test-in-browser = []
-[[test]]
-name = "custom"
-required-features = ["custom"]
+[lints.rust.unexpected_cfgs]
+level = "warn"
+check-cfg = [
+ 'cfg(getrandom_backend, values("custom", "rdrand", "linux_getrandom", "wasm_js", "esp_idf"))',
+ 'cfg(getrandom_browser_test)',
+]
[package.metadata.docs.rs]
-features = ["std", "custom"]
+features = ["std"]
rustdoc-args = ["--cfg", "docsrs"]
# workaround for https://github.com/cross-rs/cross/issues/1345
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,104 +2,88 @@
//!
//! # Supported targets
//!
-//! | Target | Target Triple | Implementation
-//! | ----------------- | ------------------ | --------------
-//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
-//! | Windows 10+ | `*‑windows‑*` | [`ProcessPrng`]
-//! | Windows 7 and 8 | `*-win7‑windows‑*` | [`RtlGenRandom`]
-//! | macOS | `*‑apple‑darwin` | [`getentropy`][3]
+//! | Target | Target Triple | Implementation
+//! | ------------------ | ------------------ | --------------
+//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
+//! | Windows 10+ | `*‑windows‑*` | [`ProcessPrng`]
+//! | Windows 7 and 8 | `*-win7‑windows‑*` | [`RtlGenRandom`]
+//! | macOS | `*‑apple‑darwin` | [`getentropy`][3]
//! | iOS, tvOS, watchOS | `*‑apple‑ios`, `*-apple-tvos`, `*-apple-watchos` | [`CCRandomGenerateBytes`]
-//! | FreeBSD | `*‑freebsd` | [`getrandom`][5]
-//! | OpenBSD | `*‑openbsd` | [`getentropy`][7]
-//! | NetBSD | `*‑netbsd` | [`getrandom`][16] if available, otherwise [`kern.arandom`][8]
-//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9]
-//! | Solaris | `*‑solaris` | [`getrandom`][11] (with `GRND_RANDOM`)
-//! | illumos | `*‑illumos` | [`getrandom`][12]
-//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
-//! | Redox | `*‑redox` | `/dev/urandom`
-//! | Haiku | `*‑haiku` | `/dev/urandom` (identical to `/dev/random`)
-//! | Hermit | `*-hermit` | [`sys_read_entropy`]
-//! | Hurd | `*-hurd-*` | [`getrandom`][17]
-//! | SGX | `x86_64‑*‑sgx` | [`RDRAND`]
-//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
-//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`]
-//! | Emscripten | `*‑emscripten` | [`getentropy`][13]
-//! | WASI 0.1 | `wasm32‑wasip1` | [`random_get`]
-//! | WASI 0.2 | `wasm32‑wasip2` | [`get-random-u64`]
-//! | Web Browser and Node.js | `wasm*‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js, see [WebAssembly support]
-//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
-//! | Nintendo 3DS | `*-nintendo-3ds` | [`getrandom`][18]
-//! | PS Vita | `*-vita-*` | [`getentropy`][13]
-//! | QNX Neutrino | `*‑nto-qnx*` | [`/dev/urandom`][14] (identical to `/dev/random`)
-//! | AIX | `*-ibm-aix` | [`/dev/urandom`][15]
+//! | FreeBSD | `*‑freebsd` | [`getrandom`][5]
+//! | OpenBSD | `*‑openbsd` | [`getentropy`][7]
+//! | NetBSD | `*‑netbsd` | [`getrandom`][16] if available, otherwise [`kern.arandom`][8]
+//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9]
+//! | Solaris | `*‑solaris` | [`getrandom`][11] (with `GRND_RANDOM`)
+//! | illumos | `*‑illumos` | [`getrandom`][12]
+//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
+//! | Redox | `*‑redox` | `/dev/urandom`
+//! | Haiku | `*‑haiku` | `/dev/urandom` (identical to `/dev/random`)
+//! | Hermit | `*-hermit` | [`sys_read_entropy`]
+//! | Hurd | `*-hurd-*` | [`getrandom`][17]
+//! | SGX | `x86_64‑*‑sgx` | [`RDRAND`]
+//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
+//! | Emscripten | `*‑emscripten` | [`getentropy`][13]
+//! | WASI 0.1 | `wasm32‑wasip1` | [`random_get`]
+//! | WASI 0.2 | `wasm32‑wasip2` | [`get-random-u64`]
+//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
+//! | Nintendo 3DS | `*-nintendo-3ds` | [`getrandom`][18]
+//! | PS Vita | `*-vita-*` | [`getentropy`][13]
+//! | QNX Neutrino | `*‑nto-qnx*` | [`/dev/urandom`][14] (identical to `/dev/random`)
+//! | AIX | `*-ibm-aix` | [`/dev/urandom`][15]
//!
//! Pull Requests that add support for new targets to `getrandom` are always welcome.
//!
-//! ## Unsupported targets
+//! ## Opt-in backends
//!
-//! By default, `getrandom` will not compile on unsupported targets, but certain
-//! features allow a user to select a "fallback" implementation if no supported
-//! implementation exists.
+//! `getrandom` also provides optional backends which can be enabled using `getrandom_backend`
+//! configuration flag:
//!
-//! All of the below mechanisms only affect unsupported
-//! targets. Supported targets will _always_ use their supported implementations.
-//! This prevents a crate from overriding a secure source of randomness
-//! (either accidentally or intentionally).
+//! | Backend name | Target | Target Triple | Implementation
+//! | ----------------- | -------------------- | -------------------- | --------------
+//! | `linux_getrandom` | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call (without `/dev/urandom` fallback). Bumps minimum supported Linux kernel version to 3.17 and Android API level to 23 (Marshmallow).
+//! | `rdrand` | x86, x86-64 | `x86_64-*`, `i686-*` | [`RDRAND`] instruction
+//! | `esp_idf` | ESP-IDF | `*‑espidf` | [`esp_fill_random`]. WARNING: can return low quality entropy without proper hardware configuration!
+//! | `wasm_js` | Web Browser, Node.js | `wasm*‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js (see [WebAssembly support])
+//! | `custom` | All targets | `*` | User-provided custom implementation (see [custom backend])
//!
-//! ## `/dev/urandom` fallback on Linux and Android
+//! The configuration flag can be enabled either by specifying the `rustflags` field in
+//! [`.cargo/config.toml`] (note that it can be done on a per-target basis), or by using
+//! `RUSTFLAGS` environment variable:
//!
-//! On Linux targets the fallback is present only if either `target_env` is `musl`,
-//! or `target_arch` is one of the following: `aarch64`, `arm`, `powerpc`, `powerpc64`,
-//! `s390x`, `x86`, `x86_64`. Other supported targets [require][platform-support]
-//! kernel versions which support `getrandom` system call, so fallback is not needed.
-//!
-//! On Android targets the fallback is present only for the following `target_arch`es:
-//! `aarch64`, `arm`, `x86`, `x86_64`. Other `target_arch`es (e.g. RISC-V) require
-//! sufficiently high API levels.
+//! ```sh
+//! RUSTFLAGS='getrandom_backend="linux_getrandom"' cargo build
+//! ```
//!
-//! The fallback can be disabled by enabling the `linux_disable_fallback` crate feature.
-//! Note that doing so will bump minimum supported Linux kernel version to 3.17 and
-//! Android API level to 23 (Marshmallow).
+//! Enabling an opt-in backend will replace backend used by default. Doing it for a wrong target
+//! (e.g. using `linux_getrandom` while compiling for a Windows target) will result
+//! in a compilation error. Be extremely carefull while using opt-in backends, since incorrect
+//! configuration may result in vulnerable or in always panicking applications.
//!
-//! ### RDRAND on x86
+//! Note that using an opt-in backend in a library (e.g. for tests or benchmarks)
+//! WILL NOT have any effect on its downstream users.
//!
-//! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using
-//! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64`
-//! targets. This feature has no effect on other CPU architectures.
+//! [`.cargo/config.toml`]: https://doc.rust-lang.org/cargo/reference/config.html
//!
//! ### WebAssembly support
//!
-//! This crate fully supports the
-//! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and
-//! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/)
-//! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used
-//! by `wasm-pack`) is not automatically
-//! supported since, from the target name alone, we cannot deduce which
-//! JavaScript interface is in use (or if JavaScript is available at all).
+//! This crate fully supports the [WASI] and [Emscripten] targets. However,
+//! the `wasm32-unknown-unknown` target (i.e. the target used by `wasm-pack`)
+//! is not automatically supported since, from the target name alone, we cannot deduce
+//! which JavaScript interface should be used (or if JavaScript is available at all).
//!
-//! Instead, *if the `js` Cargo feature is enabled*, this crate will assume
+//! Instead, *if the `wasm_js` backend is enabled*, this crate will assume
//! that you are building for an environment containing JavaScript, and will
//! call the appropriate methods. Both web browser (main window and Web Workers)
//! and Node.js environments are supported, invoking the methods
-//! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain.
+//! [described above](#opt-in-backends) using the [`wasm-bindgen`] toolchain.
//!
-//! To enable the `js` Cargo feature, add the following to the `dependencies`
-//! section in your `Cargo.toml` file:
+//! To enable the `wasm_js` backend, you can add the following lines to your
+//! project's `.cargo/config.toml` file:
//! ```toml
-//! [dependencies]
-//! getrandom = { version = "0.2", features = ["js"] }
+//! [target.wasm32-unknown-unknown]
+//! rustflags = ['--cfg', 'getrandom_backend="wasm_js"']
//! ```
//!
-//! This can be done even if `getrandom` is not a direct dependency. Cargo
-//! allows crates to enable features for indirect dependencies.
-//!
-//! This feature should only be enabled for binary, test, or benchmark crates.
-//! Library crates should generally not enable this feature, leaving such a
-//! decision to *users* of their library. Also, libraries should not introduce
-//! their own `js` features *just* to enable `getrandom`'s `js` feature.
-//!
-//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
-//!
//! #### Node.js ES module support
//!
//! Node.js supports both [CommonJS modules] and [ES modules]. Due to
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -112,6 +96,42 @@
//! ```
//! This crate will then use the provided `webcrypto` implementation.
//!
+//! ### Custom backend
+//!
+//! If this crate does not support your target out of box or you have to use
+//! a non-default entropy source, then you can provide a custom implementation.
+//! You need to enable the custom backend as described in the [configuration flags]
+//! section. Next, you need to define an `extern` function with the following
+//! signature:
+//!
+//! ```
+//! #[no_mangle]
+//! unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
+//! todo!()
+//! }
+//! ```
+//!
+//! This function ideally should be defined in the root crate of your project,
+//! e.g. in your `main.rs`. This function MUST be defined only once for your
+//! project, i.e. upstream library crates SHOULD NOT define it outside of
+//! tests and benchmarks. Improper configuration of this backend may result
+//! in linking errors.
+//!
+//! The function accepts pointer to buffer which should be filled with random
+//! data and length in bytes. Note that the buffer MAY be uninitialized.
+//! On success the function should return 0 and fully fill the input buffer,
+//! every other return result will be interpreted as an error code.
+//!
+//! If you are confident that `getrandom` is not used in your project, but
+//! it gets pulled nevertheless by one of your dependencies, then you can
+//! use the following custom backend which always returns "unsupported" error:
+//! ```
+//! #[no_mangle]
+//! unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
+//! getrandom::Error::UNSUPPORTED.code().get()
+//! }
+//! ```
+//!
//! ### Platform Support
//! This crate generally supports the same operating system and platform versions
//! that the Rust standard library does. Additional targets may be supported using
diff --git a/tests/common/mod.rs /dev/null
--- a/tests/common/mod.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use super::getrandom_impl;
-
-#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
-use wasm_bindgen_test::wasm_bindgen_test as test;
-
-#[cfg(feature = "test-in-browser")]
-wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
-
-#[test]
-fn test_zero() {
- // Test that APIs are happy with zero-length requests
- getrandom_impl(&mut [0u8; 0]).unwrap();
-}
-
-// Return the number of bits in which s1 and s2 differ
-#[cfg(not(feature = "custom"))]
-fn num_diff_bits(s1: &[u8], s2: &[u8]) -> usize {
- assert_eq!(s1.len(), s2.len());
- s1.iter()
- .zip(s2.iter())
- .map(|(a, b)| (a ^ b).count_ones() as usize)
- .sum()
-}
-
-// Tests the quality of calling getrandom on two large buffers
-#[test]
-#[cfg(not(feature = "custom"))]
-fn test_diff() {
- let mut v1 = [0u8; 1000];
- getrandom_impl(&mut v1).unwrap();
-
- let mut v2 = [0u8; 1000];
- getrandom_impl(&mut v2).unwrap();
-
- // Between 3.5 and 4.5 bits per byte should differ. Probability of failure:
- // ~ 2^(-94) = 2 * CDF[BinomialDistribution[8000, 0.5], 3500]
- let d = num_diff_bits(&v1, &v2);
- assert!(d > 3500);
- assert!(d < 4500);
-}
-
-// Tests the quality of calling getrandom repeatedly on small buffers
-#[test]
-#[cfg(not(feature = "custom"))]
-fn test_small() {
- // For each buffer size, get at least 256 bytes and check that between
- // 3 and 5 bits per byte differ. Probability of failure:
- // ~ 2^(-91) = 64 * 2 * CDF[BinomialDistribution[8*256, 0.5], 3*256]
- for size in 1..=64 {
- let mut num_bytes = 0;
- let mut diff_bits = 0;
- while num_bytes < 256 {
- let mut s1 = vec![0u8; size];
- getrandom_impl(&mut s1).unwrap();
- let mut s2 = vec![0u8; size];
- getrandom_impl(&mut s2).unwrap();
-
- num_bytes += size;
- diff_bits += num_diff_bits(&s1, &s2);
- }
- assert!(diff_bits > 3 * num_bytes);
- assert!(diff_bits < 5 * num_bytes);
- }
-}
-
-#[test]
-fn test_huge() {
- let mut huge = [0u8; 100_000];
- getrandom_impl(&mut huge).unwrap();
-}
-
-// On WASM, the thread API always fails/panics
-#[cfg(not(target_arch = "wasm32"))]
-#[test]
-fn test_multithreading() {
- extern crate std;
- use std::{sync::mpsc::channel, thread, vec};
-
- let mut txs = vec![];
- for _ in 0..20 {
- let (tx, rx) = channel();
- txs.push(tx);
-
- thread::spawn(move || {
- // wait until all the tasks are ready to go.
- rx.recv().unwrap();
- let mut v = [0u8; 1000];
-
- for _ in 0..100 {
- getrandom_impl(&mut v).unwrap();
- thread::yield_now();
- }
- });
- }
-
- // start all the tasks
- for tx in txs.iter() {
- tx.send(()).unwrap();
- }
-}
diff --git a/tests/custom.rs /dev/null
--- a/tests/custom.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-use core::num::NonZeroU32;
-use getrandom::{getrandom, register_custom_getrandom, Error};
-#[cfg(all(target_family = "wasm", target_os = "unknown"))]
-use wasm_bindgen_test::wasm_bindgen_test as test;
-
-const LEN7_CODE: u32 = Error::CUSTOM_START + 7;
-// Returns a custom error if input is length 7, otherwise fills with 0x55.
-fn mock_rng(buf: &mut [u8]) -> Result<(), Error> {
- // `getrandom` guarantees it will not call any implementation if the output
- // buffer is empty.
- assert!(!buf.is_empty());
- if buf.len() == 7 {
- return Err(NonZeroU32::new(LEN7_CODE).unwrap().into());
- }
- buf.fill(0x55);
- Ok(())
-}
-
-// Test registering a custom implementation, even on supported platforms.
-register_custom_getrandom!(mock_rng);
-
-// Invoking with an empty buffer should never call the custom implementation.
-#[test]
-fn custom_empty() {
- getrandom(&mut []).unwrap();
-}
-
-// On a supported platform, make sure the custom implementation isn't used. We
-// test on a few common platfroms, rather than duplicating the lib.rs logic.
-#[cfg(any(
- target_os = "linux",
- target_os = "windows",
- target_os = "macos",
- target_os = "espidf",
- target_os = "wasi",
- all(target_family = "wasm", target_os = "unknown", feature = "js"),
-))]
-#[test]
-fn custom_not_used() {
- getrandom(&mut [0; 7]).unwrap();
-}
-// On an unsupported platform, make sure the custom implementation is used.
-#[cfg(all(target_family = "wasm", target_os = "unknown", not(feature = "js")))]
-#[test]
-fn custom_used() {
- let err = getrandom(&mut [0; 7]).unwrap_err();
- assert_eq!(err.code().get(), LEN7_CODE);
-
- let mut buf = [0; 12];
- getrandom(&mut buf).unwrap();
- assert_eq!(buf, [0x55; 12]);
-}
diff --git /dev/null b/tests/mod.rs
new file mode 100644
--- /dev/null
+++ b/tests/mod.rs
@@ -0,0 +1,182 @@
+use getrandom::getrandom;
+
+#[cfg(getrandom_browser_test)]
+use wasm_bindgen_test::wasm_bindgen_test as test;
+#[cfg(getrandom_browser_test)]
+wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
+
+#[test]
+fn test_zero() {
+ // Test that APIs are happy with zero-length requests
+ getrandom(&mut [0u8; 0]).unwrap();
+}
+
+// Return the number of bits in which s1 and s2 differ
+fn num_diff_bits(s1: &[u8], s2: &[u8]) -> usize {
+ assert_eq!(s1.len(), s2.len());
+ s1.iter()
+ .zip(s2.iter())
+ .map(|(a, b)| (a ^ b).count_ones() as usize)
+ .sum()
+}
+
+// Tests the quality of calling getrandom on two large buffers
+#[test]
+fn test_diff() {
+ let mut v1 = [0u8; 1000];
+ getrandom(&mut v1).unwrap();
+
+ let mut v2 = [0u8; 1000];
+ getrandom(&mut v2).unwrap();
+
+ // Between 3.5 and 4.5 bits per byte should differ. Probability of failure:
+ // ~ 2^(-94) = 2 * CDF[BinomialDistribution[8000, 0.5], 3500]
+ let d = num_diff_bits(&v1, &v2);
+ assert!(d > 3500);
+ assert!(d < 4500);
+}
+
+// Tests the quality of calling getrandom repeatedly on small buffers
+#[test]
+fn test_small() {
+ let mut buf1 = [0u8; 64];
+ let mut buf2 = [0u8; 64];
+ // For each buffer size, get at least 256 bytes and check that between
+ // 3 and 5 bits per byte differ. Probability of failure:
+ // ~ 2^(-91) = 64 * 2 * CDF[BinomialDistribution[8*256, 0.5], 3*256]
+ for size in 1..=64 {
+ let mut num_bytes = 0;
+ let mut diff_bits = 0;
+ while num_bytes < 256 {
+ let s1 = &mut buf1[..size];
+ let s2 = &mut buf2[..size];
+
+ getrandom(s1).unwrap();
+ getrandom(s2).unwrap();
+
+ num_bytes += size;
+ diff_bits += num_diff_bits(s1, s2);
+ }
+ assert!(diff_bits > 3 * num_bytes);
+ assert!(diff_bits < 5 * num_bytes);
+ }
+}
+
+#[test]
+fn test_huge() {
+ let mut huge = [0u8; 100_000];
+ getrandom(&mut huge).unwrap();
+}
+
+#[test]
+#[cfg_attr(
+ target_arch = "wasm32",
+ ignore = "The thread API always fails/panics on WASM"
+)]
+fn test_multithreading() {
+ extern crate std;
+ use std::{sync::mpsc::channel, thread, vec};
+
+ let mut txs = vec![];
+ for _ in 0..20 {
+ let (tx, rx) = channel();
+ txs.push(tx);
+
+ thread::spawn(move || {
+ // wait until all the tasks are ready to go.
+ rx.recv().unwrap();
+ let mut v = [0u8; 1000];
+
+ for _ in 0..100 {
+ getrandom(&mut v).unwrap();
+ thread::yield_now();
+ }
+ });
+ }
+
+ // start all the tasks
+ for tx in txs.iter() {
+ tx.send(()).unwrap();
+ }
+}
+
+#[cfg(getrandom_backend = "custom")]
+mod custom {
+ struct Xoshiro128PlusPlus {
+ s: [u32; 4],
+ }
+
+ impl Xoshiro128PlusPlus {
+ fn new(mut seed: u64) -> Self {
+ const PHI: u64 = 0x9e3779b97f4a7c15;
+ let mut s = [0u32; 4];
+ for val in s.iter_mut() {
+ seed = seed.wrapping_add(PHI);
+ let mut z = seed;
+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
+ z = z ^ (z >> 31);
+ *val = z as u32;
+ }
+ Self { s }
+ }
+
+ fn next_u32(&mut self) -> u32 {
+ let res = self.s[0]
+ .wrapping_add(self.s[3])
+ .rotate_left(7)
+ .wrapping_add(self.s[0]);
+
+ let t = self.s[1] << 9;
+
+ self.s[2] ^= self.s[0];
+ self.s[3] ^= self.s[1];
+ self.s[1] ^= self.s[2];
+ self.s[0] ^= self.s[3];
+
+ self.s[2] ^= t;
+
+ self.s[3] = self.s[3].rotate_left(11);
+
+ res
+ }
+ }
+
+ // This implementation uses current timestamp as a PRNG seed.
+ //
+ // WARNING: this custom implementation is for testing purposes ONLY!
+ #[no_mangle]
+ unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ assert_ne!(len, 0);
+
+ if len == 142 {
+ return getrandom::Error::CUSTOM_START + 142;
+ }
+
+ let dest_u32 = dest.cast::<u32>();
+ let ts = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
+ let mut rng = Xoshiro128PlusPlus::new(ts.as_nanos() as u64);
+ for i in 0..len / 4 {
+ let val = rng.next_u32();
+ core::ptr::write_unaligned(dest_u32.add(i), val);
+ }
+ if len % 4 != 0 {
+ let start = 4 * (len / 4);
+ for i in start..len {
+ let val = rng.next_u32();
+ core::ptr::write_unaligned(dest.add(i), val as u8);
+ }
+ }
+ 0
+ }
+
+ // Test that enabling the custom feature indeed uses the custom implementation
+ #[test]
+ fn test_custom() {
+ let mut buf = [0u8; 142];
+ let res = getrandom::getrandom(&mut buf);
+ assert!(res.is_err());
+ }
+}
diff --git a/tests/normal.rs /dev/null
--- a/tests/normal.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-// Don't test on custom wasm32-unknown-unknown
-#![cfg(not(all(
- target_arch = "wasm32",
- target_os = "unknown",
- feature = "custom",
- not(feature = "js")
-)))]
-
-// Use the normal getrandom implementation on this architecture.
-use getrandom::getrandom as getrandom_impl;
-mod common;
diff --git a/tests/rdrand.rs /dev/null
--- a/tests/rdrand.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-// We only test the RDRAND-based RNG source on supported architectures.
-#![cfg(any(target_arch = "x86_64", target_arch = "x86"))]
-
-// rdrand.rs expects to be part of the getrandom main crate, so we need these
-// additional imports to get rdrand.rs to compile.
-use getrandom::Error;
-#[macro_use]
-extern crate cfg_if;
-#[path = "../src/lazy.rs"]
-mod lazy;
-#[path = "../src/rdrand.rs"]
-mod rdrand;
-#[path = "../src/util.rs"]
-mod util;
-
-// The rdrand implementation has the signature of getrandom_uninit(), but our
-// tests expect getrandom_impl() to have the signature of getrandom().
-fn getrandom_impl(dest: &mut [u8]) -> Result<(), Error> {
- rdrand::getrandom_inner(unsafe { util::slice_as_uninit_mut(dest) })?;
- Ok(())
-}
-mod common;
| diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -27,11 +27,15 @@ jobs:
components: clippy,rust-src
- name: std feature
run: cargo clippy --features std
- - name: custom feature
- run: cargo clippy -Zbuild-std=core --target riscv32i-unknown-none-elf --features custom
+ - name: custom backend
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="custom"
+ run: cargo clippy -Zbuild-std=core --target riscv32i-unknown-none-elf
- name: iOS (apple-other.rs)
run: cargo clippy -Zbuild-std=core --target x86_64-apple-ios
- name: ESP-IDF (espidf.rs)
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="esp_idf"
run: cargo clippy -Zbuild-std=core --target riscv32imc-esp-espidf
- name: Fuchsia (fuchsia.rs)
run: cargo clippy -Zbuild-std=core --target x86_64-unknown-fuchsia
diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -42,9 +46,13 @@ jobs:
- name: Hermit (hermit.rs)
run: cargo clippy -Zbuild-std=core --target x86_64-unknown-hermit
- name: Web WASM (js.rs)
- run: cargo clippy -Zbuild-std --target wasm32-unknown-unknown --features js
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="wasm_js"
+ run: cargo clippy -Zbuild-std --target wasm32-unknown-unknown
- name: Linux (linux_android.rs)
- run: cargo clippy --target x86_64-unknown-linux-gnu --features linux_disable_fallback
+ env:
+ RUSTFLAGS: -Dwarnings --cfg getrandom_backend="linux_getrandom"
+ run: cargo clippy --target x86_64-unknown-linux-gnu
- name: Linux (linux_android_with_fallback.rs)
run: cargo clippy --target x86_64-unknown-linux-gnu
- name: NetBSD (netbsd.rs)
diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -93,4 +101,4 @@ jobs:
- name: Generate Docs
env:
RUSTDOCFLAGS: "-Dwarnings --cfg docsrs"
- run: cargo doc --no-deps --features custom
+ run: cargo doc --no-deps --features std
diff --git a/src/custom.rs b/src/custom.rs
--- a/src/custom.rs
+++ b/src/custom.rs
@@ -1,103 +1,12 @@
//! An implementation which calls out to an externally defined function.
-use crate::{util::uninit_slice_fill_zero, Error};
+use crate::Error;
use core::{mem::MaybeUninit, num::NonZeroU32};
-/// Register a function to be invoked by `getrandom` on unsupported targets.
-///
-/// ## Writing a custom `getrandom` implementation
-///
-/// The function to register must have the same signature as
-/// [`getrandom::getrandom`](crate::getrandom). The function can be defined
-/// wherever you want, either in root crate or a dependent crate.
-///
-/// For example, if we wanted a `failure-getrandom` crate containing an
-/// implementation that always fails, we would first depend on `getrandom`
-/// (for the [`Error`] type) in `failure-getrandom/Cargo.toml`:
-/// ```toml
-/// [dependencies]
-/// getrandom = "0.2"
-/// ```
-/// Note that the crate containing this function does **not** need to enable the
-/// `"custom"` Cargo feature.
-///
-/// Next, in `failure-getrandom/src/lib.rs`, we define our function:
-/// ```rust
-/// use core::num::NonZeroU32;
-/// use getrandom::Error;
-///
-/// // Some application-specific error code
-/// const MY_CUSTOM_ERROR_CODE: u32 = Error::CUSTOM_START + 42;
-/// pub fn always_fail(buf: &mut [u8]) -> Result<(), Error> {
-/// let code = NonZeroU32::new(MY_CUSTOM_ERROR_CODE).unwrap();
-/// Err(Error::from(code))
-/// }
-/// ```
-///
-/// ## Registering a custom `getrandom` implementation
-///
-/// Functions can only be registered in the root binary crate. Attempting to
-/// register a function in a non-root crate will result in a linker error.
-/// This is similar to
-/// [`#[panic_handler]`](https://doc.rust-lang.org/nomicon/panic-handler.html) or
-/// [`#[global_allocator]`](https://doc.rust-lang.org/edition-guide/rust-2018/platform-and-target-support/global-allocators.html),
-/// where helper crates define handlers/allocators but only the binary crate
-/// actually _uses_ the functionality.
-///
-/// To register the function, we first depend on `failure-getrandom` _and_
-/// `getrandom` in `Cargo.toml`:
-/// ```toml
-/// [dependencies]
-/// failure-getrandom = "0.1"
-/// getrandom = { version = "0.2", features = ["custom"] }
-/// ```
-///
-/// Then, we register the function in `src/main.rs`:
-/// ```rust
-/// # mod failure_getrandom { pub fn always_fail(_: &mut [u8]) -> Result<(), getrandom::Error> { unimplemented!() } }
-/// use failure_getrandom::always_fail;
-/// use getrandom::register_custom_getrandom;
-///
-/// register_custom_getrandom!(always_fail);
-/// ```
-///
-/// Now any user of `getrandom` (direct or indirect) on this target will use the
-/// registered function. As noted in the
-/// [top-level documentation](index.html#custom-implementations) this
-/// registration only has an effect on unsupported targets.
-#[macro_export]
-macro_rules! register_custom_getrandom {
- ($path:path) => {
- // TODO(MSRV 1.37): change to unnamed block
- const __GETRANDOM_INTERNAL: () = {
- // We use Rust ABI to be safe against potential panics in the passed function.
- #[no_mangle]
- unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
- // Make sure the passed function has the type of getrandom::getrandom
- type F = fn(&mut [u8]) -> ::core::result::Result<(), $crate::Error>;
- let _: F = $crate::getrandom;
- let f: F = $path;
- let slice = ::core::slice::from_raw_parts_mut(dest, len);
- match f(slice) {
- Ok(()) => 0,
- Err(e) => e.code().get(),
- }
- }
- };
- };
-}
-
-#[allow(dead_code)]
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
extern "Rust" {
fn __getrandom_custom(dest: *mut u8, len: usize) -> u32;
}
- // Previously we always passed a valid, initialized slice to
- // `__getrandom_custom`. Ensure `dest` has been initialized for backward
- // compatibility with implementations that rely on that (e.g. Rust
- // implementations that construct a `&mut [u8]` slice from `dest` and
- // `len`).
- let dest = uninit_slice_fill_zero(dest);
- let ret = unsafe { __getrandom_custom(dest.as_mut_ptr(), dest.len()) };
+ let ret = unsafe { __getrandom_custom(dest.as_mut_ptr().cast(), dest.len()) };
match NonZeroU32::new(ret) {
None => Ok(()),
Some(code) => Err(Error::from(code)),
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -122,17 +142,20 @@
//! `getrandom` may create new patch releases (`0.N.x`) that remove support for
//! outdated platform versions.
//!
-//! ### Custom implementations
+//! ## `/dev/urandom` fallback on Linux and Android
+//!
+//! On Linux targets the fallback is present only if either `target_env` is `musl`,
+//! or `target_arch` is one of the following: `aarch64`, `arm`, `powerpc`, `powerpc64`,
+//! `s390x`, `x86`, `x86_64`. Other supported targets [require][platform-support]
+//! kernel versions which support `getrandom` system call, so fallback is not needed.
//!
-//! The [`register_custom_getrandom!`] macro allows a user to mark their own
-//! function as the backing implementation for [`getrandom`]. See the macro's
-//! documentation for more information about writing and registering your own
-//! custom implementations.
+//! On Android targets the fallback is present only for the following `target_arch`es:
+//! `aarch64`, `arm`, `x86`, `x86_64`. Other `target_arch`es (e.g. RISC-V) require
+//! sufficiently high API levels.
//!
-//! Note that registering a custom implementation only has an effect on targets
-//! that would otherwise not compile. Any supported targets (including those
-//! using `rdrand` and `js` Cargo features) continue using their normal
-//! implementations even if a function is registered.
+//! The fallback can be disabled by enabling the `linux_getrandom` opt-in backend.
+//! Note that doing so will bump minimum supported Linux kernel version to 3.17 and
+//! Android API level to 23 (Marshmallow).
//!
//! ## Early boot
//!
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -195,12 +218,16 @@
//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
//! [`get-random-u64`]: https://github.com/WebAssembly/WASI/blob/v0.2.1/wasip2/random/random.wit#L23-L28
//! [WebAssembly support]: #webassembly-support
+//! [configuration flags]: #configuration-flags
+//! [custom backend]: #custom-backend
//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
//! [CommonJS modules]: https://nodejs.org/api/modules.html
//! [ES modules]: https://nodejs.org/api/esm.html
//! [`sys_read_entropy`]: https://github.com/hermit-os/kernel/blob/315f58ff5efc81d9bf0618af85a59963ff55f8b1/src/syscalls/entropy.rs#L47-L55
//! [platform-support]: https://doc.rust-lang.org/stable/rustc/platform-support.html
+//! [WASI]: https://github.com/CraneStation/wasi
+//! [Emscripten]: https://www.hellorust.com/setup/emscripten/
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -214,20 +241,17 @@
#[macro_use]
extern crate cfg_if;
-use crate::util::{slice_as_uninit_mut, slice_assume_init_mut};
use core::mem::MaybeUninit;
mod error;
mod lazy;
mod util;
-// To prevent a breaking change when targets are added, we always export the
-// register_custom_getrandom macro, so old Custom RNG crates continue to build.
-#[cfg(feature = "custom")]
-mod custom;
+
#[cfg(feature = "std")]
mod error_impls;
pub use crate::error::Error;
+use crate::util::{slice_as_uninit_mut, slice_assume_init_mut};
// System-specific implementations.
//
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -237,7 +261,34 @@ pub use crate::error::Error;
// The function MUST NOT ever write uninitialized bytes into `dest`,
// regardless of what value it returns.
cfg_if! {
- if #[cfg(any(target_os = "haiku", target_os = "redox", target_os = "nto", target_os = "aix"))] {
+ if #[cfg(getrandom_backend = "custom")] {
+ #[path = "custom.rs"] mod imp;
+ } else if #[cfg(getrandom_backend = "linux_getrandom")] {
+ #[cfg(not(any(target_os = "android", target_os = "linux")))]
+ compile_error!("`linux_getrandom` backend can be enabled only for Linux/Android targets!");
+ mod util_libc;
+ #[path = "linux_android.rs"] mod imp;
+ } else if #[cfg(getrandom_backend = "rdrand")] {
+ #[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))]
+ compile_error!("`rdrand` backend can be enabled only for x86 and x86-64 targets!");
+ #[path = "rdrand.rs"] mod imp;
+ } else if #[cfg(getrandom_backend = "wasm_js")] {
+ #[cfg(not(all(
+ any(target_arch = "wasm32", target_arch = "wasm64"),
+ target_os = "unknown",
+ )))]
+ compile_error!("`wasm_js` backend can be enabled only on OS-less WASM targets!");
+ #[path = "js.rs"] mod imp;
+ } else if #[cfg(getrandom_backend = "esp_idf")] {
+ #[cfg(not(target_os = "espidf"))]
+ compile_error!("`esp_idf` backend can be enabled only for ESP-IDF targets!");
+ #[path = "espidf.rs"] mod imp;
+ } else if #[cfg(any(
+ target_os = "haiku",
+ target_os = "redox",
+ target_os = "nto",
+ target_os = "aix",
+ ))] {
mod util_libc;
#[path = "use_file.rs"] mod imp;
} else if #[cfg(any(
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -259,45 +310,42 @@ cfg_if! {
))] {
mod util_libc;
#[path = "getrandom.rs"] mod imp;
- } else if #[cfg(all(
- not(feature = "linux_disable_fallback"),
- any(
- // Rust supports Android API level 19 (KitKat) [0] and the next upgrade targets
- // level 21 (Lollipop) [1], while `getrandom(2)` was added only in
- // level 23 (Marshmallow). Note that it applies only to the "old" `target_arch`es,
- // RISC-V Android targets sufficiently new API level, same will apply for potential
- // new Android `target_arch`es.
- // [0]: https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html
- // [1]: https://github.com/rust-lang/rust/pull/120593
- all(
- target_os = "android",
- any(
- target_arch = "aarch64",
- target_arch = "arm",
- target_arch = "x86",
- target_arch = "x86_64",
- ),
+ } else if #[cfg(any(
+ // Rust supports Android API level 19 (KitKat) [0] and the next upgrade targets
+ // level 21 (Lollipop) [1], while `getrandom(2)` was added only in
+ // level 23 (Marshmallow). Note that it applies only to the "old" `target_arch`es,
+ // RISC-V Android targets sufficiently new API level, same will apply for potential
+ // new Android `target_arch`es.
+ // [0]: https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html
+ // [1]: https://github.com/rust-lang/rust/pull/120593
+ all(
+ target_os = "android",
+ any(
+ target_arch = "aarch64",
+ target_arch = "arm",
+ target_arch = "x86",
+ target_arch = "x86_64",
),
- // Only on these `target_arch`es Rust supports Linux kernel versions (3.2+)
- // that precede the version (3.17) in which `getrandom(2)` was added:
- // https://doc.rust-lang.org/stable/rustc/platform-support.html
- all(
- target_os = "linux",
- any(
- target_arch = "aarch64",
- target_arch = "arm",
- target_arch = "powerpc",
- target_arch = "powerpc64",
- target_arch = "s390x",
- target_arch = "x86",
- target_arch = "x86_64",
- // Minimum supported Linux kernel version for MUSL targets
- // is not specified explicitly (as of Rust 1.77) and they
- // are used in practice to target pre-3.17 kernels.
- target_env = "musl",
- ),
- )
),
+ // Only on these `target_arch`es Rust supports Linux kernel versions (3.2+)
+ // that precede the version (3.17) in which `getrandom(2)` was added:
+ // https://doc.rust-lang.org/stable/rustc/platform-support.html
+ all(
+ target_os = "linux",
+ any(
+ target_arch = "aarch64",
+ target_arch = "arm",
+ target_arch = "powerpc",
+ target_arch = "powerpc64",
+ target_arch = "s390x",
+ target_arch = "x86",
+ target_arch = "x86_64",
+ // Minimum supported Linux kernel version for MUSL targets
+ // is not specified explicitly (as of Rust 1.77) and they
+ // are used in practice to target pre-3.17 kernels.
+ target_env = "musl",
+ ),
+ )
))] {
mod util_libc;
mod use_file;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -314,7 +362,12 @@ cfg_if! {
#[path = "netbsd.rs"] mod imp;
} else if #[cfg(target_os = "fuchsia")] {
#[path = "fuchsia.rs"] mod imp;
- } else if #[cfg(any(target_os = "ios", target_os = "visionos", target_os = "watchos", target_os = "tvos"))] {
+ } else if #[cfg(any(
+ target_os = "ios",
+ target_os = "visionos",
+ target_os = "watchos",
+ target_os = "tvos",
+ ))] {
#[path = "apple-other.rs"] mod imp;
} else if #[cfg(all(target_arch = "wasm32", target_os = "wasi"))] {
#[path = "wasi.rs"] mod imp;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -325,32 +378,24 @@ cfg_if! {
#[path = "vxworks.rs"] mod imp;
} else if #[cfg(target_os = "solid_asp3")] {
#[path = "solid.rs"] mod imp;
- } else if #[cfg(target_os = "espidf")] {
- #[path = "espidf.rs"] mod imp;
} else if #[cfg(all(windows, target_vendor = "win7"))] {
#[path = "windows7.rs"] mod imp;
} else if #[cfg(windows)] {
#[path = "windows.rs"] mod imp;
} else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
#[path = "rdrand.rs"] mod imp;
- } else if #[cfg(all(feature = "rdrand",
- any(target_arch = "x86_64", target_arch = "x86")))] {
- #[path = "rdrand.rs"] mod imp;
- } else if #[cfg(all(feature = "js",
- any(target_arch = "wasm32", target_arch = "wasm64"),
- target_os = "unknown"))] {
- #[path = "js.rs"] mod imp;
- } else if #[cfg(feature = "custom")] {
- use custom as imp;
- } else if #[cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"),
- target_os = "unknown"))] {
+ } else if #[cfg(all(
+ any(target_arch = "wasm32", target_arch = "wasm64"),
+ target_os = "unknown",
+ ))] {
compile_error!("the wasm*-unknown-unknown targets are not supported by \
- default, you may need to enable the \"js\" feature. \
- For more information see: \
+ default, you may need to enable the \"wasm_js\" \
+ configuration flag. For more information see: \
https://docs.rs/getrandom/#webassembly-support");
} else {
- compile_error!("target is not supported, for more information see: \
- https://docs.rs/getrandom/#unsupported-targets");
+ compile_error!("target is not supported. You may need to define \
+ a custom backend see: \
+ https://docs.rs/getrandom/#custom-backends");
}
}
| 0.2 | 2024-10-04T17:33:42Z | fd2de2f7c3f9ffe62ab4efc3553ce2daa55de09a | 504 | Allow to change default entropy source with configuration flags
Some platforms provide hardware-based "true" RNG sources which can be faster and have smaller footprint than using OS-provided APIs. For example: the RDRAND instruction (x86), the RNDR register (ARM, see #494), the `seed` CSR (RISC-V). In most cases users should prefer OS-provided APIs because they are more widely available, likely less buggy (see comments in the `rdrand` module), and there are less security concerns about them. But in some controlled cases it could be useful to be able to switch to these entropy sources.
Crate features could be used for that, but they are not a good fit since, strictly speaking, change of entropy backend is not "additive". Some users also misuse those features and enable them unconditionally in library crates. It's probably better to use configuration flags (i.e. `cfg(getrandom = "rdrand")`). In future we may replace them with something like [mutually exclusive features](https://github.com/rust-lang/cargo/issues/2980).
This configuration flag should probably replace the existing `linux_disable_fallback`, `rdrand`, and `js` features. The last one is the most debatable. It's the most used feature compared to the other two, so replacing it with a configuration flag may result in complaints from developers targeting Web WASM.
We also can gate support of "problematic" targets such as ESP-IDF (see #397) behind such flag to improve visibility of potential issues with such targets.
| rust-random/getrandom | rust-random__getrandom-504 | 2024-10-07T14:11:09Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 | |
[
"492"
] | diff --git a/.cargo/config.toml b/.cargo/config.toml
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,7 +1,9 @@
# Allow normal use of "cargo run" and "cargo test" on these wasm32 platforms.
[target.wasm32-unknown-unknown]
runner = 'wasm-bindgen-test-runner'
-[target.wasm32-wasi]
+[target.wasm32-wasip1]
+runner = 'wasmtime'
+[target.wasm32-wasip2]
runner = 'wasmtime'
# Just run on node by default (that's where emscripten is tested)
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -274,21 +274,25 @@ jobs:
run: cargo test --no-run -Z build-std=std,panic_abort --target=wasm64-unknown-unknown --features=js
wasi-tests:
- name: WASI Test
+ name: WASI Tests
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- - uses: dtolnay/rust-toolchain@stable
+ - uses: dtolnay/rust-toolchain@master
with:
- targets: wasm32-wasi
- - name: Install precompiled wasmtime
+ toolchain: nightly # TODO: Use stable after 1.82 is released as stable
+ targets: wasm32-wasip1,wasm32-wasip2
+ - name: Install Wasmtime
run: |
- VERSION=v2.0.0
+ VERSION=v24.0.0
URL=https://github.com/bytecodealliance/wasmtime/releases/download/${VERSION}/wasmtime-${VERSION}-x86_64-linux.tar.xz
wget -O - $URL | tar -xJ --strip-components=1 -C ~/.cargo/bin
wasmtime --version
- uses: Swatinem/rust-cache@v2
- - run: cargo test --target wasm32-wasi
+ - name: WASI 0.1 Test
+ run: cargo test --target wasm32-wasip1
+ - name: WASI 0.2 Test
+ run: cargo test --target wasm32-wasip2
build-tier2:
name: Tier 2 Build
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -46,10 +49,7 @@ js = ["wasm-bindgen", "js-sys"]
# Feature to enable custom RNG implementations
custom = []
# Unstable feature to support being a libstd dependency
-rustc-dep-of-std = [
- "compiler_builtins",
- "core",
-]
+rustc-dep-of-std = ["compiler_builtins", "core"]
# Unstable/test-only feature to run wasm-bindgen tests in a browser
test-in-browser = []
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -191,7 +192,8 @@
//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
//! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size
//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
-//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
+//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
+//! [`get-random-u64`]: https://github.com/WebAssembly/WASI/blob/v0.2.1/wasip2/random/random.wit#L23-L28
//! [WebAssembly support]: #webassembly-support
//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
| IIUC the `wasm32-wasi` target uses the preview1 API, so we should keep using `wasi v0.11` on it and `wasip1` targets. Meanwhile, `wasi v0.13` should be used for `wasip2` targets.
But I am not sure what value `target_os` has on `wasm32-wasi`, `wasm32-wasip1`, and `wasm32-wasip2`. Is it `wasi`, `wasip1`, and `wasip2`? Or `wasi` for all of them? If it's the latter, I think we have a problem... | diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -23,7 +23,7 @@ jobs:
# Fixed Nigthly version is used to prevent
# CI failures which are not relevant to PR changes
# on introduction of new Clippy lints.
- toolchain: nightly-2024-06-11
+ toolchain: nightly-2024-09-04
components: clippy,rust-src
- name: std feature
run: cargo clippy --features std
diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -59,8 +59,10 @@ jobs:
run: cargo clippy -Zbuild-std=core --target x86_64-unknown-redox
- name: VxWorks (vxworks.rs)
run: cargo clippy -Zbuild-std=core --target x86_64-wrs-vxworks
- - name: WASI (wasi.rs)
- run: cargo clippy -Zbuild-std=core --target wasm32-wasip2
+ - name: WASI preview 1 (wasi.rs)
+ run: cargo clippy -Zbuild-std=core --target wasm32-wasip1
+ - name: WASI preview 2 (wasi.rs)
+ run: cargo clippy -Zbuild-std=core,alloc --target wasm32-wasip2
- name: Windows 7 (windows7.rs)
run: cargo clippy -Zbuild-std=core --target x86_64-win7-windows-msvc
- name: Windows (windows.rs)
diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -86,7 +88,7 @@ jobs:
- uses: dtolnay/rust-toolchain@master
with:
# We need Nightly for doc_auto_cfg
- toolchain: nightly-2024-06-11
+ toolchain: nightly-2024-09-04
- uses: Swatinem/rust-cache@v2
- name: Generate Docs
env:
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,8 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Breaking Changes
- Update MSRV to 1.38 [#425]
+- Remove support of the `wasm32-wasi` target (use `wasm32-wasip1` or `wasm32-wasip2` instead) [#499]
+
+### Added
+- `wasm32-wasip1` and `wasm32-wasip2` support [#499]
[#425]: https://github.com/rust-random/getrandom/pull/425
+[#499]: https://github.com/rust-random/getrandom/pull/499
## [0.2.15] - 2024-05-06
### Added
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,9 +21,12 @@ core = { version = "1.0", optional = true, package = "rustc-std-workspace-core"
[target.'cfg(unix)'.dependencies]
libc = { version = "0.2.154", default-features = false }
-[target.'cfg(target_os = "wasi")'.dependencies]
+[target.'cfg(all(target_arch = "wasm32", target_os = "wasi", target_env = "p1"))'.dependencies]
wasi = { version = "0.11", default-features = false }
+[target.'cfg(all(target_arch = "wasm32", target_os = "wasi", target_env = "p2"))'.dependencies]
+wasi = { version = "0.13", default-features = false }
+
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
windows-targets = "0.52"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -64,10 +64,10 @@ rustdoc-args = ["--cfg", "docsrs"]
# workaround for https://github.com/cross-rs/cross/issues/1345
[package.metadata.cross.target.x86_64-unknown-netbsd]
pre-build = [
- "mkdir -p /tmp/netbsd",
- "curl https://cdn.netbsd.org/pub/NetBSD/NetBSD-9.2/amd64/binary/sets/base.tar.xz -O",
- "tar -C /tmp/netbsd -xJf base.tar.xz",
- "cp /tmp/netbsd/usr/lib/libexecinfo.so /usr/local/x86_64-unknown-netbsd/lib",
- "rm base.tar.xz",
- "rm -rf /tmp/netbsd",
+ "mkdir -p /tmp/netbsd",
+ "curl https://cdn.netbsd.org/pub/NetBSD/NetBSD-9.2/amd64/binary/sets/base.tar.xz -O",
+ "tar -C /tmp/netbsd -xJf base.tar.xz",
+ "cp /tmp/netbsd/usr/lib/libexecinfo.so /usr/local/x86_64-unknown-netbsd/lib",
+ "rm base.tar.xz",
+ "rm -rf /tmp/netbsd",
]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -24,7 +24,8 @@
//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`]
//! | Emscripten | `*‑emscripten` | [`getentropy`][13]
-//! | WASI | `wasm32‑wasi` | [`random_get`]
+//! | WASI 0.1 | `wasm32‑wasip1` | [`random_get`]
+//! | WASI 0.2 | `wasm32‑wasip2` | [`get-random-u64`]
//! | Web Browser and Node.js | `wasm*‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js, see [WebAssembly support]
//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
//! | Nintendo 3DS | `*-nintendo-3ds` | [`getrandom`][18]
diff --git a/src/wasi.rs b/src/wasi.rs
--- a/src/wasi.rs
+++ b/src/wasi.rs
@@ -1,9 +1,53 @@
-//! Implementation for WASI
+//! Implementation for WASI (preview 1 and 2)
+//!
+//! `target_env = "p1"` was introduced only in Rust 1.80, so on earlier compiler versions this
+//! code will result in a compilation error.
use crate::Error;
use core::mem::MaybeUninit;
-use wasi::random_get;
+#[cfg(not(any(target_env = "p1", target_env = "p2")))]
+compile_error!(
+ "Unknown version of WASI (only previews 1 and 2 are supported) \
+ or Rust version older than 1.80 was used"
+);
+
+#[cfg(target_env = "p1")]
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
- unsafe { random_get(dest.as_mut_ptr().cast::<u8>(), dest.len()) }
+ unsafe { wasi::random_get(dest.as_mut_ptr().cast::<u8>(), dest.len()) }
.map_err(|e| Error::from_os_error(e.raw().into()))
}
+
+#[cfg(target_env = "p2")]
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
+ use core::ptr::copy_nonoverlapping;
+ use wasi::random::random::get_random_u64;
+
+ let (prefix, chunks, suffix) = unsafe { dest.align_to_mut::<MaybeUninit<u64>>() };
+
+ // We use `get_random_u64` instead of `get_random_bytes` because the latter creates
+ // an allocation due to the Wit IDL [restrictions][0]. This should be fine since
+ // the main use case of `getrandom` is seed generation.
+ //
+ // [0]: https://github.com/WebAssembly/wasi-random/issues/27
+ if !prefix.is_empty() {
+ let val = get_random_u64();
+ let src = (&val as *const u64).cast();
+ unsafe {
+ copy_nonoverlapping(src, prefix.as_mut_ptr(), prefix.len());
+ }
+ }
+
+ for dst in chunks {
+ dst.write(get_random_u64());
+ }
+
+ if !suffix.is_empty() {
+ let val = get_random_u64();
+ let src = (&val as *const u64).cast();
+ unsafe {
+ copy_nonoverlapping(src, suffix.as_mut_ptr(), suffix.len());
+ }
+ }
+
+ Ok(())
+}
| 0.2 | 2024-09-05T12:02:48Z | aa13fa58821180248507b81c967d3c731a2ca1d5 | 499 | Consider updating to `wasi v0.13.1+wasi-0.2.0`
Hi! I noticed that `getrandom` appears to be using `wasi v0.11.0+wasi-snapshot-preview1`. The latest version of `wasi` is `wasi v0.13.1+wasi-0.2.0`.
I would normally recommend updating `getrandom` to use `wasi v0.13` (newer versions are almost always better). However, I took a quick look at [`wasi`'s repository](https://github.com/bytecodealliance/wasi-rs), specifically their readme, and found that `wasi` itself recommends staying on `v0.11` [in certain circumstances](https://github.com/bytecodealliance/wasi-rs/blob/94e50002c0d3691f54ad370eb2d10ddad4c2777b/README.md#wasip2-vs-wasip1).
Still, I'm hesitant to simply assume that the `getrandom` developers know of any of this - and in any case, I didn't see issues or PRs with information on why `getrandom` isn't using a newer version. So, I wanted to make this issue. If nothing else, it'll be an opportunity to explain why `getrandom` isn't using a newer version.
Thank you in advance.
| rust-random/getrandom | rust-random__getrandom-499 | 2024-09-27T16:31:03Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"349"
] | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,14 +4,55 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## Unreleased
+## [0.2.9] - 2023-04-03
### Added
-- `getrandom_uninit` [#291]
+- AIX support [#282]
+- `getrandom_uninit` function [#291]
+- `wasm64-unknown-unknown` support [#303]
+- tvOS and watchOS support [#317]
+- QNX/nto support [#325]
+- Support for `getrandom` syscall on NetBSD ≥ 10.0 [#331]
+- `RtlGenRandom` fallback for non-UWP Windows [#337]
### Breaking Changes
- Update MSRV to 1.36 [#291]
+### Fixed
+- Solaris/OpenBSD/Dragonfly build [#301]
+
+### Changed
+- Update MSRV to 1.36 [#291]
+- Use getentropy on Emscripten [#307]
+- Solaris: consistantly use `/dev/random` source [#310]
+- Move 3ds selection above rdrand/js/custom fallback [#312]
+- Remove buffer zeroing from Node.js implementation [#315]
+- Use `open` instead of `open64` [#326]
+- Remove #cfg from bsd_arandom.rs [#332]
+- Hermit: use `sys_read_entropy` syscall [#333]
+- Eliminate potential panic in sys_fill_exact [#334]
+- rdrand: Remove checking for 0 and !0 and instead check CPU family and do a self-test [#335]
+- Move `__getrandom_custom` definition into a const block [#344]
+- Switch the custom backend to Rust ABI [#347]
+
+[#282]: https://github.com/rust-random/getrandom/pull/282
[#291]: https://github.com/rust-random/getrandom/pull/291
+[#301]: https://github.com/rust-random/getrandom/pull/301
+[#303]: https://github.com/rust-random/getrandom/pull/303
+[#307]: https://github.com/rust-random/getrandom/pull/307
+[#310]: https://github.com/rust-random/getrandom/pull/310
+[#312]: https://github.com/rust-random/getrandom/pull/312
+[#315]: https://github.com/rust-random/getrandom/pull/315
+[#317]: https://github.com/rust-random/getrandom/pull/317
+[#325]: https://github.com/rust-random/getrandom/pull/325
+[#326]: https://github.com/rust-random/getrandom/pull/326
+[#331]: https://github.com/rust-random/getrandom/pull/331
+[#332]: https://github.com/rust-random/getrandom/pull/332
+[#333]: https://github.com/rust-random/getrandom/pull/333
+[#334]: https://github.com/rust-random/getrandom/pull/334
+[#335]: https://github.com/rust-random/getrandom/pull/335
+[#337]: https://github.com/rust-random/getrandom/pull/337
+[#344]: https://github.com/rust-random/getrandom/pull/344
+[#347]: https://github.com/rust-random/getrandom/pull/347
## [0.2.8] - 2022-10-20
### Changed
| Cutting a `v0.2.9` release seems reasonable to me. It seem like the only API change is in #291. However, I'm not sure if free functions are the right API for future-proofing extensions to this crate.
@newpavlov would you be OK:
- temporiliy reverting #291,
- Having a bug fix only releae `v0.2.9`
- Add back #291
- Have further discussion about the API
@josephlr
>However, I'm not sure if free functions are the right API for future-proofing extensions to this crate.
Could you expand on that? Note that we may release `getrandom v0.3` in future without causing too much trouble downstream. Most of the ecosystem does not use `getrandom` directly and instead relies on `rand_core` and it does not expose any types from `getrandom` in its public API.
Right now I do not see the need for reverting `getrandom_uninit` and think that we can do release with it.
> Could you expand on that? Note that we may release `getrandom v0.3` in future without causing too much trouble downstream. Most of the ecosystem does not use `getrandom` directly and instead relies on `rand_core` and it does not expose any types from `getrandom` in its public API.
>
> Right now I do not see the need for reverting `getrandom_uninit` and think that we can do release with it.
See https://github.com/rust-random/getrandom/pull/353 for the basic idea. If we think something like that is _maybe_ worth doing, we can revert #291 and release v0.2.9 while we discuss it.
I don't think your proposal conflicts with existence of `getrandom_uninit`. You left the `getrandom` function as a safe default which simply wraps the default option, so `getrandom_uninit` can be handled in the same way.
But if you feel more comfortable releasing v0.2.9 without `getrandom_unit` and feel strongly about it... I am fine with its temporary removal, though I personally would prefer to keep it in the new release.
> I don't think your proposal conflicts with existence of `getrandom_uninit`. You left the `getrandom` function as a safe default which simply wraps the default option, so `getrandom_uninit` can be handled in the same way.
That seems fair. I'm good to do a release with `getrandom_uninit`.
Final question, in https://github.com/rust-random/getrandom/pull/293#issuecomment-1286492125 we talked about `fill_uninit` being a better name than `getrandom_uninit`, do we want to change the name to `fill_uninit` now?
I think `getrandom_uninit` will be a more consistent name for now. In future we may rename it together with `getrandom`.
Sounds good, let's cut a release. I can do it Monday, but I'm OOO until then. | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -340,6 +381,7 @@ Publish initial implementation.
## [0.0.0] - 2019-01-19
Publish an empty template library.
+[0.2.9]: https://github.com/rust-random/getrandom/compare/v0.2.8...v0.2.9
[0.2.8]: https://github.com/rust-random/getrandom/compare/v0.2.7...v0.2.8
[0.2.7]: https://github.com/rust-random/getrandom/compare/v0.2.6...v0.2.7
[0.2.6]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "getrandom"
-version = "0.2.8" # Also update html_root_url in lib.rs when bumping this
+version = "0.2.9" # Also update html_root_url in lib.rs when bumping this
edition = "2018"
authors = ["The Rand Project Developers"]
license = "MIT OR Apache-2.0"
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -184,7 +184,7 @@
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
- html_root_url = "https://docs.rs/getrandom/0.2.8"
+ html_root_url = "https://docs.rs/getrandom/0.2.9"
)]
#![no_std]
#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
| 0.2 | 2023-04-02T02:12:50Z | 03defac1e59234d4ea057ff28f4b30cb0c1bb944 | 354 | Requesting a release
Hi! We're hoping to use this to resolve an infrequent and irritating crash in Firefox (see [bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1816953)) now that we've updated our stdlib to a fixed version. Are there any plans for a release in the near term?
| rust-random/getrandom | rust-random__getrandom-354 | 2023-04-07T11:03:56Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"568"
] | diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -176,15 +210,3 @@ impl fmt::Display for Error {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::Error;
- use core::mem::size_of;
-
- #[test]
- fn test_size() {
- assert_eq!(size_of::<Error>(), 4);
- assert_eq!(size_of::<Result<(), Error>>(), 4);
- }
-}
| diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Do not use `dlsym` on MUSL targets in the `linux_android_with_fallback` backend [#602]
- Remove `linux_android.rs` and use `getrandom.rs` instead [#603]
- Always use `RtlGenRandom` on Windows targets when compiling with pre-1.78 Rust [#610]
+- Internal representation of the `Error` type [#614]
+
+### Removed
+- `Error::INTERNAL_START` and `Error::CUSTOM_START` associated constants [#614]
[#570]: https://github.com/rust-random/getrandom/pull/570
[#572]: https://github.com/rust-random/getrandom/pull/572
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#603]: https://github.com/rust-random/getrandom/pull/603
[#605]: https://github.com/rust-random/getrandom/pull/605
[#610]: https://github.com/rust-random/getrandom/pull/610
+[#614]: https://github.com/rust-random/getrandom/pull/614
## [0.3.1] - 2025-01-28
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -556,7 +561,7 @@ Publish initial implementation.
## [0.0.0] - 2019-01-19
Publish an empty template library.
-[0.3.2]: https://github.com/rust-random/getrandom/compare/v0.3.0...v0.3.2
+[0.3.2]: https://github.com/rust-random/getrandom/compare/v0.3.1...v0.3.2
[0.3.1]: https://github.com/rust-random/getrandom/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/rust-random/getrandom/compare/v0.2.15...v0.3.0
[0.2.15]: https://github.com/rust-random/getrandom/compare/v0.2.14...v0.2.15
diff --git a/src/backends/efi_rng.rs b/src/backends/efi_rng.rs
--- a/src/backends/efi_rng.rs
+++ b/src/backends/efi_rng.rs
@@ -43,7 +43,7 @@ fn init() -> Result<NonNull<rng::Protocol>, Error> {
};
if ret.is_error() {
- return Err(Error::TEMP_EFI_ERROR);
+ return Err(Error::from_uefi_code(ret.as_usize()));
}
let handles_len = buf_size / HANDLE_SIZE;
diff --git a/src/backends/efi_rng.rs b/src/backends/efi_rng.rs
--- a/src/backends/efi_rng.rs
+++ b/src/backends/efi_rng.rs
@@ -112,7 +112,7 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
};
if ret.is_error() {
- Err(Error::TEMP_EFI_ERROR)
+ Err(Error::from_uefi_code(ret.as_usize()))
} else {
Ok(())
}
diff --git a/src/backends/efi_rng.rs b/src/backends/efi_rng.rs
--- a/src/backends/efi_rng.rs
+++ b/src/backends/efi_rng.rs
@@ -121,5 +121,4 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
impl Error {
pub(crate) const BOOT_SERVICES_UNAVAILABLE: Error = Self::new_internal(10);
pub(crate) const NO_RNG_HANDLE: Error = Self::new_internal(11);
- pub(crate) const TEMP_EFI_ERROR: Error = Self::new_internal(12);
}
diff --git a/src/backends/hermit.rs b/src/backends/hermit.rs
--- a/src/backends/hermit.rs
+++ b/src/backends/hermit.rs
@@ -44,10 +44,8 @@ pub fn fill_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
dest = dest.get_mut(len..).ok_or(Error::UNEXPECTED)?;
}
code => {
- let err = u32::try_from(code.unsigned_abs())
- .ok()
- .map_or(Error::UNEXPECTED, Error::from_os_error);
- return Err(err);
+ let code = i32::try_from(code).map_err(|_| Error::UNEXPECTED)?;
+ return Err(Error::from_neg_error_code(code));
}
}
}
diff --git a/src/backends/linux_raw.rs b/src/backends/linux_raw.rs
--- a/src/backends/linux_raw.rs
+++ b/src/backends/linux_raw.rs
@@ -128,11 +128,8 @@ pub fn fill_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
}
Err(_) if ret == EINTR => continue,
Err(_) => {
- let code: u32 = ret
- .wrapping_neg()
- .try_into()
- .map_err(|_| Error::UNEXPECTED)?;
- return Err(Error::from_os_error(code));
+ let code = i32::try_from(ret).map_err(|_| Error::UNEXPECTED)?;
+ return Err(Error::from_neg_error_code(code));
}
}
}
diff --git a/src/backends/solid.rs b/src/backends/solid.rs
--- a/src/backends/solid.rs
+++ b/src/backends/solid.rs
@@ -14,8 +14,6 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
if ret >= 0 {
Ok(())
} else {
- // ITRON error numbers are always negative, so we negate it so that it
- // falls in the dedicated OS error range (1..INTERNAL_START).
- Err(Error::from_os_error(ret.unsigned_abs()))
+ Err(Error::from_neg_error_code(ret))
}
}
diff --git a/src/backends/wasi_p1.rs b/src/backends/wasi_p1.rs
--- a/src/backends/wasi_p1.rs
+++ b/src/backends/wasi_p1.rs
@@ -21,11 +21,6 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
let ret = unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) };
match ret {
0 => Ok(()),
- code => {
- let err = u32::try_from(code)
- .map(Error::from_os_error)
- .unwrap_or(Error::UNEXPECTED);
- Err(err)
- }
+ code => Err(Error::from_neg_error_code(code)),
}
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,15 +1,20 @@
#[cfg(feature = "std")]
extern crate std;
-use core::{fmt, num::NonZeroU32};
+use core::fmt;
// This private alias mirrors `std::io::RawOsError`:
// https://doc.rust-lang.org/std/io/type.RawOsError.html)
cfg_if::cfg_if!(
if #[cfg(target_os = "uefi")] {
+ // See the UEFI spec for more information:
+ // https://uefi.org/specs/UEFI/2.10/Apx_D_Status_Codes.html
type RawOsError = usize;
+ type NonZeroRawOsError = core::num::NonZeroUsize;
+ const UEFI_ERROR_FLAG: RawOsError = 1 << (RawOsError::BITS - 1);
} else {
type RawOsError = i32;
+ type NonZeroRawOsError = core::num::NonZeroI32;
}
);
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -19,16 +24,16 @@ cfg_if::cfg_if!(
/// if so, which error code the OS gave the application. If such an error is
/// encountered, please consult with your system documentation.
///
-/// Internally this type is a NonZeroU32, with certain values reserved for
-/// certain purposes, see [`Error::INTERNAL_START`] and [`Error::CUSTOM_START`].
-///
/// *If this crate's `"std"` Cargo feature is enabled*, then:
/// - [`getrandom::Error`][Error] implements
/// [`std::error::Error`](https://doc.rust-lang.org/std/error/trait.Error.html)
/// - [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) implements
/// [`From<getrandom::Error>`](https://doc.rust-lang.org/std/convert/trait.From.html).
+
+// note: on non-UEFI targets OS errors are represented as negative integers,
+// while on UEFI targets OS errors have the highest bit set to 1.
#[derive(Copy, Clone, Eq, PartialEq)]
-pub struct Error(NonZeroU32);
+pub struct Error(NonZeroRawOsError);
impl Error {
/// This target/platform is not supported by `getrandom`.
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -38,29 +43,32 @@ impl Error {
/// Encountered an unexpected situation which should not happen in practice.
pub const UNEXPECTED: Error = Self::new_internal(2);
- /// Codes below this point represent OS Errors (i.e. positive i32 values).
- /// Codes at or above this point, but below [`Error::CUSTOM_START`] are
- /// reserved for use by the `rand` and `getrandom` crates.
- pub const INTERNAL_START: u32 = 1 << 31;
+ /// Internal errors can be in the range of 2^16..2^17
+ const INTERNAL_START: RawOsError = 1 << 16;
+ /// Custom errors can be in the range of 2^17..(2^17 + 2^16)
+ const CUSTOM_START: RawOsError = 1 << 17;
- /// Codes at or above this point can be used by users to define their own
- /// custom errors.
- pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30);
+ /// Creates a new instance of an `Error` from a negative error code.
+ #[cfg(not(target_os = "uefi"))]
+ #[allow(dead_code)]
+ pub(super) fn from_neg_error_code(code: RawOsError) -> Self {
+ if code < 0 {
+ let code = NonZeroRawOsError::new(code).expect("`code` is negative");
+ Self(code)
+ } else {
+ Error::UNEXPECTED
+ }
+ }
- /// Creates a new instance of an `Error` from a particular OS error code.
- ///
- /// This method is analogous to [`std::io::Error::from_raw_os_error()`][1],
- /// except that it works in `no_std` contexts and `code` will be
- /// replaced with `Error::UNEXPECTED` if it isn't in the range
- /// `1..Error::INTERNAL_START`. Thus, for the result `r`,
- /// `r == Self::UNEXPECTED || r.raw_os_error().unsigned_abs() == code`.
- ///
- /// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.from_raw_os_error
+ /// Creates a new instance of an `Error` from an UEFI error code.
+ #[cfg(target_os = "uefi")]
#[allow(dead_code)]
- pub(super) fn from_os_error(code: u32) -> Self {
- match NonZeroU32::new(code) {
- Some(code) if code.get() < Self::INTERNAL_START => Self(code),
- _ => Self::UNEXPECTED,
+ pub(super) fn from_uefi_code(code: RawOsError) -> Self {
+ if code & UEFI_ERROR_FLAG != 0 {
+ let code = NonZeroRawOsError::new(code).expect("The highest bit of `code` is set to 1");
+ Self(code)
+ } else {
+ Self::UNEXPECTED
}
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -79,27 +87,53 @@ impl Error {
#[inline]
pub fn raw_os_error(self) -> Option<RawOsError> {
let code = self.0.get();
- if code >= Self::INTERNAL_START {
- return None;
+
+ // note: in this method we need to cover only backends which rely on
+ // `Error::{from_error_code, from_errno, from_uefi_code}` methods,
+ // on all other backends this method always returns `None`.
+
+ #[cfg(target_os = "uefi")]
+ {
+ if code & UEFI_ERROR_FLAG != 0 {
+ Some(code)
+ } else {
+ None
+ }
+ }
+
+ #[cfg(not(target_os = "uefi"))]
+ {
+ // On most targets `std` expects positive error codes while retrieving error strings:
+ // - `libc`-based targets use `strerror_r` which expects positive error codes.
+ // - Hermit relies on the `hermit-abi` crate, which expects positive error codes:
+ // https://docs.rs/hermit-abi/0.4.0/src/hermit_abi/errno.rs.html#400-532
+ // - WASIp1 uses the same conventions as `libc`:
+ // https://github.com/rust-lang/rust/blob/1.85.0/library/std/src/sys/pal/wasi/os.rs#L57-L67
+ //
+ // The only exception is Solid, `std` expects negative system error codes, see:
+ // https://github.com/rust-lang/rust/blob/1.85.0/library/std/src/sys/pal/solid/error.rs#L5-L31
+ if code >= 0 {
+ None
+ } else if cfg!(not(target_os = "solid_asp3")) {
+ code.checked_neg()
+ } else {
+ Some(code)
+ }
}
- let errno = RawOsError::try_from(code).ok()?;
- #[cfg(target_os = "solid_asp3")]
- let errno = -errno;
- Some(errno)
}
/// Creates a new instance of an `Error` from a particular custom error code.
pub const fn new_custom(n: u16) -> Error {
- // SAFETY: code > 0 as CUSTOM_START > 0 and adding n won't overflow a u32.
- let code = Error::CUSTOM_START + (n as u32);
- Error(unsafe { NonZeroU32::new_unchecked(code) })
+ // SAFETY: code > 0 as CUSTOM_START > 0 and adding `n` won't overflow `RawOsError`.
+ let code = Error::CUSTOM_START + (n as RawOsError);
+ Error(unsafe { NonZeroRawOsError::new_unchecked(code) })
}
/// Creates a new instance of an `Error` from a particular internal error code.
pub(crate) const fn new_internal(n: u16) -> Error {
- // SAFETY: code > 0 as INTERNAL_START > 0 and adding n won't overflow a u32.
- let code = Error::INTERNAL_START + (n as u32);
- Error(unsafe { NonZeroU32::new_unchecked(code) })
+ // SAFETY: code > 0 as INTERNAL_START > 0 and adding `n` won't overflow `RawOsError`.
+ let code = Error::INTERNAL_START + (n as RawOsError);
+ Error(unsafe { NonZeroRawOsError::new_unchecked(code) })
}
fn internal_desc(&self) -> Option<&'static str> {
diff --git a/src/util_libc.rs b/src/util_libc.rs
--- a/src/util_libc.rs
+++ b/src/util_libc.rs
@@ -34,14 +34,16 @@ cfg_if! {
}
pub(crate) fn last_os_error() -> Error {
- let errno: libc::c_int = unsafe { get_errno() };
+ // We assume that on all targets which use the `util_libc` module `c_int` is equal to `i32`
+ let errno: i32 = unsafe { get_errno() };
- // c_int-to-u32 conversion is lossless for nonnegative values if they are the same size.
- const _: () = assert!(core::mem::size_of::<libc::c_int>() == core::mem::size_of::<u32>());
-
- match u32::try_from(errno) {
- Ok(code) if code != 0 => Error::from_os_error(code),
- _ => Error::ERRNO_NOT_POSITIVE,
+ if errno > 0 {
+ let code = errno
+ .checked_neg()
+ .expect("Positive number can be always negated");
+ Error::from_neg_error_code(code)
+ } else {
+ Error::ERRNO_NOT_POSITIVE
}
}
| 0.3 | 2025-03-03T13:33:55Z | 76ed428dadd7cc8be4f04d495a22806e86e7749e | 614 | `Error` on targets where `RawOsError` is not equal to `i32`
Previously, all Rust targets with `std` were using `i32` for "raw" OS error codes, i.e. `io::Error::raw_os_error/from_raw_os_error` have accepted `i32`. We have encoded this assumption in `Error::raw_os_error`, `fmt::Debug/Display`, and `From<Error> for io::Error` implementations.
But in the recently added UEFI `std` implementation `usize` is used for error codes instead as per [UEFI spec](https://uefi.org/specs/UEFI/2.10/Apx_D_Status_Codes.html). It's reflected by the new (Nightly-only) type alias [`RawOsError`](https://doc.rust-lang.org/std/io/type.RawOsError.html)
For now, we just added `cfg`-based exceptions for UEFI targets in the relevant internal implementations (see #566). But it may be worth to reconsider our use of `NonZeroU32` for `Error` internal representation and return type of `Error::raw_os_error`.
cc @usamoi
| rust-random/getrandom | rust-random__getrandom-614 | 2025-03-07T09:37:21Z | 76ed428dadd7cc8be4f04d495a22806e86e7749e | |
[
"608"
] | diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -83,6 +83,7 @@ level = "warn"
check-cfg = [
'cfg(getrandom_backend, values("custom", "rdrand", "rndr", "linux_getrandom", "wasm_js"))',
'cfg(getrandom_msan)',
+ 'cfg(getrandom_windows_legacy)',
'cfg(getrandom_test_linux_fallback)',
'cfg(getrandom_test_linux_without_fallback)',
'cfg(getrandom_test_netbsd_fallback)',
| Hm, I think we could add Rust compiler version detection to our build script and switch to the `windows7` backend on older compilers. Alternatively, we could introduce a `getrandom_backend = "windows_legacy"` configuration flag. | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.3.2] - UNRELEASED
+
+### Changed
+- Always use `RtlGenRandom` on Windows targets when compiling with pre-1.78 Rust [#610]
+
+[#610]: https://github.com/rust-random/getrandom/pull/610
+
## [0.3.1] - 2025-01-28
### Fixed
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -526,6 +533,8 @@ Publish initial implementation.
## [0.0.0] - 2019-01-19
Publish an empty template library.
+[0.3.2]: https://github.com/rust-random/getrandom/compare/v0.3.0...v0.3.2
+[0.3.1]: https://github.com/rust-random/getrandom/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/rust-random/getrandom/compare/v0.2.15...v0.3.0
[0.2.15]: https://github.com/rust-random/getrandom/compare/v0.2.14...v0.2.15
[0.2.14]: https://github.com/rust-random/getrandom/compare/v0.2.13...v0.2.14
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -67,7 +67,7 @@ libc = { version = "0.2.154", default-features = false }
wasi = { version = "0.14", default-features = false }
# windows7
-[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
+[target.'cfg(all(windows, not(target_vendor = "win7"), not(getrandom_windows_legacy)))'.dependencies]
windows-targets = "0.53"
# wasm_js
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -43,7 +43,7 @@ fn get_random_u128() -> Result<u128, getrandom::Error> {
| Target | Target Triple | Implementation
| ------------------ | ------------------ | --------------
| Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
-| Windows 10+ | `*‑windows‑*` | [`ProcessPrng`]
+| Windows 10+ | `*‑windows‑*` | [`ProcessPrng`] on Rust 1.78+, [`RtlGenRandom`] otherwise
| Windows 7, 8 | `*-win7‑windows‑*` | [`RtlGenRandom`]
| macOS | `*‑apple‑darwin` | [`getentropy`][3]
| iOS, tvOS, watchOS | `*‑apple‑{ios,tvos,watchos}` | [`CCRandomGenerateBytes`]
diff --git a/build.rs b/build.rs
--- a/build.rs
+++ b/build.rs
@@ -1,9 +1,57 @@
-// Automatically detect cfg(sanitize = "memory") even if cfg(sanitize) isn't
-// supported. Build scripts get cfg() info, even if the cfg is unstable.
+use std::{env, ffi::OsString, process::Command};
+
+/// Tries to get the minor version of the Rust compiler in use.
+/// If it fails for any reason, returns `None`.
+///
+/// Based on the `rustc_version` crate.
+fn rustc_minor_version() -> Option<u64> {
+ let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
+ let mut cmd = if let Some(wrapper) = env::var_os("RUSTC_WRAPPER").filter(|w| !w.is_empty()) {
+ let mut cmd = Command::new(wrapper);
+ cmd.arg(rustc);
+ cmd
+ } else {
+ Command::new(rustc)
+ };
+
+ let out = cmd.arg("-vV").output().ok()?;
+
+ if !out.status.success() {
+ return None;
+ }
+
+ let stdout = std::str::from_utf8(&out.stdout).ok()?;
+
+ // Assumes that the first line contains "rustc 1.xx.0-channel (abcdef 2025-01-01)"
+ // where "xx" is the minor version which we want to extract
+ let mut lines = stdout.lines();
+ let first_line = lines.next()?;
+ let minor_ver_str = first_line.split(".").nth(1)?;
+ minor_ver_str.parse().ok()
+}
+
fn main() {
+ // Automatically detect cfg(sanitize = "memory") even if cfg(sanitize) isn't
+ // supported. Build scripts get cfg() info, even if the cfg is unstable.
println!("cargo:rerun-if-changed=build.rs");
let santizers = std::env::var("CARGO_CFG_SANITIZE").unwrap_or_default();
if santizers.contains("memory") {
println!("cargo:rustc-cfg=getrandom_msan");
}
+
+ // Use `RtlGenRandom` on older compiler versions since win7 targets
+ // were introduced only in Rust 1.78
+ let target_family = env::var_os("CARGO_CFG_TARGET_FAMILY").and_then(|f| f.into_string().ok());
+ if target_family.as_deref() == Some("windows") {
+ /// Minor version of the Rust compiler in which win7 targets were inroduced
+ const WIN7_INTRODUCED_MINOR_VER: u64 = 78;
+
+ match rustc_minor_version() {
+ Some(minor_ver) if minor_ver < WIN7_INTRODUCED_MINOR_VER => {
+ println!("cargo:rustc-cfg=getrandom_windows_legacy");
+ }
+ None => println!("cargo:warning=Couldn't detect minor version of the Rust compiler"),
+ _ => {}
+ }
+ }
}
diff --git a/src/backends.rs b/src/backends.rs
--- a/src/backends.rs
+++ b/src/backends.rs
@@ -145,7 +145,7 @@ cfg_if! {
} else if #[cfg(target_os = "solid_asp3")] {
mod solid;
pub use solid::*;
- } else if #[cfg(all(windows, target_vendor = "win7"))] {
+ } else if #[cfg(all(windows, any(target_vendor = "win7", getrandom_windows_legacy)))] {
mod windows7;
pub use windows7::*;
} else if #[cfg(windows)] {
| 0.3 | 2025-02-26T13:44:31Z | 491d9d4a9cb965216a4e303c6d898635812ed723 | 610 | Windows 7 support on Rust 1.77 and lower
Currently the Window 10 and newer code using `ProcessPrng` is always chosen on Rust 1.77 and lower, because target_vendor = "win7" was only introduced with Rust 1.78. As the `ProcessPrng` API does not exist on Windows 7, programs just refuse to start.
Code in backend.rs:
```
} else if #[cfg(all(windows, target_vendor = "win7"))] {
mod windows7;
pub use windows7::*;
} else if #[cfg(windows)] {
mod windows;
pub use windows::*;
```
Would it be possible to either always use the safe Windows 7 code on older Rust versions (1.77 and lower) or change the code to automatically detect if `ProcessPrng` is available using e.g. GetProcAddress, so the best API is chosen depending on what is available? All older Rust versions support Windows 7 by default, so it seems wrong to statically depend on a Windows 10 API with no way to disable this dependency.
| rust-random/getrandom | rust-random__getrandom-610 | 2025-03-03T11:26:20Z | 76ed428dadd7cc8be4f04d495a22806e86e7749e |
[
"229"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -61,6 +61,7 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo test
- run: cargo test --features=std
+ - run: cargo test --features=linux_disable_fallback
- run: cargo test --features=custom # custom should do nothing here
- if: ${{ matrix.toolchain == 'nightly' }}
run: cargo test --benches
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -32,6 +32,9 @@ wasm-bindgen-test = "0.3.18"
[features]
# Implement std-only traits for getrandom::Error
std = []
+# Disable `/dev/urandom` fallback for Linux and Android targets.
+# Bumps minimum supported Linux kernel version to 3.17 and Android API level to 23 (Marshmallow).
+linux_disable_fallback = []
# Feature to enable fallback RDRAND-based implementation on x86/x86_64
rdrand = []
# Feature to enable JavaScript bindings on wasm*-unknown-unknown
| The problem here is that this crate is used in a very wide range of environments, and we don't want to break them. I also don't see how falling back to the `/dev/urandom` implementation hurts security. It might hurt _reliability_ but if you've hit this codepath, then something is already unreliable.
Looking at other implementaitons, [`boringssl` doesn't check for `EPERM` it just fails](https://boringssl.googlesource.com/boringssl/+/818c4aafa86fa3922f969220473a27c163214b73/crypto/fipsmodule/rand/urandom.c#148), [`openssl` falls back on any sort of failure from the gerandom syscall](https://github.com/openssl/openssl/blob/e257d3e76ffb848b7607b04057257323dc51c3b4/providers/implementations/rands/seeding/rand_unix.c#L645), and the Rust standard library [checks for `EPERM`](https://github.com/rust-lang/rust/blob/4bd30785eb6e55f317b41b7c278f438807eeb174/library/std/src/sys/unix/rand.rs#L100).
So overall, I think we should either:
- Only fallback on `ENOSYS`
- Fallback on any sort of unexpected error from the getrandom syscall
- Have some (off by default) control that just says "don't ever fall back to file-based interfaces". This is basically [what `BORINGSSL_FIPS` does](https://boringssl.googlesource.com/boringssl/+/818c4aafa86fa3922f969220473a27c163214b73/crypto/fipsmodule/rand/urandom.c#190).
> I also don't see how falling back to the `/dev/urandom` implementation hurts security. It might hurt _reliability_ but if you've hit this codepath, then something is already unreliable.
All file I/O interfaces are risky to use because it is too easy to close the `/dev/random`. file descriptor, and then cause the random bytes to be read from whatever file happens to be opened after closing it. See the issues in Python that forced them to jump through a lot of hoops to try to mitigate those risks.
> * Have some (off by default) control that just says "don't ever fall back to file-based interfaces". This is basically [what `BORINGSSL_FIPS` does](https://boringssl.googlesource.com/boringssl/+/818c4aafa86fa3922f969220473a27c163214b73/crypto/fipsmodule/rand/urandom.c#190).
That's probably because their FIPS validation requires an operating system that has `getrandom`, so perhaps not as relevant here.
Rather than having an off-by-default feature that says "don't ever fall back," `getrandom` could have a default feature that enables the fallback. This is what *ring* does with default feature `dev_urandom_fallback`.
Don't the newest versions of libstd now require a kernel that is new enough to have `getrandom`? So in the configuration that is being used by libstd, we should definitely not do the fallback. (This would then allow `getrandom` to use safe `std::fs` APIs instead of unsafe code to do the file I/O, IIUC.)
>Don't the newest versions of libstd now require a kernel that is new enough to have getrandom?
No. On x86 Rust [supports](https://doc.rust-lang.org/beta/rustc/platform-support.html) kernel 3.2+, while `getrandom` was introduced only in 3.17.
>Have some (off by default) control that just says "don't ever fall back to file-based interfaces".
If wea re to introduce such control, I think we should use configuration flags for it, not crate features, i.e. `#[cfg(getrandom_only)]` instead of `#[cfg(feature = "getrandom_only")]`. Such crate feature would subtract crate functionality and some argue that it's an incorrect use of crate features.
My goal here is to limit the fallback logic to "Use File I/O if and only if getrandom isn't implemented in the kernel," instead of "Use File I/O if there is any issue at all trying to use getrandom."
I believe the main concern here is that some devices shipped with broken kernels that return EPERM (or some other error) instead of ENOSYS. I think there was one specific brand of home NAS that was known to have this issue, for example.
I think that at least Android has not been known to have that problem though, so I think at least on Android we can be stricter and require that the error be ENOSYS. Further, using the same logic as #376, we can become stricter based on the target_arch based on the platform support policy. Taking these baby steps would be a material improvement.
>I think that at least Android has not been known to have that problem though, so I think at least on Android we can be stricter and require that the error be ENOSYS
Sounds good to me.
> My goal here is to limit the fallback logic to "Use File I/O if and only if getrandom isn't implemented in the kernel," instead of "Use File I/O if there is any issue at all trying to use getrandom."
First of all, the above mischaracterizes the current fallback strategy. The fallback only happens on ENOSYS and EPERM, not "any issue at all." I am sorry about that exaggeration.
The product that seemed to force libraries to accept EPERM was QNAP Container Station, which was running applications in Docker Containers, using a seccomp policy that blocked `getrandom` (probably it used an allowlist approach and hadn't added getrandom to its allowlist). I looked at docker's default seccomp policies and for at least 9 years getrandom appears to have been in the default policy. So I think it is very likely that very few systems really need the EPERM support. And also the issues with QNAP Container Station were several years ago, so maybe that product doesn't even need this workaround anymore as I imagine by now it has been forced to update its allowlist of syscalls.
In PR #396 @newpavlov proposes to follow my suggestion above and remove the EPERM fallback on Android. I think that is a good change, whether it is in that PR or on a new one. I think the change should include the comment "// The fallback on EPERM is intentionally not done on Android since this workaround seems to be needed only for specific Linux-based products that aren't based on Android. See https://github.com/rust-random/getrandom/issues/229."
I also think we could have a feature flag that allows users to disable the fallback on PERM for `target_os = "linux"` as well, to allow for experimentation with the goal of making that behavior the default. Especially if we could find somebody from QNAP to help us.
Another minor detail: As https://www.qnap.com/en/how-to/faq/article/how-do-i-find-out-if-my-nas-uses-an-arm-or-x86-processor indicates, perhaps the EPERM fallback is only needed for aarch64 and x86_64 (and arm and/or x86?) target architectures.
>perhaps the EPERM fallback is only needed for aarch64 and x86_64 (and arm and/or x86?) target architectures.
I would prefer to keep it simple and more or less consistent. I don't think a new feature flag would pull its weight (especially considering introduction of the `disable_urandom_fallback` flag). Hopefully, Rust will bump min kernel versions to 3.17+ for all targets relatively soon and we will be able to drop the file fallback completely. | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## Unreleased
+### Added
+- `linux_disable_fallback` crate feature to disable `/dev/urandom`-based fallback on Linux and
+ Android targets. Enabling this feature bumps minimum supported Linux kernel version to 4.17 and
+ Android API level to 23 (Marshmallow). [#396]
+
+### Changed
+- Disable `/dev/urandom` fallback for Linux targets outside of the following `target_arch`es:
+ `aarch64`, `arm`, `powerpc`, `powerpc64`, `s390x`, `x86`, `x86_64` [#396]
+- Do not catch `EPERM` error code on Android while checking availability of
+ the `getrandom` syscall [#396]
+
+[#396]: https://github.com/rust-random/getrandom/pull/396
+
## [0.2.12] - 2024-01-09
### Fixed
- Custom backend for targets without atomics [#385]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -99,11 +99,14 @@
//! This crate will then use the provided `webcrypto` implementation.
//!
//! ### Platform Support
-//! This crate generally supports the same operating system and platform versions that the Rust standard library does.
-//! Additional targets may be supported using pluggable custom implementations.
+//! This crate generally supports the same operating system and platform versions
+//! that the Rust standard library does. Additional targets may be supported using
+//! pluggable custom implementations.
//!
-//! This means that as Rust drops support for old versions of operating systems (such as old Linux kernel versions, Android API levels, etc)
-//! in stable releases, `getrandom` may create new patch releases (`0.N.x`) that remove support for outdated platform versions.
+//! This means that as Rust drops support for old versions of operating systems
+//! (such as old Linux kernel versions, Android API levels, etc) in stable releases,
+//! `getrandom` may create new patch releases (`0.N.x`) that remove support for
+//! outdated platform versions.
//!
//! ### Custom implementations
//!
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -220,10 +223,48 @@ cfg_if! {
if #[cfg(any(target_os = "haiku", target_os = "redox", target_os = "nto", target_os = "aix"))] {
mod util_libc;
#[path = "use_file.rs"] mod imp;
- } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
+ } else if #[cfg(all(
+ not(feature = "linux_disable_fallback"),
+ any(
+ // Rust supports Android API level 19 (KitKat) [0] and the next upgrade targets
+ // level 21 (Lollipop) [1], while `getrandom(2)` was added only in
+ // level 23 (Marshmallow). Note that it applies only to the "old" `target_arch`es,
+ // RISC-V Android targets sufficiently new API level, same will apply for potential
+ // new Android `target_arch`es.
+ // [0]: https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html
+ // [1]: https://github.com/rust-lang/rust/pull/120593
+ all(
+ target_os = "android",
+ any(
+ target_arch = "aarch64",
+ target_arch = "arm",
+ target_arch = "x86",
+ target_arch = "x86_64",
+ ),
+ ),
+ // Only on these `target_arch`es Rust supports Linux kernel versions (3.2+)
+ // that precede the version (3.17) in which `getrandom(2)` was added:
+ // https://doc.rust-lang.org/stable/rustc/platform-support.html
+ all(
+ target_os = "linux",
+ any(
+ target_arch = "aarch64",
+ target_arch = "arm",
+ target_arch = "powerpc",
+ target_arch = "powerpc64",
+ target_arch = "s390x",
+ target_arch = "x86",
+ target_arch = "x86_64",
+ ),
+ )
+ ),
+ ))] {
mod util_libc;
mod use_file;
mod lazy;
+ #[path = "linux_android_with_fallback.rs"] mod imp;
+ } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
+ mod util_libc;
#[path = "linux_android.rs"] mod imp;
} else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
mod util_libc;
diff --git a/src/linux_android.rs b/src/linux_android.rs
--- a/src/linux_android.rs
+++ b/src/linux_android.rs
@@ -1,40 +1,7 @@
-//! Implementation for Linux / Android
-use crate::{
- lazy::LazyBool,
- util_libc::{last_os_error, sys_fill_exact},
- {use_file, Error},
-};
+//! Implementation for Linux / Android without `/dev/urandom` fallback
+use crate::{util_libc, Error};
use core::mem::MaybeUninit;
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
- // getrandom(2) was introduced in Linux 3.17
- static HAS_GETRANDOM: LazyBool = LazyBool::new();
- if HAS_GETRANDOM.unsync_init(is_getrandom_available) {
- sys_fill_exact(dest, |buf| unsafe {
- getrandom(buf.as_mut_ptr() as *mut libc::c_void, buf.len(), 0)
- })
- } else {
- use_file::getrandom_inner(dest)
- }
-}
-
-fn is_getrandom_available() -> bool {
- let res = unsafe { getrandom(core::ptr::null_mut(), 0, libc::GRND_NONBLOCK) };
- if res < 0 {
- match last_os_error().raw_os_error() {
- Some(libc::ENOSYS) => false, // No kernel support
- Some(libc::EPERM) => false, // Blocked by seccomp
- _ => true,
- }
- } else {
- true
- }
-}
-
-unsafe fn getrandom(
- buf: *mut libc::c_void,
- buflen: libc::size_t,
- flags: libc::c_uint,
-) -> libc::ssize_t {
- libc::syscall(libc::SYS_getrandom, buf, buflen, flags) as libc::ssize_t
+ util_libc::sys_fill_exact(dest, util_libc::getrandom_syscall)
}
diff --git /dev/null b/src/linux_android_with_fallback.rs
new file mode 100644
--- /dev/null
+++ b/src/linux_android_with_fallback.rs
@@ -0,0 +1,33 @@
+//! Implementation for Linux / Android with `/dev/urandom` fallback
+use crate::{
+ lazy::LazyBool,
+ util_libc::{getrandom_syscall, last_os_error, sys_fill_exact},
+ {use_file, Error},
+};
+use core::mem::MaybeUninit;
+
+pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
+ // getrandom(2) was introduced in Linux 3.17
+ static HAS_GETRANDOM: LazyBool = LazyBool::new();
+ if HAS_GETRANDOM.unsync_init(is_getrandom_available) {
+ sys_fill_exact(dest, getrandom_syscall)
+ } else {
+ use_file::getrandom_inner(dest)
+ }
+}
+
+fn is_getrandom_available() -> bool {
+ if getrandom_syscall(&mut []) < 0 {
+ match last_os_error().raw_os_error() {
+ Some(libc::ENOSYS) => false, // No kernel support
+ // The fallback on EPERM is intentionally not done on Android since this workaround
+ // seems to be needed only for specific Linux-based products that aren't based
+ // on Android. See https://github.com/rust-random/getrandom/issues/229.
+ #[cfg(target_os = "linux")]
+ Some(libc::EPERM) => false, // Blocked by seccomp
+ _ => true,
+ }
+ } else {
+ true
+ }
+}
diff --git a/src/util_libc.rs b/src/util_libc.rs
--- a/src/util_libc.rs
+++ b/src/util_libc.rs
@@ -151,3 +151,16 @@ pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> {
}
}
}
+
+/// Thin wrapper around the `getrandom()` Linux system call
+#[cfg(any(target_os = "android", target_os = "linux"))]
+pub fn getrandom_syscall(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t {
+ unsafe {
+ libc::syscall(
+ libc::SYS_getrandom,
+ buf.as_mut_ptr() as *mut libc::c_void,
+ buf.len(),
+ 0,
+ ) as libc::ssize_t
+ }
+}
| 0.2 | 2024-02-19T13:13:01Z | 5f0701faba5b83ebf144af9973582904f60849b7 | 396 | Should `getrandom()` really fall back to File I/O when the getrandom syscall returns EPERM?
If the `getrandom` syscall returns `EPERM` then it's probably because (a) the OS is buggy, e.g. QNAP apparently, or (b) the syscall is blocked by seccomp filtering or similar.
In the case where the syscall is blocked by a sandbox, I think it doesn't make sense to fall back to File I/O; why would a sandbox intentionally block `getrandom` but also intentionally allow file I/O that/s equivalent or worse (w.r.t security)? This indicates to me that the sandbox is buggy and needs to be fixed.
In the case of the QNAP situation, it is purely a bug on their part and it seems like it should be fixed on their side, instead of making security worse on our side. Note that we don't fall back on EFAULT which is another buggy result that sometimes occurs for this syscall.
At the very least, I'd love to have a way to opt out of falling back to File I/O on EPERM, but ideally we'd only fall back on ENOSYS.
| rust-random/getrandom | rust-random__getrandom-396 | 2024-03-27T12:46:47Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"254"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -166,8 +166,9 @@ jobs:
strategy:
matrix:
target: [
- # See: https://github.com/rust-random/getrandom/issues/254
- # sparcv9-sun-solaris,
+ sparcv9-sun-solaris,
+ x86_64-unknown-illumos,
+ x86_64-unknown-freebsd,
x86_64-unknown-netbsd,
]
steps:
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -277,7 +278,6 @@ jobs:
strategy:
matrix:
target: [
- x86_64-unknown-freebsd,
x86_64-fuchsia,
x86_64-unknown-redox,
x86_64-fortanix-unknown-sgx,
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -288,7 +288,7 @@ jobs:
with:
profile: minimal
target: ${{ matrix.target }}
- toolchain: nightly # Required to build libc for Redox
+ toolchain: stable
override: true
- uses: Swatinem/rust-cache@v1
- name: Build
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -319,6 +319,14 @@ jobs:
run: cargo build -Z build-std=core --target=aarch64-kmc-solid_asp3
- name: Nintendo 3DS
run: cargo build -Z build-std=core --target=armv6k-nintendo-3ds
+ - name: RISC-V ESP-IDF
+ run: cargo build -Z build-std=core --target=riscv32imc-esp-espidf
+ - name: OpenBSD
+ run: cargo build -Z build-std=std --target=x86_64-unknown-openbsd --features=std
+ - name: Dragonfly BSD
+ run: cargo build -Z build-std=std --target=x86_64-unknown-dragonfly --features=std
+ - name: Haiku OS
+ run: cargo build -Z build-std=std --target=x86_64-unknown-haiku --features=std
clippy-fmt:
name: Clippy + rustfmt
| diff --git a/src/dragonfly.rs b/src/dragonfly.rs
--- a/src/dragonfly.rs
+++ b/src/dragonfly.rs
@@ -12,7 +12,7 @@ use crate::{
util_libc::{sys_fill_exact, Weak},
Error,
};
-use std::mem::MaybeUninit;
+use core::mem::MaybeUninit;
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
diff --git a/src/dragonfly.rs b/src/dragonfly.rs
--- a/src/dragonfly.rs
+++ b/src/dragonfly.rs
@@ -21,7 +21,9 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getrandom(2) was introduced in DragonflyBSD 5.7
if let Some(fptr) = GETRANDOM.ptr() {
let func: GetRandomFn = unsafe { core::mem::transmute(fptr) };
- return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) });
+ return sys_fill_exact(dest, |buf| unsafe {
+ func(buf.as_mut_ptr() as *mut u8, buf.len(), 0)
+ });
} else {
use_file::getrandom_inner(dest)
}
diff --git a/src/openbsd.rs b/src/openbsd.rs
--- a/src/openbsd.rs
+++ b/src/openbsd.rs
@@ -8,6 +8,7 @@
//! Implementation for OpenBSD
use crate::{util_libc::last_os_error, Error};
+use core::mem::MaybeUninit;
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally.
diff --git a/src/solaris_illumos.rs b/src/solaris_illumos.rs
--- a/src/solaris_illumos.rs
+++ b/src/solaris_illumos.rs
@@ -22,7 +22,7 @@ use crate::{
util_libc::{sys_fill_exact, Weak},
Error,
};
-use core::mem;
+use core::mem::{self, MaybeUninit};
#[cfg(target_os = "illumos")]
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
diff --git a/src/solaris_illumos.rs b/src/solaris_illumos.rs
--- a/src/solaris_illumos.rs
+++ b/src/solaris_illumos.rs
@@ -38,7 +38,7 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// derived platforms for atomically obtaining random data.
for chunk in dest.chunks_mut(256) {
sys_fill_exact(chunk, |buf| unsafe {
- func(buf.as_mut_ptr(), buf.len(), 0) as libc::ssize_t
+ func(buf.as_mut_ptr() as *mut u8, buf.len(), 0) as libc::ssize_t
})?
}
Ok(())
| 0.2 | 2022-10-22T00:21:59Z | bd0654fe70980583e51573e755bafa3b2f8342d9 | 301 | Fix Solaris cross-build job
It fails with linker error, e.g. see: https://github.com/rust-random/getrandom/runs/5698849705
Relevant Rust issue: https://github.com/rust-lang/rust/pull/94052
It looks like due to `libc` changes we now need Solaris-specific `sendfile` and `lgrp`.
| rust-random/getrandom | rust-random__getrandom-301 | 2022-10-22T20:28:43Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 | |
[
"296"
] | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -219,6 +219,24 @@ jobs:
- name: Test (custom getrandom)
run: cargo test --target=wasm32-unknown-unknown --features=custom
+ wasm64-tests:
+ name: WASM memory64
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ toolchain: nightly
+ components: rust-src
+ override: true
+ - uses: Swatinem/rust-cache@v1
+ - name: Build and Link tests (build-std)
+ # This target is Tier 3, so we have to build libstd ourselves.
+ # We currently cannot run these tests because wasm-bindgen-test-runner
+ # does not yet support memory64.
+ run: cargo test --no-run -Z build-std=std,panic_abort --target=wasm64-unknown-unknown --features=js
+
wasi-tests:
name: WASI test
runs-on: ubuntu-latest
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -23,10 +23,10 @@ libc = { version = "0.2.128", default-features = false }
[target.'cfg(target_os = "wasi")'.dependencies]
wasi = { version = "0.11", default-features = false }
-[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
+[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dependencies]
wasm-bindgen = { version = "0.2.62", default-features = false, optional = true }
js-sys = { version = "0.3", optional = true }
-[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies]
+[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dev-dependencies]
wasm-bindgen-test = "0.3.18"
[features]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -34,7 +34,7 @@ wasm-bindgen-test = "0.3.18"
std = []
# Feature to enable fallback RDRAND-based implementation on x86/x86_64
rdrand = []
-# Feature to enable JavaScript bindings on wasm32-unknown-unknown
+# Feature to enable JavaScript bindings on wasm*-unknown-unknown
js = ["wasm-bindgen", "js-sys"]
# Feature to enable custom RNG implementations
custom = []
| This seems reasonable, I wondering if there's any existing implementations to test against? Do Node or any of the Browser runtimes support `wasm64`? | diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -16,6 +16,8 @@ use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
// Size of our temporary Uint8Array buffer used with WebCrypto methods
// Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
const WEB_CRYPTO_BUFFER_SIZE: usize = 256;
+// Node.js's crypto.randomFillSync requires the size to be less than 2**31.
+const NODE_MAX_BUFFER_SIZE: usize = (1 << 31) - 1;
enum RngSource {
Node(NodeCrypto),
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -38,8 +40,10 @@ pub(crate) fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>
// have to ensure the memory in `dest` is initialized.
let dest = uninit_slice_fill_zero(dest);
- if n.random_fill_sync(dest).is_err() {
- return Err(Error::NODE_RANDOM_FILL_SYNC);
+ for chunk in dest.chunks_mut(NODE_MAX_BUFFER_SIZE) {
+ if n.random_fill_sync(chunk).is_err() {
+ return Err(Error::NODE_RANDOM_FILL_SYNC);
+ }
}
}
RngSource::Web(crypto, buf) => {
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -30,7 +30,7 @@
//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`]
//! | Emscripten | `*‑emscripten` | `/dev/urandom` (identical to `/dev/random`)
//! | WASI | `wasm32‑wasi` | [`random_get`]
-//! | Web Browser and Node.js | `wasm32‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js, see [WebAssembly support]
+//! | Web Browser and Node.js | `wasm*‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js, see [WebAssembly support]
//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
//! | Nintendo 3DS | `armv6k-nintendo-3ds` | [`getrandom`][1]
//!
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -262,12 +262,14 @@ cfg_if! {
any(target_arch = "x86_64", target_arch = "x86")))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "js",
- target_arch = "wasm32", target_os = "unknown"))] {
+ any(target_arch = "wasm32", target_arch = "wasm64"),
+ target_os = "unknown"))] {
#[path = "js.rs"] mod imp;
} else if #[cfg(feature = "custom")] {
use custom as imp;
- } else if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
- compile_error!("the wasm32-unknown-unknown target is not supported by \
+ } else if #[cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"),
+ target_os = "unknown"))] {
+ compile_error!("the wasm*-unknown-unknown targets are not supported by \
default, you may need to enable the \"js\" feature. \
For more information see: \
https://docs.rs/getrandom/#webassembly-support");
| 0.2 | 2022-10-22T02:17:40Z | f2d76625d54b2eae398634e055ef143b3c3c1db1 | 303 | Add support for wasm64-unknown-unknown
The Rust 1.64.0 release added wasm64-unknown-unknown as a Tier 3 target. https://github.com/rust-lang/rust/blob/stable/RELEASES.md#compiler-11. Since it is Tier 3, it is non-trivial to build/test for this target. However, we should plan on supporting it. I think the key thing will be to stop assuming all the WebAssembly stuff is necessarily 32-bit.
| rust-random/getrandom | rust-random__getrandom-303 | 2022-10-23T21:57:22Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"256"
] | diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -154,11 +166,14 @@
//! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
//! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc
//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
-//! [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
+//! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size
//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
//! [WebAssembly support]: #webassembly-support
//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
+//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
+//! [CommonJS modules]: https://nodejs.org/api/modules.html
+//! [ES modules]: https://nodejs.org/api/esm.html
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
| We have run into a bunch of issues like this before (see #214 #224 #234). If you (or anyone else) have an improvement for our code, we would be happy to accept a PR. The current logic for selecting the implementation is here: https://github.com/rust-random/getrandom/blob/9e2c896e653611188df9d835d2570546e2bf1d67/src/js.rs#L59
We have CI tests that make sure our code works w/ Web and NodeJS, so I'm confused as to why you are having issues. The code you have above will only be run in a Node environment. That function will not be called if you are running on a web browser.
Oh wait I think this issue was fixed in #234 as the generated JS bindings should now look like:
```
getObject(arg0).require(getStringFromWasm0(arg1, arg2))
```
not
```
module.require(getStringFromWasm0(arg0, arg1))
```
Can you make sure you are using the latest version of `getrandom` and see if your issue still persists?
> We have CI tests that make sure our code works w/ Web and NodeJS, so I'm confused as to why you are having issues.
The code works in web and nodejs, so long as I compile separate wasm modules for each context. And thus, publish separate npm packages for the web and for nodejs. But I hate that - javascript code works on the web and nodejs (thats kind of the whole point of nodejs). Ideally I'd like to be able to just compile my wasm code once and run it in both a nodejs and web context.
And I *almost* can do that - but I just can't get getrandom to work in both contexts. I'm not sure what the right answer is here from a library design perspective.
The current steps I'm taking:
lib.rs:
```rust
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn foo() -> u32 {
console_error_panic_hook::set_once();
let mut bytes = [0; 4];
getrandom::getrandom(&mut bytes[..]).expect("getrandom failed");
u32::from_be_bytes(bytes)
}
```
Then:
```
wasm-pack build --dev --target web
```
Unfortunately I need to add `"type": "module"` into the generated package.json. Once I've done that I can load the wasm module from nodejs in a kinda manual, hacky way:
foo.mjs:
```javascript
import {default as init} from "./pkg/rand_wasm.js"
import {readFileSync} from 'fs'
;(async () => {
let bytes = readFileSync("pkg/rand_wasm_bg.wasm")
let module = await init(bytes)
console.log(module.foo())
})()
```
All my rust code runs fine - but the getrandom call fails:
```
$ node foo.mjs
panicked at 'getrandom failed: Error { internal_code: 2147483660, description: "Node.js crypto module is unavailable" }', src/lib.rs:8:42
(stack follows...)
```
The reason is that the [nodejs codepath](https://github.com/rust-random/getrandom/blob/9e2c896e653611188df9d835d2570546e2bf1d67/src/js.rs#L62-L64) is trying to use `require()`, which is unavailable when using es modules.
For now I've given up, and I'm just compiling my wasm module twice (once for node, once for the web). But ideally I'd like to get this fixed. Having a single wasm module which works everywhere would be lovely.
Any ideas on how we can make this work?
Maybe in the long term I could target WASI instead, which provides an [API for random](https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---result-errno). Thats probably a long ways out though :/
Another approach is to detect nodejs then use a dynamic import if we're in ESM mode -
```javascript
let crypto = await import('node:crypto').webcrypto
crypto.getRandomValues(buffer)
```
... But dynamic imports return a promise, and thats really hard to cope with. :/
A cheap workaround is to add this to the end of the generated bindings file:
```ts
// workaround for https://github.com/rust-random/getrandom/issues/256
import * as crypto from "crypto"
const module = {
require: (string) => {
if(string !== "crypto") throw new Error("Unexpected require " + string)
return crypto
}
}
```
So it seems like we cannot support both ES6 modules running on Node.js and `wasm_bindgen`'s `--target nodejs` which uses CommonJS modules. I'll try to get some concrete code examples together this week/weekend.
Basically, as the object returned by `import()` is a `Promise` and we have no way to "run" this Promise, we can't actually use `import()` as a function call. We can [convert between Promises and Futures](https://rustwasm.github.io/wasm-bindgen/reference/js-promises-and-rust-futures.html)
but there's not a way to execute them. We could get around this by using [top-level `await`](https://github.com/tc39/proposal-top-level-await) but that doesn't work with CommonJS. This would also mean losing support for many older environments which currently work.
So _if_ we want to support this use-case, we would have to add an additional `js_modules` Cargo feature that:
- Allows `getrandom` use features exclusive to ES6 modules
- Node.js + ES6 now works
- Makes `getrandom` no longer work in older JS environments
- Makes `getrandom` incompatible with `wasm_bindgen`'s `--target nodejs` and `--target no-modules`
- Only `--target web` and `--target bundler` would be supported
> The code works in web and nodejs, so long as I compile separate wasm modules for each context. And thus, publish separate npm packages for the web and for nodejs. But I hate that - javascript code works on the web and nodejs (thats kind of the whole point of nodejs). Ideally I'd like to be able to just compile my wasm code once and run it in both a nodejs and web context.
The main issue here is that Node and the Web really are different targets, even if they are superficially similar. We've had a ton of issues targeting Node.js in general (targeting the Web has been bad but not _as bad_). This library attempts to support every Rust target possible, and Node.js has _easily_ has the highest maintenance cost, due to:
- A lower level of support in `wasm_bindgen`
- The fractured module ecosystem (CommonJS modules vs ES6 modules vs whatever was before ES6)
- `global.foo` and `foo` not being being the same (or one will exist and the other will not)
- We need to _conditionally_ import a Node.js library (unlike the Web which needs no library imports)
- Node.js conditional import story is half-backed:
- CommonJS `require()` is only synchronous
- ES6 `import()` is only asynchronous
- Node.js's only ES6-compatible way to do blocking imports requires [importing another Node.js specific library](https://nodejs.org/api/module.html#modulecreaterequirefilename), making this "solution" circular.
I've had a bit of a think about it, and I want to suggest another approach:
So right now, the logic is something like this:
```javascript
if (process.versions.node != null) {
require('crypto').randomFillSync(...)
} else {
globalThis.crypto.getRandomValues(...)
}
```
There are essentially 3 different environments:
1. Nodejs in commonjs mode (supported)
2. Nodejs in esm mode (unsupported - require is not available)
3. Web browsers in any mode (supported)
If we invert the logic to do capability detection instead, it would look like this:
```javascript
if (globalThis.crypto.getRandomValues != null) {
globalThis.crypto.getRandomValues(...)
} else if (globalThis.require != null) { // Or keep the existing check for process.version.node
require('crypto').randomFillSync(...)
}
```
Then I could make my code work with a simple shim:
```javascript
import {webcrypto} from 'crypto' // only available from node 16+, but thats not a problem for me.
globalThis.crypto = webcrypto
// ...
wasm.init()
```
This would also work in deno, and any other javascript context which follows web standards. And if nodejs ever implements the web's JS crypto standard, everything will just work. | diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -43,16 +43,19 @@ impl Error {
pub const FAILED_RDRAND: Error = internal_error(5);
/// RDRAND instruction unsupported on this target.
pub const NO_RDRAND: Error = internal_error(6);
- /// The browser does not have support for `self.crypto`.
+ /// The environment does not support the Web Crypto API.
pub const WEB_CRYPTO: Error = internal_error(7);
- /// The browser does not have support for `crypto.getRandomValues`.
+ /// Calling Web Crypto API `crypto.getRandomValues` failed.
pub const WEB_GET_RANDOM_VALUES: Error = internal_error(8);
/// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized).
pub const VXWORKS_RAND_SECURE: Error = internal_error(11);
- /// NodeJS does not have support for the `crypto` module.
+ /// Node.js does not have the `crypto` CommonJS module.
pub const NODE_CRYPTO: Error = internal_error(12);
- /// NodeJS does not have support for `crypto.randomFillSync`.
+ /// Calling Node.js function `crypto.randomFillSync` failed.
pub const NODE_RANDOM_FILL_SYNC: Error = internal_error(13);
+ /// Called from an ES module on Node.js. This is unsupported, see:
+ /// <https://docs.rs/getrandom#nodejs-es-module-support>.
+ pub const NODE_ES_MODULE: Error = internal_error(14);
/// Codes below this point represent OS Errors (i.e. positive i32 values).
/// Codes at or above this point, but below [`Error::CUSTOM_START`] are
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -166,10 +169,11 @@ fn internal_desc(error: Error) -> Option<&'static str> {
Error::FAILED_RDRAND => Some("RDRAND: failed multiple times: CPU issue likely"),
Error::NO_RDRAND => Some("RDRAND: instruction not supported"),
Error::WEB_CRYPTO => Some("Web Crypto API is unavailable"),
- Error::WEB_GET_RANDOM_VALUES => Some("Web API crypto.getRandomValues is unavailable"),
+ Error::WEB_GET_RANDOM_VALUES => Some("Calling Web API crypto.getRandomValues failed"),
Error::VXWORKS_RAND_SECURE => Some("randSecure: VxWorks RNG module is not initialized"),
- Error::NODE_CRYPTO => Some("Node.js crypto module is unavailable"),
- Error::NODE_RANDOM_FILL_SYNC => Some("Node.js API crypto.randomFillSync is unavailable"),
+ Error::NODE_CRYPTO => Some("Node.js crypto CommonJS module is unavailable"),
+ Error::NODE_RANDOM_FILL_SYNC => Some("Calling Node.js API crypto.randomFillSync failed"),
+ Error::NODE_ES_MODULE => Some("Node.js ES modules are not directly supported, see https://docs.rs/getrandom#nodejs-es-module-support"),
_ => None,
}
}
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -10,15 +10,16 @@ use crate::Error;
extern crate std;
use std::thread_local;
-use js_sys::{global, Uint8Array};
+use js_sys::{global, Function, Uint8Array};
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
+// Size of our temporary Uint8Array buffer used with WebCrypto methods
// Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
-const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256;
+const WEB_CRYPTO_BUFFER_SIZE: usize = 256;
enum RngSource {
Node(NodeCrypto),
- Browser(BrowserCrypto, Uint8Array),
+ Web(WebCrypto, Uint8Array),
}
// JsValues are always per-thread, so we initialize RngSource for each thread.
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -37,10 +38,10 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
return Err(Error::NODE_RANDOM_FILL_SYNC);
}
}
- RngSource::Browser(crypto, buf) => {
+ RngSource::Web(crypto, buf) => {
// getRandomValues does not work with all types of WASM memory,
// so we initially write to browser memory to avoid exceptions.
- for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) {
+ for chunk in dest.chunks_mut(WEB_CRYPTO_BUFFER_SIZE) {
// The chunk can be smaller than buf's length, so we call to
// JS to create a smaller view of buf without allocation.
let sub_buf = buf.subarray(0, chunk.len() as u32);
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -58,25 +59,33 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
fn getrandom_init() -> Result<RngSource, Error> {
let global: Global = global().unchecked_into();
- if is_node(&global) {
- let crypto = NODE_MODULE
- .require("crypto")
- .map_err(|_| Error::NODE_CRYPTO)?;
- return Ok(RngSource::Node(crypto));
- }
- // Assume we are in some Web environment (browser or web worker). We get
- // `self.crypto` (called `msCrypto` on IE), so we can call
- // `crypto.getRandomValues`. If `crypto` isn't defined, we assume that
- // we are in an older web browser and the OS RNG isn't available.
- let crypto = match (global.crypto(), global.ms_crypto()) {
- (c, _) if c.is_object() => c,
- (_, c) if c.is_object() => c,
- _ => return Err(Error::WEB_CRYPTO),
+ // Get the Web Crypto interface if we are in a browser, Web Worker, Deno,
+ // or another environment that supports the Web Cryptography API. This
+ // also allows for user-provided polyfills in unsupported environments.
+ let crypto = match global.crypto() {
+ // Standard Web Crypto interface
+ c if c.is_object() => c,
+ // Node.js CommonJS Crypto module
+ _ if is_node(&global) => {
+ // If module.require isn't a valid function, we are in an ES module.
+ match Module::require_fn().and_then(JsCast::dyn_into::<Function>) {
+ Ok(require_fn) => match require_fn.call1(&global, &JsValue::from_str("crypto")) {
+ Ok(n) => return Ok(RngSource::Node(n.unchecked_into())),
+ Err(_) => return Err(Error::NODE_CRYPTO),
+ },
+ Err(_) => return Err(Error::NODE_ES_MODULE),
+ }
+ }
+ // IE 11 Workaround
+ _ => match global.ms_crypto() {
+ c if c.is_object() => c,
+ _ => return Err(Error::WEB_CRYPTO),
+ },
};
- let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
- Ok(RngSource::Browser(crypto, buf))
+ let buf = Uint8Array::new_with_length(WEB_CRYPTO_BUFFER_SIZE as u32);
+ Ok(RngSource::Web(crypto, buf))
}
// Taken from https://www.npmjs.com/package/browser-or-node
diff --git a/src/js.rs b/src/js.rs
--- a/src/js.rs
+++ b/src/js.rs
@@ -93,30 +102,36 @@ fn is_node(global: &Global) -> bool {
#[wasm_bindgen]
extern "C" {
- type Global; // Return type of js_sys::global()
+ // Return type of js_sys::global()
+ type Global;
- // Web Crypto API (https://www.w3.org/TR/WebCryptoAPI/)
- #[wasm_bindgen(method, getter, js_name = "msCrypto")]
- fn ms_crypto(this: &Global) -> BrowserCrypto;
+ // Web Crypto API: Crypto interface (https://www.w3.org/TR/WebCryptoAPI/)
+ type WebCrypto;
+ // Getters for the WebCrypto API
#[wasm_bindgen(method, getter)]
- fn crypto(this: &Global) -> BrowserCrypto;
- type BrowserCrypto;
+ fn crypto(this: &Global) -> WebCrypto;
+ #[wasm_bindgen(method, getter, js_name = msCrypto)]
+ fn ms_crypto(this: &Global) -> WebCrypto;
+ // Crypto.getRandomValues()
#[wasm_bindgen(method, js_name = getRandomValues, catch)]
- fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
+ fn get_random_values(this: &WebCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
- // We use a "module" object here instead of just annotating require() with
- // js_name = "module.require", so that Webpack doesn't give a warning. See:
- // https://github.com/rust-random/getrandom/issues/224
- type NodeModule;
- #[wasm_bindgen(js_name = module)]
- static NODE_MODULE: NodeModule;
// Node JS crypto module (https://nodejs.org/api/crypto.html)
- #[wasm_bindgen(method, catch)]
- fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
type NodeCrypto;
+ // crypto.randomFillSync()
#[wasm_bindgen(method, js_name = randomFillSync, catch)]
fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
+ // Ideally, we would just use `fn require(s: &str)` here. However, doing
+ // this causes a Webpack warning. So we instead return the function itself
+ // and manually invoke it using call1. This also lets us to check that the
+ // function actually exists, allowing for better error messages. See:
+ // https://github.com/rust-random/getrandom/issues/224
+ // https://github.com/rust-random/getrandom/issues/256
+ type Module;
+ #[wasm_bindgen(getter, static_method_of = Module, js_class = module, js_name = require, catch)]
+ fn require_fn() -> Result<JsValue, JsValue>;
+
// Node JS process Object (https://nodejs.org/api/process.html)
#[wasm_bindgen(method, getter)]
fn process(this: &Global) -> Process;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -31,7 +31,7 @@
//! | Emscripten | `*‑emscripten` | `/dev/random` (identical to `/dev/urandom`)
//! | WASI | `wasm32‑wasi` | [`random_get`]
//! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues`], see [WebAssembly support]
-//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`], see [WebAssembly support]
+//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomFillSync`], see [WebAssembly support]
//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
//! | Nintendo 3DS | `armv6k-nintendo-3ds` | [`getrandom`][1]
//!
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -91,6 +91,18 @@
//!
//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
//!
+//! #### Node.js ES module support
+//!
+//! Node.js supports both [CommonJS modules] and [ES modules]. Due to
+//! limitations in wasm-bindgen's [`module`] support, we cannot directly
+//! support ES Modules running on Node.js. However, on Node v15 and later, the
+//! module author can add a simple shim to support the Web Cryptography API:
+//! ```js
+//! import { webcrypto } from 'node:crypto'
+//! globalThis.crypto = webcrypto
+//! ```
+//! This crate will then use the provided `webcrypto` implementation.
+//!
//! ### Custom implementations
//!
//! The [`register_custom_getrandom!`] macro allows a user to mark their own
| 0.2 | 2022-09-13T07:16:02Z | d3aa089bbdefa95da9130b7c633e1f49687f04ce | 284 | Javascript code does not work in ESM context
Currently wasm-pack has two common build options:
- `nodejs` produces a commonjs module for node
- `web` produces an es6 module for the web
I'd like to use the same wasm module (published in npm) isomorphically for both nodejs and the web. It almost works - but unfortunately getrandom (run from nodejs) doesn't work at all in an es6 context. It produces this code in a esm file:
```
imports.wbg.__wbg_modulerequire_0a83c0c31d12d2c7 = function() { return handleError(function (arg0, arg1) {
var ret = module.require(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
}, arguments) };
```
... Which errors, because `module` is not defined in this context.
I'm not sure how getrandom should work around this. Any thoughts?
| rust-random/getrandom | rust-random__getrandom-284 | 2022-10-19T21:07:18Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
[
"277"
] | diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -154,6 +153,7 @@
//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
//! [WebAssembly support]: #webassembly-support
+//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
# using the
-//! [wasm-bindgen](https://github.com/rust-lang/rust-bindgen) toolchain.
+//! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain.
//!
//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
//!
| 0.2 | 2022-08-18T02:01:56Z | 9a64857ae616b57d7b703706fed2f067153a5212 | 278 | Wrong link in the docs links to rust-bindgen instead of wasm-bindgen
The [WebAssemmbely](https://docs.rs/getrandom/latest/getrandom/#webassembly-support) docs section seems want to link to [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen), but links to [rust-bindgen](https://github.com/rust-lang/rust-bindgen) instead.
I assume this is an error right? I also noticed the issue https://github.com/rust-random/getrandom/issues/267, which could be fixed at the same time as this one when the documentation is updated.
| rust-random/getrandom | rust-random__getrandom-278 | 2022-08-19T01:58:35Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 | |
[
"181"
] | diff --git a/.cargo/config b/.cargo/config
--- a/.cargo/config
+++ b/.cargo/config
@@ -1,5 +1,5 @@
+# Allow normal use of "cargo run" and "cargo test" on these wasm32 platforms.
[target.wasm32-unknown-unknown]
runner = 'wasm-bindgen-test-runner'
-
[target.wasm32-wasi]
runner = 'wasmtime'
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -14,36 +14,47 @@ env:
jobs:
check-doc:
- name: Doc deadlinks
+ name: Docs, deadlinks, minimal dependencies
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- - name: Install toolchain
- uses: actions-rs/toolchain@v1
+ - uses: actions-rs/toolchain@v1
with:
profile: minimal
- toolchain: nightly
+ toolchain: nightly # Needed for -Z minimal-versions
override: true
- - run: cargo install cargo-deadlinks
- - run: cargo deadlinks -- --features custom
+ - name: Install precompiled cargo-deadlinks
+ run: |
+ export URL=$(curl -s https://api.github.com/repos/deadlinks/cargo-deadlinks/releases/latest | jq -r '.assets[] | select(.name | contains("cargo-deadlinks-linux")) | .browser_download_url')
+ wget -O /tmp/cargo-deadlinks $URL
+ chmod +x /tmp/cargo-deadlinks
+ mv /tmp/cargo-deadlinks ~/.cargo/bin
+ - run: cargo deadlinks -- --features=custom,std
+ - run: |
+ cargo generate-lockfile -Z minimal-versions
+ cargo test --features=custom,std
main-tests:
name: Main tests
runs-on: ${{ matrix.os }}
strategy:
matrix:
- os: [ubuntu-latest, macos-latest, windows-latest]
+ os: [ubuntu-latest, windows-latest]
toolchain: [nightly, beta, stable, 1.34]
+ # Only Test macOS on stable to reduce macOS CI jobs
+ include:
+ - os: macos-latest
+ toolchain: stable
steps:
- uses: actions/checkout@v2
- - name: Install toolchain
- uses: actions-rs/toolchain@v1
+ - uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.toolchain }}
override: true
- run: cargo test
- - run: cargo test --features std
+ - run: cargo test --features=std
+ - run: cargo test --features=custom # custom should do nothing here
- if: ${{ matrix.toolchain == 'nightly' }}
run: cargo build --benches
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -59,18 +70,40 @@ jobs:
]
steps:
- uses: actions/checkout@v2
- - name: Install toolchain
- uses: actions-rs/toolchain@v1
+ - uses: actions-rs/toolchain@v1
with:
profile: minimal
target: ${{ matrix.target }}
toolchain: stable
- override: true
- # update is needed to fix the 404 error on install, see:
- # https://github.com/actions/virtual-environments/issues/675
- - run: sudo apt-get update
- - run: sudo apt-get install gcc-multilib
- - run: cargo test --target ${{ matrix.target }}
+ - name: Install multilib
+ # update is needed to fix the 404 error on install, see:
+ # https://github.com/actions/virtual-environments/issues/675
+ run: |
+ sudo apt-get update
+ sudo apt-get install gcc-multilib
+ - run: cargo test --target=${{ matrix.target }} --features=std
+
+ # We can only Build/Link on these targets for now.
+ # TODO: Run the iOS binaries in the simulator
+ # TODO: build/run aarch64-apple-darwin binaries on a x86_64 Mac
+ apple-tests:
+ name: Additional Apple targets
+ runs-on: macos-latest
+ strategy:
+ matrix:
+ target: [
+ aarch64-apple-ios,
+ x86_64-apple-ios,
+ ]
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ target: ${{ matrix.target }}
+ toolchain: stable
+ - name: Build Tests
+ run: cargo test --no-run --target=${{ matrix.target }} --features=std
windows-tests:
name: Additional Windows targets
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -90,63 +123,131 @@ jobs:
profile: minimal
toolchain: ${{ matrix.toolchain }}
override: true
- - run: cargo test
+ - run: cargo test --features=std
+ # TODO: Add emscripten when it's working with Cross
cross-tests:
- name: Cross tests
- runs-on: ${{ matrix.os }}
+ name: Cross Test
+ runs-on: ubuntu-latest
strategy:
matrix:
- include:
- - os: ubuntu-latest
- target: mips-unknown-linux-gnu
- toolchain: stable
+ target: [
+ aarch64-unknown-linux-gnu,
+ aarch64-linux-android,
+ mips-unknown-linux-gnu,
+ ]
steps:
- uses: actions/checkout@v2
- - name: Install toolchain
- uses: actions-rs/toolchain@v1
+ - uses: actions-rs/toolchain@v1
with:
profile: minimal
target: ${{ matrix.target }}
- toolchain: ${{ matrix.toolchain }}
- override: true
- - name: Cache cargo plugins
- uses: actions/cache@v1
- with:
- path: ~/.cargo/bin/
- key: ${{ runner.os }}-cargo-plugins
- - name: Install cross
- run: cargo install cross || true
+ toolchain: stable
+ - name: Install precompiled cross
+ run: |
+ export URL=$(curl -s https://api.github.com/repos/rust-embedded/cross/releases/latest | jq -r '.assets[] | select(.name | contains("x86_64-unknown-linux-gnu.tar.gz")) | .browser_download_url')
+ wget -O /tmp/binaries.tar.gz $URL
+ tar -C /tmp -xzf /tmp/binaries.tar.gz
+ mv /tmp/cross ~/.cargo/bin
- name: Test
- run: cross test --no-fail-fast --target ${{ matrix.target }}
+ run: cross test --no-fail-fast --target=${{ matrix.target }} --features=std
- build:
- name: Build-only
+ cross-link:
+ name: Cross Build/Link
runs-on: ubuntu-latest
strategy:
matrix:
target: [
x86_64-sun-solaris,
+ x86_64-unknown-netbsd,
+ ]
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ target: ${{ matrix.target }}
+ toolchain: stable
+ - name: Install precompiled cross
+ run: |
+ export URL=$(curl -s https://api.github.com/repos/rust-embedded/cross/releases/latest | jq -r '.assets[] | select(.name | contains("x86_64-unknown-linux-gnu.tar.gz")) | .browser_download_url')
+ wget -O /tmp/binaries.tar.gz $URL
+ tar -C /tmp -xzf /tmp/binaries.tar.gz
+ mv /tmp/cross ~/.cargo/bin
+ - name: Build Tests
+ run: cross test --no-run --target=${{ matrix.target }} --features=std
+
+ web-tests:
+ name: Web tests
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ target: wasm32-unknown-unknown
+ toolchain: stable
+ - name: Install precompiled wasm-bindgen-test-runner
+ run: |
+ export VERSION=$(cargo metadata --format-version=1 | jq -r '.packages[] | select ( .name == "wasm-bindgen" ) | .version')
+ wget -O /tmp/binaries.tar.gz https://github.com/rustwasm/wasm-bindgen/releases/download/$VERSION/wasm-bindgen-$VERSION-x86_64-unknown-linux-musl.tar.gz
+ tar -C /tmp -xzf /tmp/binaries.tar.gz --strip-components=1
+ mv /tmp/wasm-bindgen-test-runner ~/.cargo/bin
+ - name: Test (Node)
+ run: cargo test --target=wasm32-unknown-unknown --features=js
+ - name: Test (Firefox)
+ env:
+ GECKODRIVER: /usr/bin/geckodriver
+ run: cargo test --target=wasm32-unknown-unknown --features=js,test-in-browser
+ - name: Test (Chrome)
+ env:
+ CHROMEDRIVER: /usr/bin/chromedriver
+ run: cargo test --target=wasm32-unknown-unknown --features=js,test-in-browser
+ - name: Build Tests (with custom, without JS)
+ run: cargo test --no-run --target=wasm32-unknown-unknown --features=custom
+
+ wasi-tests:
+ name: WASI test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ target: wasm32-wasi
+ toolchain: stable
+ - name: Install precompiled wasmtime
+ run: |
+ export URL=$(curl -s https://api.github.com/repos/bytecodealliance/wasmtime/releases/latest | jq -r '.assets[] | select(.name | contains("x86_64-linux.tar.xz")) | .browser_download_url')
+ wget -O /tmp/binaries.tar.xz $URL
+ tar -C /tmp -xf /tmp/binaries.tar.xz --strip-components=1
+ mv /tmp/wasmtime ~/.cargo/bin
+ - run: cargo test --target wasm32-wasi
+
+ build:
+ name: Build only
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ target: [
x86_64-unknown-freebsd,
x86_64-fuchsia,
- x86_64-unknown-netbsd,
x86_64-unknown-redox,
x86_64-fortanix-unknown-sgx,
]
steps:
- uses: actions/checkout@v2
- - name: Install toolchain
- uses: actions-rs/toolchain@v1
+ - uses: actions-rs/toolchain@v1
with:
profile: minimal
target: ${{ matrix.target }}
- toolchain: nightly
+ toolchain: nightly # Required to build libc for Redox
override: true
- name: Build
- run: cargo build --target ${{ matrix.target }}
+ run: cargo build --target=${{ matrix.target }} --features=std
- build-rdrand:
- name: Build-only RDRAND
+ build-std:
+ name: Build-only (build-std)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -154,24 +255,17 @@ jobs:
uses: actions-rs/toolchain@v1
with:
profile: minimal
- toolchain: nightly
+ toolchain: nightly # Required to build libcore
components: rust-src
override: true
- - name: Cache cargo plugins
- uses: actions/cache@v1
- with:
- path: ~/.cargo/bin/
- key: ${{ runner.os }}-cargo-plugins
- - name: Install xbuild
- run: cargo install cargo-xbuild || true
- - name: UEFI
- run: cargo xbuild --features=rdrand --target x86_64-unknown-uefi
- - name: Hermit
- run: cargo xbuild --features=rdrand --target x86_64-unknown-hermit
- - name: L4Re
- run: cargo xbuild --features=rdrand --target x86_64-unknown-l4re-uclibc
+ - name: UEFI (RDRAND)
+ run: cargo build -Z build-std=core --features=rdrand --target=x86_64-unknown-uefi
+ - name: Hermit (RDRAND)
+ run: cargo build -Z build-std=core --features=rdrand --target=x86_64-unknown-hermit
+ - name: L4Re (RDRAND)
+ run: cargo build -Z build-std=core --features=rdrand --target=x86_64-unknown-l4re-uclibc
- name: VxWorks
- run: cargo xbuild --features=rdrand --target x86_64-wrs-vxworks
+ run: cargo build -Z build-std=core --target=x86_64-wrs-vxworks
clippy-fmt:
name: Clippy + rustfmt
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -181,9 +275,12 @@ jobs:
- uses: actions-rs/toolchain@v1
with:
profile: minimal
- toolchain: stable
+ # https://github.com/rust-lang/rust-clippy/pull/6379 added MSRV
+ # support, so we need to use nightly until this is on stable.
+ toolchain: nightly
components: rustfmt, clippy
+ override: true
- name: clippy
- run: cargo clippy --all
+ run: cargo clippy --all --features=custom,std
- name: fmt
run: cargo fmt --all -- --check
| With the stdweb support removed in #178, this should now be easier to get working. The best approach might be to have a Dockerfile containing the Node/Firefox/Chromium deps, so that we can keep all of those ordered in a single place. | diff --git /dev/null b/.clippy.toml
new file mode 100644
--- /dev/null
+++ b/.clippy.toml
@@ -0,0 +1,1 @@
+msrv = "1.34"
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -146,8 +146,6 @@
)]
#![no_std]
#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
-// `matches!` macro was added only in Rust 1.42, which is bigger than our MSRV
-#![allow(clippy::match_like_matches_macro)]
#[macro_use]
extern crate cfg_if;
| 0.2 | 2021-01-03T05:40:59Z | 6c94834850c94810f757658255c7e437db84cc44 | 192 | Add CI for WASM targets
In #180 we have migrated to GitHub Actions almost all tests except related to WASM and Emscripten.
[Old Travis config](https://github.com/rust-random/getrandom/blob/2d899940a2a4968f81b3e715deef1a6d47cf5801/.travis.yml#L37-L97)
| rust-random/getrandom | rust-random__getrandom-192 | 2021-01-04T06:05:18Z | 5e62ce9fadb401539a08b329e4cbd98cc6393f60 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.