Skip to content

Commit 0cc05bb

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 43c9a90 commit 0cc05bb

2 files changed

Lines changed: 22 additions & 5 deletions

File tree

src/backends/getentropy.rs

Lines changed: 15 additions & 3 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,19 @@ 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()) };
2230
if ret != 0 {
23-
let errno = utils::get_errno();
24-
return Err(Error::from_errno(errno));
31+
let err = if ret == -1 {
32+
Error::from_errno(utils::get_errno())
33+
} else {
34+
Error::from_errno(errno)
35+
};
36+
return Err(err);
2537
}
2638
}
2739
Ok(())

src/backends/vxworks.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,13 @@ pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
3939
let p: *mut libc::c_uchar = chunk.as_mut_ptr().cast();
4040
let ret = unsafe { libc::randABytes(p, chunk_len) };
4141
if ret != 0 {
42-
let errno = unsafe { libc::errnoGet() };
43-
return Err(Error::from_errno(errno));
42+
let err = if ret == -1 {
43+
let errno = unsafe { libc::errnoGet() };
44+
Error::from_errno(errno)
45+
} else {
46+
Error::UNEXPECTED
47+
};
48+
return Err(err);
4449
}
4550
}
4651
Ok(())

0 commit comments

Comments
 (0)