Skip to content

Commit

Permalink
Include error-reason when failining in CryptoVec unix
Browse files Browse the repository at this point in the history
  • Loading branch information
amtelekom committed Jan 10, 2025
1 parent b3cc63a commit 5a883fb
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions cryptovec/src/platform/unix.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use std::ffi::CStr;

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!("Failed to unlock memory");
panic_libc_error("Failed to unlock memory");
}
}
}
Expand All @@ -14,7 +16,7 @@ pub fn mlock(ptr: *const u8, len: usize) {
unsafe {
#[allow(clippy::panic)]
if libc::mlock(ptr as *const c_void, len) != 0 {
panic!("Failed to lock memory");
panic_libc_error("Failed to lock memory");
}
}
}
Expand All @@ -24,3 +26,20 @@ pub fn memset(ptr: *mut u8, value: i32, size: usize) {
libc::memset(ptr as *mut c_void, value, size);
}
}

unsafe fn panic_libc_error(msg: &str) {
let errno = *libc::__errno_location();
const ERRMAXLEN: usize = 255;
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")
} else {
"Invalid error"
};
// Note: if you get 'Cannot allocate memory (0xc)' here,
// check if your RLIMIT_MEMLOCK (`ulimit -l`) is configured low!
panic!("{}: {} (0x{:x})", msg, errdesc, errno);
}

0 comments on commit 5a883fb

Please sign in to comment.