Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions zeroize/benches/zeroize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: Copy + Default>(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();
}

Expand Down
61 changes: 61 additions & 0 deletions zeroize/src/bulk.rs
Original file line number Diff line number Diff line change
@@ -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<T: Copy>(dst: &mut [T], src: T) {
// Target 16-byte chunks
match size_of::<T>() {
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<T: Copy, const N: usize>(dst: &mut [T], src: T) {
let (chunks, tail) = as_chunks_mut::<T, N>(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<T: Copy, const N: usize>(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: <https://github.com/rust-lang/rust/blob/1.88.0/library/core/src/slice/mod.rs>
// TODO(tarcieri): use `slice::as_chunks_mut` when MSRV is 1.88 or newer.
#[inline]
#[track_caller]
#[must_use]
const fn as_chunks_mut<T, const N: usize>(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)
}
26 changes: 11 additions & 15 deletions zeroize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ mod x86;
mod barrier;
pub use barrier::optimization_barrier;

mod bulk;

mod stack;
pub use stack::zeroize_stack;

Expand Down Expand Up @@ -744,24 +746,18 @@ fn volatile_write<T: Copy + Sized>(dst: &mut T, src: T) {
/// contiguous elements of `T`.
/// `count` must not be larger than an `isize`.
/// `dst` being offset by `size_of::<T> * 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<T: Copy + Sized>(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::<T>()` bytes.
unsafe { ptr::write_volatile(ptr, src) };
if size_of::<T>() == 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::<MaybeUninit<T>>(), 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
Expand Down
Loading