Skip to content

Commit 7b903e1

Browse files
authored
Fix error handling in WASI p1 (rust-random#661)
1 parent 928ec5d commit 7b903e1

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
- Doc improvements [#632] [#634] [#635]
1111
- Add crate version to docs.rs links used in `compile_error!`s [#639]
1212

13+
## Fixed
14+
- Error handling in WASI p1 [#661]
15+
1316
[#632]: https://github.com/rust-random/getrandom/pull/632
1417
[#634]: https://github.com/rust-random/getrandom/pull/634
1518
[#635]: https://github.com/rust-random/getrandom/pull/635
1619
[#639]: https://github.com/rust-random/getrandom/pull/639
20+
[#661]: https://github.com/rust-random/getrandom/pull/661
1721

1822
## [0.3.2] - 2025-03-17
1923

src/backends/wasi_p1.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ extern "C" {
1111
fn random_get(arg0: i32, arg1: i32) -> i32;
1212
}
1313

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+
1418
#[inline]
1519
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
1620
// Based on the wasi code:
@@ -21,6 +25,8 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
2125
let ret = unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) };
2226
match ret {
2327
0 => Ok(()),
24-
code => Err(Error::from_neg_error_code(code)),
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),
2531
}
2632
}

0 commit comments

Comments
 (0)