Skip to content

Commit 7c83ea0

Browse files
authored
Hermit: use sys_read_entropy syscall (rust-random#333)
* Hermit: use sys_read_entropy syscall * Add doc link
1 parent c65522b commit 7c83ea0

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/hermit.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
use crate::Error;
2+
use core::{cmp::min, mem::MaybeUninit, num::NonZeroU32};
3+
4+
extern "C" {
5+
fn sys_read_entropy(buffer: *mut u8, length: usize, flags: u32) -> isize;
6+
}
7+
8+
pub fn getrandom_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
9+
while !dest.is_empty() {
10+
let res = unsafe { sys_read_entropy(dest.as_mut_ptr() as *mut u8, dest.len(), 0) };
11+
if res < 0 {
12+
// SAFETY: all Hermit error codes use i32 under the hood:
13+
// https://github.com/hermitcore/libhermit-rs/blob/master/src/errno.rs
14+
let code = unsafe { NonZeroU32::new_unchecked((-res) as u32) };
15+
return Err(code.into());
16+
}
17+
let len = min(res as usize, dest.len());
18+
dest = &mut dest[len..];
19+
}
20+
Ok(())
21+
}

src/lib.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
2525
//! | Redox | `*‑redox` | `/dev/urandom`
2626
//! | Haiku | `*‑haiku` | `/dev/urandom` (identical to `/dev/random`)
27-
//! | Hermit | `x86_64-*-hermit` | [`RDRAND`]
27+
//! | Hermit | `*-hermit` | [`sys_read_entropy`]
2828
//! | SGX | `x86_64‑*‑sgx` | [`RDRAND`]
2929
//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
3030
//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`]
@@ -179,6 +179,7 @@
179179
//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
180180
//! [CommonJS modules]: https://nodejs.org/api/modules.html
181181
//! [ES modules]: https://nodejs.org/api/esm.html
182+
//! [`sys_read_entropy`]: https://hermitcore.github.io/libhermit-rs/hermit/fn.sys_read_entropy.html
182183
183184
#![doc(
184185
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
@@ -245,8 +246,8 @@ cfg_if! {
245246
#[path = "openbsd.rs"] mod imp;
246247
} else if #[cfg(all(target_arch = "wasm32", target_os = "wasi"))] {
247248
#[path = "wasi.rs"] mod imp;
248-
} else if #[cfg(all(target_arch = "x86_64", target_os = "hermit"))] {
249-
#[path = "rdrand.rs"] mod imp;
249+
} else if #[cfg(target_os = "hermit")] {
250+
#[path = "hermit.rs"] mod imp;
250251
} else if #[cfg(target_os = "vxworks")] {
251252
mod util_libc;
252253
#[path = "vxworks.rs"] mod imp;

0 commit comments

Comments
 (0)