From 26b88caf339122539d431cbacc16026870560590 Mon Sep 17 00:00:00 2001 From: Artyom Pavlov Date: Fri, 4 Oct 2024 20:40:24 +0300 Subject: [PATCH] wasi: remove dependency on `wasi` v0.11 (#502) Having two `wasi` versions in dependencies causes some annoyances in downstream users, e.g. v0.11 gets show as an "outdated" dependency. The dependency is removed by directly linking `random_get` by following the `wasi` code. --- Cargo.toml | 3 --- src/wasi.rs | 18 ++++++++++++++++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 34dbd3a5..2d8baa62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,9 +21,6 @@ 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(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 } diff --git a/src/wasi.rs b/src/wasi.rs index 77bc9531..db2a800e 100644 --- a/src/wasi.rs +++ b/src/wasi.rs @@ -13,8 +13,22 @@ compile_error!( #[cfg(target_env = "p1")] pub fn getrandom_inner(dest: &mut [MaybeUninit]) -> Result<(), Error> { - unsafe { wasi::random_get(dest.as_mut_ptr().cast::(), dest.len()) } - .map_err(|e| Error::from_os_error(e.raw().into())) + // This linking is vendored from the wasi crate: + // https://docs.rs/wasi/0.11.0+wasi-snapshot-preview1/src/wasi/lib_generated.rs.html#2344-2350 + #[link(wasm_import_module = "wasi_snapshot_preview1")] + extern "C" { + fn random_get(arg0: i32, arg1: i32) -> i32; + } + + // Based on the wasi code: + // https://docs.rs/wasi/0.11.0+wasi-snapshot-preview1/src/wasi/lib_generated.rs.html#2046-2062 + // Note that size of an allocated object can not be bigger than isize::MAX bytes. + // WASI 0.1 supports only 32-bit WASM, so casting length to `i32` is safe. + let ret = unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) }; + match ret { + 0 => Ok(()), + _ => Err(Error::from_os_error(ret as u32)), + } } #[cfg(target_env = "p2")]