aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / zeroize / tests / alloc.rs
| 1 | //! Tests for `Zeroize` impls on heap-allocated data structures |
| 2 | |
| 3 | #![allow(clippy::std_instead_of_core, clippy::undocumented_unsafe_blocks)] |
| 4 | |
| 5 | use std::alloc::{GlobalAlloc, Layout, System}; |
| 6 | use zeroize::Zeroize; |
| 7 | |
| 8 | // Allocator that ensures that deallocated data is zeroized. |
| 9 | struct ProxyAllocator; |
| 10 | |
| 11 | unsafe impl GlobalAlloc for ProxyAllocator { |
| 12 | unsafe fn alloc(&self, layout: Layout) -> *mut u8 { |
| 13 | unsafe { System.alloc(layout) } |
| 14 | } |
| 15 | |
| 16 | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { |
| 17 | if layout.size() == 160 { |
| 18 | for i in 0..layout.size() { |
| 19 | let b = unsafe { core::ptr::read(ptr.add(i)) }; |
| 20 | assert_eq!(b, 0); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | unsafe { System.dealloc(ptr, layout) } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | #[global_allocator] |
| 29 | static PROXY_ALLOCATOR: ProxyAllocator = ProxyAllocator; |
| 30 | |
| 31 | struct SecretBox<S: Zeroize>(Box<S>); |
| 32 | |
| 33 | impl<S: Zeroize> SecretBox<S> { |
| 34 | fn new(val: S) -> Self { |
| 35 | Self(Box::new(val)) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | impl<S: Zeroize> Drop for SecretBox<S> { |
| 40 | fn drop(&mut self) { |
| 41 | self.0.as_mut().zeroize(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[test] |
| 46 | fn secret_box_alloc_test() { |
| 47 | let b1 = SecretBox::new([u128::MAX; 10]); |
| 48 | core::hint::black_box(&b1); |
| 49 | let b2 = SecretBox::new([u8::MAX; 160]); |
| 50 | core::hint::black_box(&b2); |
| 51 | } |
| 52 | |
| 53 | struct ObserveSecretBox<S: Default>(Box<S>); |
| 54 | |
| 55 | impl<S: Default> ObserveSecretBox<S> { |
| 56 | fn new(val: S) -> Self { |
| 57 | Self(Box::new(val)) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | impl<S: Default> Drop for ObserveSecretBox<S> { |
| 62 | fn drop(&mut self) { |
| 63 | *self.0 = Default::default(); |
| 64 | zeroize::optimization_barrier(&self); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | #[test] |
| 69 | fn observe_secret_box_alloc_test() { |
| 70 | let b1 = ObserveSecretBox::new([u128::MAX; 10]); |
| 71 | core::hint::black_box(&b1); |
| 72 | let b2 = SecretBox::new([u8::MAX; 160]); |
| 73 | core::hint::black_box(&b2); |
| 74 | } |