Skip to content

Commit 4cb5ca6

Browse files
committed
util_libc: Clarify that conversion of syscall result is lossless.
1 parent aee6ebd commit 4cb5ca6

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/util_libc.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,23 @@ pub fn open_readonly(path: &[u8]) -> Result<libc::c_int, Error> {
103103
/// Thin wrapper around the `getrandom()` Linux system call
104104
#[cfg(any(target_os = "android", target_os = "linux"))]
105105
pub fn getrandom_syscall(buf: &mut [MaybeUninit<u8>]) -> libc::ssize_t {
106-
unsafe {
106+
let len: usize = core::cmp::min(buf.len(), libc::ssize_t::MAX.unsigned_abs());
107+
108+
let res: libc::c_long = unsafe {
107109
libc::syscall(
108110
libc::SYS_getrandom,
109111
buf.as_mut_ptr().cast::<core::ffi::c_void>(),
110-
buf.len(),
112+
len,
111113
0,
112-
) as libc::ssize_t
113-
}
114+
)
115+
};
116+
117+
// c_long to ssize_t conversion is lossless.
118+
const _: () =
119+
assert!(core::mem::size_of::<libc::c_long>() == core::mem::size_of::<libc::ssize_t>());
120+
121+
// We clamped the request to `ssize_t::MAX` bytes so this lossless.
122+
#[allow(clippy::cast_possible_truncation)]
123+
let res = res as libc::ssize_t;
124+
res
114125
}

0 commit comments

Comments
 (0)