diff --git a/zeroize/src/bulk.rs b/zeroize/src/bulk.rs index 9d22fef3..e419899e 100644 --- a/zeroize/src/bulk.rs +++ b/zeroize/src/bulk.rs @@ -8,15 +8,12 @@ use core::mem::size_of; pub(crate) fn fill(dst: &mut [T], src: T) { // Target 16-byte chunks match size_of::() { + 0 => {} 1 => fill_chunked::<_, 16>(dst, src), 2 => fill_chunked::<_, 8>(dst, src), 4 => fill_chunked::<_, 4>(dst, src), 8 => fill_chunked::<_, 2>(dst, src), - _ => { - for item in dst { - volatile_write(item, src); - } - } + _ => write_elements(dst, src), } } @@ -25,18 +22,16 @@ pub(crate) fn fill(dst: &mut [T], src: T) { fn fill_chunked(dst: &mut [T], src: T) { let (chunks, tail) = as_chunks_mut::(dst); if !chunks.is_empty() { - write_chunks(chunks, [src; N]); - } - for item in tail { - volatile_write(item, src); + write_elements(chunks, [src; N]); } + write_elements(tail, src); } -/// Portable backend for writing all complete chunks. +/// Write individual elements or complete chunks with the same volatile primitive. #[inline(always)] -fn write_chunks(dst: &mut [[T; N]], pattern: [T; N]) { - for chunk in dst { - volatile_write(chunk, pattern); +fn write_elements(dst: &mut [T], src: T) { + for item in dst { + volatile_write(item, src); } } diff --git a/zeroize/src/lib.rs b/zeroize/src/lib.rs index 7a516b25..9d569864 100644 --- a/zeroize/src/lib.rs +++ b/zeroize/src/lib.rs @@ -228,13 +228,13 @@ pub use stack::zeroize_stack; use core::{ marker::{PhantomData, PhantomPinned}, - mem::{MaybeUninit, size_of}, + mem::{MaybeUninit, size_of, size_of_val}, num::{ self, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize, }, ops, ptr, - slice::IterMut, + slice::{self, IterMut}, }; #[cfg(feature = "alloc")] @@ -385,11 +385,7 @@ where // The memory pointed to by `self` is valid for `size_of::()` bytes. // It is also properly aligned, because `u8` has an alignment of `1`. unsafe { - volatile_set( - ptr::from_mut::(self).cast::(), - 0, - size_of::(), - ); + volatile_zero(ptr::from_mut::(self).cast::(), size_of::()); } // Ensures self is overwritten with the `None` bit pattern. volatile_write can't be @@ -429,17 +425,11 @@ impl Zeroize for MaybeUninit { /// [`MaybeUninit`] removes all invariants. impl Zeroize for [MaybeUninit] { fn zeroize(&mut self) { - let ptr = self.as_mut_ptr().cast::>(); - let size = self.len().checked_mul(size_of::()).expect("overflow"); - assert!(isize::try_from(size).is_ok()); + let size = size_of_val(self); - // Safety: - // - // This is safe, because every valid pointer is well aligned for u8 - // and it is backed by a single allocated object for at least `self.len() * size_pf::()` bytes. - // and 0 is a valid value for `MaybeUninit` - // The memory of the slice should not wrap around the address space. - unsafe { volatile_set(ptr, MaybeUninit::zeroed(), size) } + // SAFETY: the slice provides exclusive access to `size` bytes, and + // `MaybeUninit` permits all-zero bytes, including in padding. + unsafe { volatile_zero(self.as_mut_ptr().cast::(), size) } } } @@ -456,22 +446,13 @@ where Z: DefaultIsZeroes, { fn zeroize(&mut self) { - assert!(isize::try_from(self.len()).is_ok()); - - // Safety: - // - // This is safe, because the slice is well aligned and is backed by a single allocated - // object for at least `self.len()` elements of type `Z`. - // `self.len()` is also not larger than an `isize`, because of the assertion above. - // The memory of the slice should not wrap around the address space. - unsafe { volatile_set(self.as_mut_ptr(), Z::default(), self.len()) }; + bulk::fill(self, Z::default()); } } impl Zeroize for str { fn zeroize(&mut self) { - // Safety: - // A zeroized byte slice is a valid UTF-8 string. + // SAFETY: a zeroized byte slice is a valid UTF-8 string. unsafe { self.as_bytes_mut().zeroize() } } } @@ -739,25 +720,23 @@ fn volatile_write(dst: &mut T, src: T) { unsafe { ptr::write_volatile(dst, src) } } -/// Perform a volatile `memset` operation which fills a slice with a value +/// Zero potentially uninitialized memory with volatile byte writes. /// /// # Safety -/// The memory pointed to by `dst` must be a single allocated object that is valid for `count` -/// contiguous elements of `T`. -/// `count` must not be larger than an `isize`. -/// `dst` being offset by `size_of:: * count` bytes must not wrap around the address space. -/// Also `dst` must be properly aligned and non-null, and the total size must not exceed -/// `isize::MAX` bytes. The destination need not be initialized. +/// For nonzero `len`, `dst` must be non-null and provide exclusive write access to +/// `len` bytes within a single allocation. The size must not exceed `isize::MAX`, +/// and the address range must not wrap. If zeroes are not a valid representation, +/// the caller must restore a valid value before any typed access or drop. #[inline(always)] -unsafe fn volatile_set(dst: *mut T, src: T, count: usize) { - if size_of::() == 0 || count == 0 { +unsafe fn volatile_zero(dst: *mut u8, len: usize) { + if len == 0 { return; } - // SAFETY: the caller supplies an aligned, writable allocation of the stated size. - // MaybeUninit permits uninitialized destinations, including padding and spare capacity. - let dst = unsafe { core::slice::from_raw_parts_mut(dst.cast::>(), count) }; - bulk::fill(dst, MaybeUninit::new(src)); + // SAFETY: the caller supplies exclusive access to the stated range. + // `MaybeUninit` has byte alignment and permits uninitialized bytes. + let dst = unsafe { slice::from_raw_parts_mut(dst.cast::>(), len) }; + bulk::fill(dst, MaybeUninit::new(0)); } /// Zeroizes a flat type/struct. Only zeroizes the values that it owns, and it does not work on @@ -815,7 +794,7 @@ pub unsafe fn zeroize_flat_type(data: *mut F) { // This is safe because `size_of()` returns the exact size of the object in memory, and // `data_ptr` points directly to the first byte of the data. unsafe { - volatile_set(data.cast::(), 0, size); + volatile_zero(data.cast::(), size); } }