Skip to content

Commit 5945455

Browse files
committed
Improve robustness of the Hermit backend
1 parent 169944f commit 5945455

3 files changed

Lines changed: 11 additions & 6 deletions

File tree

src/error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ impl Error {
3535
pub const UNSUPPORTED: Error = internal_error(0);
3636
/// The platform-specific `errno` returned a non-positive value.
3737
pub const ERRNO_NOT_POSITIVE: Error = internal_error(1);
38+
/// Encountered an unexpected situation which should not happen in practice.
39+
pub const UNEXPECTED: Error = internal_error(2);
3840
/// Call to iOS [`SecRandomCopyBytes`](https://developer.apple.com/documentation/security/1399291-secrandomcopybytes) failed.
3941
pub const IOS_SEC_RANDOM: Error = internal_error(3);
4042
/// Call to Windows [`RtlGenRandom`](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom) failed.

src/hermit.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,16 @@ pub fn getrandom_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
99
while !dest.is_empty() {
1010
let res = unsafe { sys_read_entropy(dest.as_mut_ptr() as *mut u8, dest.len(), 0) };
1111
if res < 0 {
12-
// SAFETY: all Hermit error codes use i32 under the hood:
13-
// https://github.com/hermitcore/libhermit-rs/blob/master/src/errno.rs
14-
let code = unsafe { NonZeroU32::new_unchecked((-res) as u32) };
15-
return Err(code.into());
12+
let err = (-res)
13+
.try_into()
14+
.ok()
15+
.and_then(NonZeroU32::new)
16+
.map(Into::into)
17+
.unwrap_or(Error::UNEXPECTED);
18+
return Err(err);
1619
}
1720
let len = min(res as usize, dest.len());
18-
dest = &mut dest[len..];
21+
dest = dest.get_mut(len..).ok_or(Error::UNEXPECTED)?;
1922
}
2023
Ok(())
2124
}

src/util_libc.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ pub fn sys_fill_exact(
8080
// We don't check for EOF (ret = 0) as the data we are reading
8181
// should be an infinite stream of random bytes.
8282
let len = min(res as usize, buf.len());
83-
buf = &mut buf[len..];
83+
buf = buf.get_mut(len..).ok_or(Error::UNEXPECTED)?;
8484
}
8585
}
8686
Ok(())

0 commit comments

Comments
 (0)