diff --git a/Cargo.toml b/Cargo.toml index cdf4e3cb..fe39d62f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ core = { version = "1.0", optional = true, package = "rustc-std-workspace-core" libc = { version = "0.2.62", default-features = false } [target.'cfg(target_os = "wasi")'.dependencies] -wasi = "0.5" +wasi = "0.7" [target.wasm32-unknown-unknown.dependencies] wasm-bindgen = { version = "0.2.29", optional = true } diff --git a/src/error.rs b/src/error.rs index c68a7677..a27a750e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -60,22 +60,29 @@ impl Error { } } -#[cfg(any(unix, target_os = "redox"))] -fn os_err_desc(errno: i32, buf: &mut [u8]) -> Option<&str> { - let buf_ptr = buf.as_mut_ptr() as *mut libc::c_char; - if unsafe { libc::strerror_r(errno, buf_ptr, buf.len()) } != 0 { - return None; - } - - // Take up to trailing null byte - let n = buf.len(); - let idx = buf.iter().position(|&b| b == 0).unwrap_or(n); - core::str::from_utf8(&buf[..idx]).ok() -} +cfg_if! { + if #[cfg(unix)] { + fn os_err_desc(errno: i32, buf: &mut [u8]) -> Option<&str> { + let buf_ptr = buf.as_mut_ptr() as *mut libc::c_char; + if unsafe { libc::strerror_r(errno, buf_ptr, buf.len()) } != 0 { + return None; + } -#[cfg(not(any(unix, target_os = "redox")))] -fn os_err_desc(_errno: i32, _buf: &mut [u8]) -> Option<&str> { - None + // Take up to trailing null byte + let n = buf.len(); + let idx = buf.iter().position(|&b| b == 0).unwrap_or(n); + core::str::from_utf8(&buf[..idx]).ok() + } + } else if #[cfg(target_os = "wasi")] { + fn os_err_desc(errno: i32, _buf: &mut [u8]) -> Option<&str> { + core::num::NonZeroU16::new(errno as u16) + .and_then(wasi::wasi_unstable::error_str) + } + } else { + fn os_err_desc(_errno: i32, _buf: &mut [u8]) -> Option<&str> { + None + } + } } impl fmt::Debug for Error { diff --git a/src/wasi.rs b/src/wasi.rs index a050afc8..713c1ab9 100644 --- a/src/wasi.rs +++ b/src/wasi.rs @@ -8,15 +8,12 @@ //! Implementation for WASI use crate::Error; -use core::num::NonZeroU32; +use core::num; use wasi::wasi_unstable::random_get; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - let ret = random_get(dest); - if let Some(code) = NonZeroU32::new(ret as u32) { - error!("WASI: random_get failed with return value {}", code); - Err(Error::from(code)) - } else { - Ok(()) // Zero means success for WASI - } + random_get(dest).map_err(|e: num::NonZeroU16| { + // convert wasi's NonZeroU16 error into getrandom's NonZeroU32 error + num::NonZeroU32::new(e.get() as u32).unwrap().into() + }) }