diff --git a/src/mm/alloc.rs b/src/mm/alloc.rs index 421b70dc55..c4c0e4e69a 100644 --- a/src/mm/alloc.rs +++ b/src/mm/alloc.rs @@ -5,6 +5,7 @@ // Author: Joerg Roedel use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::alloc::{Allocator, TryAllocError}; use crate::error::SvsmError; #[cfg(any(test, fuzzing))] use crate::locking::LockGuard; @@ -14,7 +15,7 @@ use crate::types::{PAGE_SHIFT, PAGE_SIZE}; use crate::utils::{align_down, align_up, zero_mem_region}; use core::alloc::{GlobalAlloc, Layout}; use core::mem::size_of; -use core::ptr; +use core::ptr::{self, NonNull}; use log; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1287,6 +1288,31 @@ unsafe impl GlobalAlloc for SvsmAllocator { } } +unsafe impl Allocator for SvsmAllocator { + fn allocate(&self, layout: Layout) -> Result, TryAllocError> { + match layout.size() { + 0 => Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)), + size => { + // SAFETY: size is nonzero + let raw_ptr = unsafe { self.alloc(layout) }; + // FIXME: find a way to return a more correct error here. At + // some point we must reconcile AllocError and + // TryAllocError. + let ptr = NonNull::new(raw_ptr).ok_or(TryAllocError::OutOfMemory)?; + Ok(NonNull::slice_from_raw_parts(ptr, size)) + } + } + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: `layout` is non-zero in size, + // other conditions must be upheld by the caller + if layout.size() != 0 { + self.dealloc(ptr.as_ptr(), layout) + } + } +} + #[cfg_attr(any(target_os = "none"), global_allocator)] #[cfg_attr(not(target_os = "none"), allow(dead_code))] static ALLOCATOR: SvsmAllocator = SvsmAllocator::new();