· 6 years ago · Feb 12, 2019, 12:06 AM
1#![feature(maybe_uninit)]
2
3mod ralloc {
4 use ::std::{
5 mem::MaybeUninit,
6 ops::{Deref, DerefMut},
7 ptr,
8 };
9
10 pub struct ZeroDropBox<T> /* = */ (Box< MaybeUninit<T> >);
11
12 impl<T> Drop for ZeroDropBox<T>
13 {
14 fn drop (
15 self: &mut Self,
16 )
17 { unsafe {
18 ptr::drop_in_place(self.0.as_mut_ptr());
19 ptr::write_volatile(
20 Box::deref_mut(&mut self.0),
21 MaybeUninit::zeroed(),
22 );
23 // we could even go as far as to zero the pointer itself ...
24 }}
25 }
26
27 impl<T> From<T> for ZeroDropBox<T>
28 {
29 #[inline(always)]
30 fn from (inline_value: T) -> Self
31 {
32 ZeroDropBox(
33 Box::new(
34 MaybeUninit::new(
35 inline_value
36 )
37 )
38 )
39 }
40 }
41
42 impl<T> Deref for ZeroDropBox<T>
43 {
44 type Target = T;
45
46 #[inline]
47 fn deref (
48 self: &Self,
49 ) -> &Self::Target
50 { unsafe {
51 self.0.get_ref()
52 }}
53 }
54 impl<T> DerefMut for ZeroDropBox<T>
55 {
56 #[inline]
57 fn deref_mut (
58 self: &mut Self,
59 ) -> &mut Self::Target
60 { unsafe {
61 self.0.get_mut()
62 }}
63 }
64}
65pub use self::ralloc::ZeroDropBox;
66
67fn main ()
68{
69 let secret_key = ZeroDropBox::from([42_u8; 16]);
70 dbg!(&secret_key as &[u8; 16]);
71 let secret_key_after_free: &[u8; 16] = unsafe {
72 &*(&secret_key as &[u8; 16] as *const _)
73 };
74 ::std::mem::drop(secret_key);
75 dbg!(secret_key_after_free);
76}