| 1 |
//! Implementation for WASI Preview 1 |
| 2 |
use crate::Error; |
| 3 |
use core::mem::MaybeUninit; |
| 4 |
|
| 5 |
pub use crate::util::{inner_u32, inner_u64}; |
| 6 |
|
| 7 |
// This linking is vendored from the wasi crate: |
| 8 |
// https://docs.rs/wasi/0.11.0+wasi-snapshot-preview1/src/wasi/lib_generated.rs.html#2344-2350 |
| 9 |
#[link(wasm_import_module = "wasi_snapshot_preview1")] |
| 10 |
extern "C" { |
| 11 |
fn random_get(arg0: i32, arg1: i32) -> i32; |
| 12 |
} |
| 13 |
|
| 14 |
/// WASI p1 uses `u16` for error codes in its witx definitions: |
| 15 |
/// https://github.com/WebAssembly/WASI/blob/38454e9e/legacy/preview1/witx/typenames.witx#L34-L39 |
| 16 |
const MAX_ERROR_CODE: i32 = u16::MAX as i32; |
| 17 |
|
| 18 |
#[inline] |
| 19 |
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
| 20 |
// Based on the wasi code: |
| 21 |
// https://docs.rs/wasi/0.11.0+wasi-snapshot-preview1/src/wasi/lib_generated.rs.html#2046-2062 |
| 22 |
// Note that size of an allocated object can not be bigger than isize::MAX bytes. |
| 23 |
// WASI 0.1 supports only 32-bit WASM, so casting length to `i32` is safe. |
| 24 |
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] |
| 25 |
let ret = unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) }; |
| 26 |
match ret { |
| 27 |
0 => Ok(()), |
| 28 |
// WASI functions should return positive error codes which are smaller than `MAX_ERROR_CODE` |
| 29 |
code if code <= MAX_ERROR_CODE => Err(Error::from_neg_error_code(-code)), |
| 30 |
_ => Err(Error::UNEXPECTED), |
| 31 |
} |
| 32 |
} |