Skip to content

Commit 0e7e6e6

Browse files
authored
zeroize: add proxy_alloc_test (#1199)
The added test checks that zeroization happens using a custom global allocator. Replacing `self.0.as_mut().zeroize()` with `self.0 = Default::default()` results in test failure as expected. The test also passes Miri without issues.
1 parent 8a58487 commit 0e7e6e6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

zeroize/tests/alloc.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
use std::alloc::{GlobalAlloc, Layout, System};
2+
3+
use zeroize::Zeroize;
4+
5+
// Allocator that ensures that deallocated data is zeroized.
6+
struct ProxyAllocator;
7+
8+
unsafe impl GlobalAlloc for ProxyAllocator {
9+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
10+
unsafe { System.alloc(layout) }
11+
}
12+
13+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
14+
if layout.size() == 160 {
15+
for i in 0..layout.size() {
16+
let b = unsafe { core::ptr::read(ptr.add(i)) };
17+
if b != 0 {
18+
panic!()
19+
}
20+
}
21+
}
22+
23+
unsafe { System.dealloc(ptr, layout) }
24+
}
25+
}
26+
27+
#[global_allocator]
28+
static PROXY_ALLOCATOR: ProxyAllocator = ProxyAllocator;
29+
30+
struct SecretBox<S: Zeroize>(Box<S>);
31+
32+
impl<S: Zeroize> SecretBox<S> {
33+
fn new(val: S) -> Self {
34+
Self(Box::new(val))
35+
}
36+
}
37+
38+
impl<S: Zeroize> Drop for SecretBox<S> {
39+
fn drop(&mut self) {
40+
self.0.as_mut().zeroize()
41+
}
42+
}
43+
44+
#[test]
45+
fn proxy_alloc_test() {
46+
let b1 = SecretBox::new([u128::MAX; 10]);
47+
core::hint::black_box(&b1);
48+
let b2 = SecretBox::new([u8::MAX; 160]);
49+
core::hint::black_box(&b2);
50+
}

0 commit comments

Comments
 (0)