Skip to content

Fix error handling in WASI p1 #661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Doc improvements [#632] [#634] [#635]
- Add crate version to docs.rs links used in `compile_error!`s [#639]

## Fixed
- Error handling in WASI p1 [#661]

[#632]: https://github.com/rust-random/getrandom/pull/632
[#634]: https://github.com/rust-random/getrandom/pull/634
[#635]: https://github.com/rust-random/getrandom/pull/635
[#639]: https://github.com/rust-random/getrandom/pull/639
[#661]: https://github.com/rust-random/getrandom/pull/661

## [0.3.2] - 2025-03-17

Expand Down
8 changes: 7 additions & 1 deletion src/backends/wasi_p1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ extern "C" {
fn random_get(arg0: i32, arg1: i32) -> i32;
}

/// WASI p1 uses `u16` for error codes in its witx definitions:
/// https://github.com/WebAssembly/WASI/blob/38454e9e/legacy/preview1/witx/typenames.witx#L34-L39
const MAX_ERROR_CODE: i32 = u16::MAX as i32;

#[inline]
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Based on the wasi code:
Expand All @@ -21,6 +25,8 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
let ret = unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) };
match ret {
0 => Ok(()),
code => Err(Error::from_neg_error_code(code)),
// WASI functions should return positive error codes which are smaller than `MAX_ERROR_CODE`
code if code <= MAX_ERROR_CODE => Err(Error::from_neg_error_code(-code)),
_ => Err(Error::UNEXPECTED),
}
}