| 1 |
//! Implementation for WASIp2 and WASIp3. |
| 2 |
use crate::Error; |
| 3 |
use core::{mem::MaybeUninit, ptr::copy_nonoverlapping}; |
| 4 |
|
| 5 |
#[cfg(not(target_env = "p2"))] |
| 6 |
#[cfg(not(target_env = "p3"))] |
| 7 |
compile_error!("Unknown version of WASI (only previews 1, 2 and 3 are supported)"); |
| 8 |
|
| 9 |
// Use manual bindings instead of `wasip2/3` crates to prevent Cargo.lock bloat. |
| 10 |
// |
| 11 |
// Technically, such manual bindings may not work since we also have to provide |
| 12 |
// type information which is expected by `wasm-component-ld`, but we assume that |
| 13 |
// in practice the relevant type information will be provided by linking to `std` |
| 14 |
// and/or `wasip2/3` crate. |
| 15 |
// |
| 16 |
// See https://github.com/rust-random/getrandom/pull/828 for more information. |
| 17 |
#[cfg_attr( |
| 18 |
target_env = "p2", |
| 19 |
link(wasm_import_module = "wasi:random/[email protected]") |
| 20 |
)] |
| 21 |
// TODO(MSRV-1.92): Use `target_env = "p3"` |
| 22 |
#[cfg_attr( |
| 23 |
not(target_env = "p2"), |
| 24 |
link(wasm_import_module = "wasi:random/[email protected]") |
| 25 |
)] |
| 26 |
unsafe extern "C" { |
| 27 |
#[link_name = "get-random-u64"] |
| 28 |
safe fn get_random_u64() -> u64; |
| 29 |
} |
| 30 |
|
| 31 |
#[inline] |
| 32 |
pub fn inner_u32() -> Result<u32, Error> { |
| 33 |
let val = get_random_u64(); |
| 34 |
Ok(crate::util::truncate(val)) |
| 35 |
} |
| 36 |
|
| 37 |
#[inline] |
| 38 |
pub fn inner_u64() -> Result<u64, Error> { |
| 39 |
Ok(get_random_u64()) |
| 40 |
} |
| 41 |
|
| 42 |
#[inline] |
| 43 |
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
| 44 |
let (prefix, chunks, suffix) = unsafe { dest.align_to_mut::<MaybeUninit<u64>>() }; |
| 45 |
|
| 46 |
// We use `get_random_u64` instead of `get_random_bytes` because the latter creates |
| 47 |
// an allocation due to the Wit IDL [restrictions][0]. This should be fine since |
| 48 |
// the main use case of `getrandom` is seed generation. |
| 49 |
// |
| 50 |
// [0]: https://github.com/WebAssembly/wasi-random/issues/27 |
| 51 |
if !prefix.is_empty() { |
| 52 |
let val = get_random_u64(); |
| 53 |
let src = (&val as *const u64).cast(); |
| 54 |
unsafe { |
| 55 |
copy_nonoverlapping(src, prefix.as_mut_ptr(), prefix.len()); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
for dst in chunks { |
| 60 |
dst.write(get_random_u64()); |
| 61 |
} |
| 62 |
|
| 63 |
if !suffix.is_empty() { |
| 64 |
let val = get_random_u64(); |
| 65 |
let src = (&val as *const u64).cast(); |
| 66 |
unsafe { |
| 67 |
copy_nonoverlapping(src, suffix.as_mut_ptr(), suffix.len()); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
Ok(()) |
| 72 |
} |