Skip to content

Commit 70b09d7

Browse files
committed
Avoid accessing errno on unexpected return values.
We expect that these system calls will never return anything other than 0 or -1 but if they do for some reason, then we shouldn't access `errno`.
1 parent 3d1b151 commit 70b09d7

File tree

3 files changed

+22
-7
lines changed

3 files changed

+22
-7
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
- Bump `r-efi` dependency to v6 [#814]
1111

1212
### Fixed
13+
- Read `errno` only when it is set [#810]
1314
- Check the return value of `ProcessPrng` on Windows [#811]
1415

1516
[Unreleased]: https://github.com/rust-random/getrandom/compare/v0.4.1...master
17+
[#810]: https://github.com/rust-random/getrandom/pull/810
1618
[#811]: https://github.com/rust-random/getrandom/pull/811
1719
[#814]: https://github.com/rust-random/getrandom/pull/814
1820

src/backends/getentropy.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
//! Implementation using getentropy(2)
22
//!
3+
//! When porting to a new target, ensure that its implementation follows the
4+
//! POSIX conventions from
5+
//! <https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html>.
6+
//!
37
//! Available since:
48
//! - macOS 10.12
59
//! - OpenBSD 5.6
@@ -17,11 +21,16 @@ mod utils;
1721

1822
#[inline]
1923
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
20-
for chunk in dest.chunks_mut(256) {
24+
// https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/limits.h.html
25+
// says `GETENTROPY_MAX` is at least 256.
26+
const GETENTROPY_MAX: usize = 256;
27+
28+
for chunk in dest.chunks_mut(GETENTROPY_MAX) {
2129
let ret = unsafe { libc::getentropy(chunk.as_mut_ptr().cast::<c_void>(), chunk.len()) };
22-
if ret != 0 {
23-
let errno = utils::get_errno();
24-
return Err(Error::from_errno(errno));
30+
match ret {
31+
0 => continue,
32+
-1 => return Err(Error::from_errno(utils::get_errno())),
33+
_ => return Err(Error::UNEXPECTED),
2534
}
2635
}
2736
Ok(())

src/backends/vxworks.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,13 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
3838
.expect("chunk size is bounded by i32::MAX");
3939
let p: *mut libc::c_uchar = chunk.as_mut_ptr().cast();
4040
let ret = unsafe { libc::randABytes(p, chunk_len) };
41-
if ret != 0 {
42-
let errno = unsafe { libc::errnoGet() };
43-
return Err(Error::from_errno(errno));
41+
match ret {
42+
0 => continue,
43+
-1 => {
44+
let errno = unsafe { libc::errnoGet() };
45+
return Err(Error::from_errno(errno));
46+
}
47+
_ => return Err(Error::UNEXPECTED),
4448
}
4549
}
4650
Ok(())

0 commit comments

Comments
 (0)