From 79023b81392bf20569b1c32e72eb158c1202d04d Mon Sep 17 00:00:00 2001 From: Ed Schouten Date: Sun, 7 Jan 2018 16:35:17 +0100 Subject: [PATCH] Port rand to CloudABI. CloudABI has a special system call, random_get(), that can be used to obtain random data from the environment (the kernel, emulator, etc). We can invoke this system call by making use of the cloudabi crate. --- Cargo.toml | 3 +++ src/os.rs | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9551aadcf48..01f3270e976 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,5 +31,8 @@ winapi = { version = "0.3", features = ["minwindef", "ntsecapi", "profileapi", " [workspace] members = ["rand-derive"] +[target.'cfg(target_os = "cloudabi")'.dependencies] +cloudabi = "0.0.3" + [target.'cfg(target_os = "fuchsia")'.dependencies] fuchsia-zircon = "0.3.2" diff --git a/src/os.rs b/src/os.rs index 248e980acb9..b9253552226 100644 --- a/src/os.rs +++ b/src/os.rs @@ -115,10 +115,12 @@ impl ReadRng { } } -#[cfg(all(unix, not(target_os = "ios"), - not(target_os = "nacl"), +#[cfg(all(unix, + not(target_os = "cloudabi"), not(target_os = "freebsd"), not(target_os = "fuchsia"), + not(target_os = "ios"), + not(target_os = "nacl"), not(target_os = "openbsd"), not(target_os = "redox")))] mod imp { @@ -267,6 +269,33 @@ mod imp { } } +#[cfg(target_os = "cloudabi")] +mod imp { + extern crate cloudabi; + + use {Error, ErrorKind}; + + #[derive(Debug)] + pub struct OsRng; + + impl OsRng { + pub fn new() -> Result { + Ok(OsRng) + } + + pub fn try_fill_bytes(&mut self, v: &mut [u8]) -> Result<(), Error> { + if unsafe { cloudabi::random_get(v) } == cloudabi::errno::SUCCESS { + Ok(()) + } else { + Err(Error::new( + ErrorKind::Unavailable, + "random_get() system call failed", + )) + } + } + } +} + #[cfg(target_os = "ios")] mod imp { extern crate libc;