//! A bounded process heap, planned together with its immutable ELF image. use super::elf_segments::{self as elf, Plan, PAGE_BYTES, GUARD_VA}; pub const MAX_HEAP_PAGES: usize = 8; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { Image(elf::Error), Empty, Capacity, AddressSpace, Shrink } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Layout { base: u64, pages: usize } impl Layout { fn new(base: u64, heap_pages: usize) -> Result { if heap_pages == 0 { return Err(Error::Empty); } if heap_pages > MAX_HEAP_PAGES { return Err(Error::Capacity); } let end = base.checked_add(heap_pages as u64 * PAGE_BYTES as u64) .ok_or(Error::AddressSpace)?; if end.checked_add(PAGE_BYTES as u64).is_none_or(|end| end > GUARD_VA) { return Err(Error::AddressSpace); } Ok(Self { base, pages: heap_pages }) } pub fn base(self) -> u64 { self.base } pub fn pages(self) -> usize { self.pages } pub fn end(self) -> u64 { self.base + self.pages as u64 * PAGE_BYTES as u64 } /// This phase only grows a heap. Validation does not mutate the old layout. pub fn grow(self, pages: usize) -> Result { if pages < self.pages { return Err(Error::Shrink); } Self::new(self.base, pages) } pub fn contains(self, address: u64, bytes: usize) -> bool { address >= self.base && address.checked_add(bytes as u64) .is_some_and(|end| end <= self.end()) } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Image<'a> { image: Plan<'a>, heap: Layout } impl<'a> Image<'a> { pub fn parse(file: &'a [u8], heap_pages: usize) -> Result { let image = Plan::parse(file).map_err(Error::Image)?; let last = image.segment(image.count() - 1).ok_or(Error::AddressSpace)?; // Leave an unmapped page between the last ELF mapping and the heap. let base = last.page_address.checked_add(2 * PAGE_BYTES as u64) .ok_or(Error::AddressSpace)?; Ok(Self { image, heap: Layout::new(base, heap_pages)? }) } pub fn image(self) -> Plan<'a> { self.image } pub fn layout(self) -> Layout { self.heap } pub fn heap_base(self) -> u64 { self.heap.base() } pub fn heap_pages(self) -> usize { self.heap.pages() } pub fn heap_end(self) -> u64 { self.heap.end() } pub fn contains(self, address: u64, bytes: usize) -> bool { self.heap.contains(address, bytes) } } #[derive(Debug, PartialEq, Eq)] pub enum PrepareError { Image(Error), Resource(E) } pub fn prepare<'a, T, E>(file: &'a [u8], pages: usize, acquire: impl FnOnce(Image<'a>) -> Result) -> Result> { acquire(Image::parse(file, pages).map_err(PrepareError::Image)?) .map_err(PrepareError::Resource) }