diff --git a/zeroize/benches/zeroize.rs b/zeroize/benches/zeroize.rs index 8b364d03..9ae5f951 100644 --- a/zeroize/benches/zeroize.rs +++ b/zeroize/benches/zeroize.rs @@ -4,17 +4,37 @@ use core::hint::black_box; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; -use zeroize::Zeroize; +use zeroize::{Zeroize, optimization_barrier}; + +#[inline(always)] +fn write_with_barrier(buf: &mut [T]) { + let zero = T::default(); + for val in buf.iter_mut() { + *val = zero; + } + optimization_barrier(buf); +} fn bench_slices(c: &mut Criterion) { let mut group = c.benchmark_group("slice/u8"); - for len in [16, 32, 63, 64, 65, 128, 4096, 65536] { + for len in [15, 16, 17, 32, 63, 64, 65, 128, 4096, 65536] { let mut bytes = vec![0xa5u8; len]; group.throughput(Throughput::Bytes(len as u64)); group.bench_function(BenchmarkId::from_parameter(len), |b| { b.iter(|| black_box(bytes.as_mut_slice()).zeroize()); }); + group.bench_function(BenchmarkId::new("write+barrier", len), |b| { + b.iter(|| write_with_barrier(black_box(bytes.as_mut_slice()))); + }); } + let mut bytes = [0xa5u8; 16]; + group.throughput(Throughput::Bytes(16)); + group.bench_function("fixed16", |b| { + b.iter(|| black_box(&mut bytes).as_mut_slice().zeroize()); + }); + group.bench_function("write+barrier/fixed16", |b| { + b.iter(|| write_with_barrier(black_box(&mut bytes).as_mut_slice())); + }); group.finish(); } diff --git a/zeroize/src/bulk.rs b/zeroize/src/bulk.rs new file mode 100644 index 00000000..9d22fef3 --- /dev/null +++ b/zeroize/src/bulk.rs @@ -0,0 +1,61 @@ +//! Bulk volatile writes of a repeated `Copy` value. + +use crate::volatile_write; +use core::mem::size_of; + +/// Fill a slice with a repeated value, preserving its type and alignment. +#[inline(always)] +pub(crate) fn fill(dst: &mut [T], src: T) { + // Target 16-byte chunks + match size_of::() { + 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); + } + } + } +} + +/// Prepare the repeated pattern and handle the tail independently of the bulk backend. +#[inline(always)] +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); + } +} + +/// Portable backend for writing all complete chunks. +#[inline(always)] +fn write_chunks(dst: &mut [[T; N]], pattern: [T; N]) { + for chunk in dst { + volatile_write(chunk, pattern); + } +} + +/// MSRV-compatible copy of core's `slice::as_chunks_mut` taken from Rust 1.88.0. +/// Source: +// TODO(tarcieri): use `slice::as_chunks_mut` when MSRV is 1.88 or newer. +#[inline] +#[track_caller] +#[must_use] +const fn as_chunks_mut(slice: &mut [T]) -> (&mut [[T; N]], &mut [T]) { + assert!(N != 0, "chunk size must be non-zero"); + let len_rounded_down = slice.len() / N * N; + // SAFETY: The rounded-down value is always the same or smaller than the + // original length, and thus must be in-bounds of the slice. + let (multiple_of_n, remainder) = unsafe { slice.split_at_mut_unchecked(len_rounded_down) }; + // SAFETY: We already panicked for zero, and ensured by construction + // that the length of the subslice is a multiple of N. Arrays have the same alignment as T. + let array_slice = unsafe { + core::slice::from_raw_parts_mut(multiple_of_n.as_mut_ptr().cast(), multiple_of_n.len() / N) + }; + (array_slice, remainder) +} diff --git a/zeroize/src/lib.rs b/zeroize/src/lib.rs index 34126c75..7a516b25 100644 --- a/zeroize/src/lib.rs +++ b/zeroize/src/lib.rs @@ -221,6 +221,8 @@ mod x86; mod barrier; pub use barrier::optimization_barrier; +mod bulk; + mod stack; pub use stack::zeroize_stack; @@ -744,24 +746,18 @@ fn volatile_write(dst: &mut T, src: T) { /// 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. +/// 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. #[inline(always)] unsafe fn volatile_set(dst: *mut T, src: T, count: usize) { - // TODO(tarcieri): use `volatile_set_memory` when stabilized - for i in 0..count { - // Safety: - // - // This is safe because there is room for at least `count` objects of type `T` in the - // allocation pointed to by `dst`, because `count <= isize::MAX` and because - // `dst.add(count)` must not wrap around the address space. - let ptr = unsafe { dst.add(i) }; - - // Safety: - // - // This is safe, because the pointer is valid and because `dst` is well aligned for `T` and - // `ptr` is an offset of `dst` by a multiple of `size_of::()` bytes. - unsafe { ptr::write_volatile(ptr, src) }; + if size_of::() == 0 || count == 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)); } /// Zeroizes a flat type/struct. Only zeroizes the values that it owns, and it does not work on