From f1b94abefa7d00a21e029de6d9732d7d7efea574 Mon Sep 17 00:00:00 2001 From: Marc Hartmayer Date: Wed, 13 Nov 2024 12:32:57 +0000 Subject: [PATCH] rust/pv_core: Implement `Zeroize` trait for u* and i* primtives Use a macro for the trait implementations. Signed-off-by: Marc Hartmayer Reviewed-by: Steffen Eiden Signed-off-by: Steffen Eiden --- rust/pv_core/src/confidential.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/rust/pv_core/src/confidential.rs b/rust/pv_core/src/confidential.rs index 61d7a067..5f51d798 100644 --- a/rust/pv_core/src/confidential.rs +++ b/rust/pv_core/src/confidential.rs @@ -12,6 +12,35 @@ pub trait Zeroize { fn zeroize(&mut self); } +macro_rules! integer_impl { + ($typ:ty) => { + impl Zeroize for $typ { + /// Reliably overwrites the given number with zeros, + /// by performing a volatile write followed by a memory barrier + fn zeroize(&mut self) { + unsafe { + std::ptr::write_volatile(self as *mut $typ, <$typ>::default()); + } + std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst); + } + } + }; +} + +integer_impl!(u8); +integer_impl!(u16); +integer_impl!(u32); +integer_impl!(u64); +integer_impl!(u128); +integer_impl!(usize); + +integer_impl!(i8); +integer_impl!(i16); +integer_impl!(i32); +integer_impl!(i64); +integer_impl!(i128); +integer_impl!(isize); + // Automatically impl Zeroize for u8 arrays impl Zeroize for [T; COUNT] { /// Reliably overwrites the given buffer with zeros,