Zeroizing allocator (#154)

* Add a zeroizing allocator

* Also implement the allocator API

* Add misisng license file to zalloc

* Slight change to zalloc description
This commit is contained in:
Luke Parker
2022-11-10 23:34:40 -06:00
committed by GitHub
parent 7334ed1f43
commit 3d9b9b178c
5 changed files with 95 additions and 0 deletions

46
common/zalloc/src/lib.rs Normal file
View File

@@ -0,0 +1,46 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(feature = "allocator", feature(allocator_api))]
//! Implementation of a Zeroizing Allocator, enabling zeroizing memory on deallocation.
//! This can either be used with Box (requires nightly and the "allocator" feature) to provide the
//! functionality of zeroize on types which don't implement zeroize, or used as a wrapper around
//! the global allocator to ensure *all* memory is zeroized.
use core::{
slice,
alloc::{Layout, GlobalAlloc},
};
use zeroize::Zeroize;
/// An allocator wrapper which zeroizes its memory on dealloc.
pub struct ZeroizingAlloc<T>(pub T);
#[cfg(feature = "allocator")]
use core::{
ptr::NonNull,
alloc::{AllocError, Allocator},
};
#[cfg(feature = "allocator")]
unsafe impl<T: Allocator> Allocator for ZeroizingAlloc<T> {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
self.0.allocate(layout)
}
unsafe fn deallocate(&self, mut ptr: NonNull<u8>, layout: Layout) {
slice::from_raw_parts_mut(ptr.as_mut(), layout.size()).zeroize();
self.0.deallocate(ptr, layout);
}
}
unsafe impl<T: GlobalAlloc> GlobalAlloc for ZeroizingAlloc<T> {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.0.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
slice::from_raw_parts_mut(ptr, layout.size()).zeroize();
self.0.dealloc(ptr, layout);
}
}