Skip to content
Open
Changes from 1 commit
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
Next Next commit
zeroize: add observe function
  • Loading branch information
newpavlov committed Dec 15, 2025
commit 35b5faba348e9cd62bff22ae5fec340fd961a7cf
72 changes: 72 additions & 0 deletions zeroize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,78 @@ pub unsafe fn zeroize_flat_type<F: Sized>(data: *mut F) {
atomic_fence()
}

/// Observe the referenced data and prevent the compiler from removing previous writes to it.
///
/// This function acts like [`core::hint::black_box`] but takes a reference and
/// does not return the passed value.
///
/// It's implemented using the [`core::arch::asm!`] macro on targets where `asm!` is stable,
/// while on all other targets it's implemented using [`core::hint::black_box`].
///
/// # Examples
/// ```
/// use core::num::NonZeroU32;
/// use zeroize::{ZeroizeOnDrop, zeroize_flat_type};
///
/// struct DataToZeroize {
/// buf: [u8; 32],
/// pos: NonZeroU32,
/// }
///
/// struct SomeMoreFlatData(u64);
///
/// impl Drop for DataToZeroize {
/// fn drop(&mut self) {
/// self.buf = [0u8; 32];
/// self.pos = NonZeroU32::new(32).unwrap();
/// zeroize::observe(self);
/// }
/// }
///
/// impl zeroize::ZeroizeOnDrop for DataToZeroize {}
///
/// let mut data = DataToZeroize {
/// buf: [3u8; 32],
/// pos: NonZeroU32::new(32).unwrap(),
/// };
///
/// // data gets zeroized when dropped
/// ```
pub fn observe<R: ?Sized>(val: &R) {
#[cfg(any(
target_arch = "aarch64",
target_arch = "arm",
target_arch = "arm64ec",
target_arch = "loongarch32",
target_arch = "loongarch64",
target_arch = "riscv32",
target_arch = "riscv64",
target_arch = "s390x",
target_arch = "x86",
target_arch = "x86_64",
))]
unsafe {
core::arch::asm!(
"# {}",
in(reg) val as *const R as *const (),
options(readonly, preserves_flags, nostack),
);
}
#[cfg(not(any(
target_arch = "aarch64",
target_arch = "arm",
target_arch = "arm64ec",
target_arch = "loongarch32",
target_arch = "loongarch64",
target_arch = "riscv32",
target_arch = "riscv64",
target_arch = "s390x",
target_arch = "x86",
target_arch = "x86_64",
)))]
core::hint::black_box(val);
}

/// Internal module used as support for `AssertZeroizeOnDrop`.
#[doc(hidden)]
pub mod __internal {
Expand Down
Loading