From 2e0f0a1a51f367dec7633e537ad4a332ee13069c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrian=20M=C3=BCller?= Date: Fri, 10 Jan 2025 13:13:23 +0100 Subject: [PATCH] Cryptovec unix error msg: fix clippy & MSRV --- cryptovec/src/platform/unix.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/cryptovec/src/platform/unix.rs b/cryptovec/src/platform/unix.rs index 745bb1e9..a1d0ab10 100644 --- a/cryptovec/src/platform/unix.rs +++ b/cryptovec/src/platform/unix.rs @@ -5,7 +5,6 @@ use libc::c_void; /// Unlock memory on drop for Unix-based systems. pub fn munlock(ptr: *const u8, len: usize) { unsafe { - #[allow(clippy::panic)] if libc::munlock(ptr as *const c_void, len) != 0 { panic_libc_error("Failed to unlock memory"); } @@ -14,7 +13,6 @@ pub fn munlock(ptr: *const u8, len: usize) { pub fn mlock(ptr: *const u8, len: usize) { unsafe { - #[allow(clippy::panic)] if libc::mlock(ptr as *const c_void, len) != 0 { panic_libc_error("Failed to lock memory"); } @@ -27,17 +25,25 @@ pub fn memset(ptr: *mut u8, value: i32, size: usize) { } } +#[allow(clippy::panic)] unsafe fn panic_libc_error(msg: &str) { let errno = *libc::__errno_location(); const ERRMAXLEN: usize = 255; + const INVALID_ERR: &str = "Unknown"; let mut errdesc = [0u8; ERRMAXLEN]; let errdesc = if libc::strerror_r(errno, errdesc.as_mut_ptr() as _, ERRMAXLEN) == 0 { - CStr::from_bytes_until_nul(&errdesc) - .ok() - .and_then(|msg| msg.to_str().ok()) - .unwrap_or("Invalid error description") + if let Some(nul_pos) = errdesc.iter().position(|b| *b == 0) { + #[allow(clippy::indexing_slicing)] + // safety: the position was just checked, so it is guaranteed to be in range + CStr::from_bytes_with_nul(&errdesc[0..nul_pos]) + .ok() + .and_then(|msg| msg.to_str().ok()) + .unwrap_or(INVALID_ERR) + } else { + INVALID_ERR + } } else { - "Invalid error" + INVALID_ERR }; // Note: if you get 'Cannot allocate memory (0xc)' here, // check if your RLIMIT_MEMLOCK (`ulimit -l`) is configured low!