Mercurial > crates > nonstick
view src/libpam/memory.rs @ 104:a2676475e86b default tip
Create the very start of a test suite.
- Creates a new testharness package
- Sets up the outlines of a test suite that will execute there
- A basic container where maybe those tests can execute
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Wed, 25 Jun 2025 16:56:56 -0400 |
parents | 3f11b8d30f63 |
children |
line wrap: on
line source
//! Things for dealing with memory. use crate::Result; use crate::{BinaryData, ErrorCode}; use std::error::Error; use std::ffi::{c_char, CStr, CString}; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::marker::{PhantomData, PhantomPinned}; use std::mem::{offset_of, ManuallyDrop}; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; use std::result::Result as StdResult; use std::{mem, ptr, slice}; /// Raised from `calloc` when you have no memory! #[derive(Debug)] pub struct NoMem; impl Display for NoMem { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { write!(f, "out of memory!") } } impl Error for NoMem {} impl From<NoMem> for ErrorCode { fn from(_: NoMem) -> Self { ErrorCode::BufferError } } /// Allocates `count` elements to hold `T`. #[inline] pub fn calloc<T>(count: usize) -> StdResult<NonNull<T>, NoMem> { // SAFETY: it's always safe to allocate! Leaking memory is fun! NonNull::new(unsafe { libc::calloc(count, size_of::<T>()) }.cast()).ok_or(NoMem) } /// Wrapper for [`libc::free`] to make debugging calls/frees easier. /// /// # Safety /// /// If you double-free, it's all your fault. #[inline] pub unsafe fn free<T>(p: *mut T) { libc::free(p.cast()) } /// Makes whatever it's in not [`Send`], [`Sync`], or [`Unpin`]. #[repr(C)] #[derive(Debug, Default)] pub struct Immovable(pub PhantomData<(*mut u8, PhantomPinned)>); /// Safely converts a `&str` option to a `CString` option. pub fn option_cstr(prompt: Option<&str>) -> Result<Option<CString>> { prompt .map(CString::new) .transpose() .map_err(|_| ErrorCode::ConversationError) } /// Gets the pointer to the given CString, or a null pointer if absent. pub fn prompt_ptr(prompt: Option<&CString>) -> *const c_char { match prompt { Some(c_str) => c_str.as_ptr(), None => ptr::null(), } } /// It's like a [`Box`], but C heap managed. #[derive(Debug)] #[repr(transparent)] pub struct CHeapBox<T>(NonNull<T>); // Lots of "as" and "into" associated functions. #[allow(clippy::wrong_self_convention)] impl<T> CHeapBox<T> { /// Creates a new CHeapBox holding the given data. pub fn new(value: T) -> Result<Self> { let memory = calloc(1)?; unsafe { ptr::write(memory.as_ptr(), value) } // SAFETY: We literally just allocated this. Ok(Self(memory)) } /// Takes ownership of the given pointer. /// /// # Safety /// /// You have to provide a valid pointer to the start of an allocation /// that was made with `malloc`. pub unsafe fn from_ptr(ptr: NonNull<T>) -> Self { Self(ptr) } /// Converts this CBox into a raw pointer. pub fn into_ptr(this: Self) -> NonNull<T> { ManuallyDrop::new(this).0 } /// Gets a pointer from this but doesn't convert this into a raw pointer. /// /// You are responsible for ensuring the CHeapBox lives long enough. pub fn as_ptr(this: &Self) -> NonNull<T> { this.0 } /// Converts this into a Box of a different type. /// /// # Safety /// /// The different type has to be compatible in size/alignment and drop behavior. pub unsafe fn cast<R>(this: Self) -> CHeapBox<R> { mem::transmute(this) } } impl<T: Default> Default for CHeapBox<T> { fn default() -> Self { Self::new(Default::default()).expect("allocation should not fail") } } impl<T> Deref for CHeapBox<T> { type Target = T; fn deref(&self) -> &Self::Target { // SAFETY: We own this pointer and it is guaranteed valid. unsafe { Self::as_ptr(self).as_ref() } } } impl<T> DerefMut for CHeapBox<T> { fn deref_mut(&mut self) -> &mut Self::Target { // SAFETY: We own this pointer and it is guaranteed valid. unsafe { Self::as_ptr(self).as_mut() } } } impl<T> Drop for CHeapBox<T> { fn drop(&mut self) { // SAFETY: We own a valid pointer, and will never use it after this. unsafe { let ptr = self.0.as_ptr(); ptr::drop_in_place(ptr); free(ptr) } } } /// A null-terminated string allocated on the C heap. /// /// Basically [`CString`], but managed by malloc. #[derive(Debug)] #[repr(transparent)] pub struct CHeapString(CHeapBox<c_char>); impl CHeapString { /// Creates a new C heap string with the given contents. pub fn new(text: &str) -> Result<Self> { let data = text.as_bytes(); if data.contains(&0) { return Err(ErrorCode::ConversationError); } // +1 for the null terminator let data_alloc: NonNull<c_char> = calloc(data.len() + 1)?; // SAFETY: we just allocated this and we have enough room. unsafe { libc::memcpy(data_alloc.as_ptr().cast(), data.as_ptr().cast(), data.len()); Ok(Self(CHeapBox::from_ptr(data_alloc))) } } /// Converts this C heap string into a raw pointer. /// /// You are responsible for freeing it later. pub fn into_ptr(self) -> NonNull<c_char> { let this = ManuallyDrop::new(self); CHeapBox::as_ptr(&this.0) } /// Converts this into a dumb box. It will no longer be zeroed upon drop. pub fn into_box(self) -> CHeapBox<c_char> { unsafe { mem::transmute(self) } } /// Takes ownership of a C heap string. /// /// # Safety /// /// You have to provide a pointer to the start of an allocation that is /// a valid 0-terminated C string. unsafe fn from_ptr(ptr: *mut c_char) -> Option<Self> { NonNull::new(ptr).map(|p| unsafe { Self(CHeapBox::from_ptr(p)) }) } unsafe fn from_box<T>(bx: CHeapBox<T>) -> Self { Self(CHeapBox::cast(bx)) } /// Zeroes the contents of a C string. /// /// # Safety /// /// You have to provide a valid pointer to a null-terminated C string. pub unsafe fn zero(ptr: NonNull<c_char>) { let cstr = ptr.as_ptr(); let len = libc::strlen(cstr.cast()); for x in 0..len { ptr::write_volatile(cstr.byte_offset(x as isize), mem::zeroed()) } } } impl Drop for CHeapString { fn drop(&mut self) { // SAFETY: We own a valid C String unsafe { Self::zero(CHeapBox::as_ptr(&self.0)) } } } impl Deref for CHeapString { type Target = CStr; fn deref(&self) -> &Self::Target { // SAFETY: We know we own a valid C string pointer. let ptr = CHeapBox::as_ptr(&self.0).as_ptr(); unsafe { CStr::from_ptr(ptr) } } } /// Creates an owned copy of a string that is returned from a /// <code>pam_get_<var>whatever</var></code> function. /// /// # Safety /// /// It's on you to provide a valid string. pub unsafe fn copy_pam_string(result_ptr: *const c_char) -> Result<Option<String>> { let borrowed = match NonNull::new(result_ptr.cast_mut()) { Some(data) => Some( CStr::from_ptr(data.as_ptr()) .to_str() .map_err(|_| ErrorCode::ConversationError)?, ), None => return Ok(None), }; Ok(borrowed.map(String::from)) } /// Binary data used in requests and responses. /// /// This is an unsized data type whose memory goes beyond its data. /// This must be allocated on the C heap. /// /// A Linux-PAM extension. #[repr(C)] pub struct CBinaryData { /// The total length of the structure; a u32 in network byte order (BE). total_length: [u8; 4], /// A tag of undefined meaning. data_type: u8, /// Pointer to an array of length [`length`](Self::length) − 5 data: [u8; 0], _marker: Immovable, } impl CBinaryData { /// Copies the given data to a new BinaryData on the heap. pub fn alloc((data, data_type): (&[u8], u8)) -> Result<CHeapBox<CBinaryData>> { let buffer_size = u32::try_from(data.len() + 5).map_err(|_| ErrorCode::ConversationError)?; // SAFETY: We're only allocating here. unsafe { let mut dest_buffer: NonNull<Self> = calloc::<u8>(buffer_size as usize)?.cast(); let dest = dest_buffer.as_mut(); dest.total_length = buffer_size.to_be_bytes(); dest.data_type = data_type; libc::memcpy( Self::data_ptr(dest_buffer).cast(), data.as_ptr().cast(), data.len(), ); Ok(CHeapBox::from_ptr(dest_buffer)) } } fn length(&self) -> usize { u32::from_be_bytes(self.total_length).saturating_sub(5) as usize } fn data_ptr(ptr: NonNull<Self>) -> *mut u8 { unsafe { ptr.as_ptr() .cast::<u8>() .byte_offset(offset_of!(Self, data) as isize) } } unsafe fn data_slice<'a>(ptr: NonNull<Self>) -> &'a mut [u8] { unsafe { slice::from_raw_parts_mut(Self::data_ptr(ptr), ptr.as_ref().length()) } } pub unsafe fn data<'a>(ptr: NonNull<Self>) -> (&'a [u8], u8) { unsafe { (Self::data_slice(ptr), ptr.as_ref().data_type) } } pub unsafe fn zero_contents(ptr: NonNull<Self>) { for byte in Self::data_slice(ptr) { ptr::write_volatile(byte as *mut u8, mem::zeroed()); } ptr::write_volatile(ptr.as_ptr(), mem::zeroed()); } #[allow(clippy::wrong_self_convention)] pub unsafe fn as_binary_data(ptr: NonNull<Self>) -> BinaryData { let (data, data_type) = unsafe { (CBinaryData::data_slice(ptr), ptr.as_ref().data_type) }; (Vec::from(data), data_type).into() } } #[cfg(test)] mod tests { use super::*; use std::hint; #[test] fn test_box() { #[allow(non_upper_case_globals)] static mut drop_count: u32 = 0; struct Dropper(i32); impl Drop for Dropper { fn drop(&mut self) { unsafe { drop_count += 1 } } } let mut dropbox = CHeapBox::new(Dropper(9)).unwrap(); hint::black_box(dropbox.0); dropbox = CHeapBox::new(Dropper(10)).unwrap(); assert_eq!(1, unsafe { drop_count }); hint::black_box(dropbox.0); drop(dropbox); assert_eq!(2, unsafe { drop_count }); } #[test] fn test_strings() { let str = CHeapString::new("hello there").unwrap(); let str_ptr = str.into_ptr().as_ptr(); CHeapString::new("hell\0 there").unwrap_err(); unsafe { let copied = copy_pam_string(str_ptr).unwrap(); assert_eq!("hello there", copied.unwrap()); CHeapString::zero(NonNull::new(str_ptr).unwrap()); let idx_three = str_ptr.add(3).as_mut().unwrap(); *idx_three = 0x80u8 as i8; let zeroed = copy_pam_string(str_ptr).unwrap().unwrap(); assert!(zeroed.is_empty()); let _ = CHeapString::from_ptr(str_ptr); } } #[test] fn test_option_str() { let good = option_cstr(Some("whatever")).unwrap(); assert_eq!("whatever", good.unwrap().to_str().unwrap()); let no_str = option_cstr(None).unwrap(); assert!(no_str.is_none()); let bad_str = option_cstr(Some("what\0ever")).unwrap_err(); assert_eq!(ErrorCode::ConversationError, bad_str); } #[test] fn test_prompt() { let prompt_cstr = CString::new("good").ok(); let prompt = prompt_ptr(prompt_cstr.as_ref()); assert!(!prompt.is_null()); let no_prompt = prompt_ptr(None); assert!(no_prompt.is_null()); } }