interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / zeroize / tests / alloc.rs

74 lines · 1804 bytes Raw Blame History
1//! Tests for `Zeroize` impls on heap-allocated data structures
2
3#![allow(clippy::std_instead_of_core, clippy::undocumented_unsafe_blocks)]
4
5use std::alloc::{GlobalAlloc, Layout, System};
6use zeroize::Zeroize;
7
8// Allocator that ensures that deallocated data is zeroized.
9struct ProxyAllocator;
10
11unsafe 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]
29static PROXY_ALLOCATOR: ProxyAllocator = ProxyAllocator;
30
31struct SecretBox<S: Zeroize>(Box<S>);
32
33impl<S: Zeroize> SecretBox<S> {
34 fn new(val: S) -> Self {
35 Self(Box::new(val))
36 }
37}
38
39impl<S: Zeroize> Drop for SecretBox<S> {
40 fn drop(&mut self) {
41 self.0.as_mut().zeroize();
42 }
43}
44
45#[test]
46fn 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
53struct ObserveSecretBox<S: Default>(Box<S>);
54
55impl<S: Default> ObserveSecretBox<S> {
56 fn new(val: S) -> Self {
57 Self(Box::new(val))
58 }
59}
60
61impl<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]
69fn 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}