//! Bounded static ELF segments. The validated plan borrows immutable bytes; //! all segment checks precede acquisition or destination writes. use super::elf_loader::{Error as HeaderError, Headers, MAX_PROGRAM_HEADERS}; pub const PAGE_BYTES: usize = 4096; pub const USER_BASE: u64 = 0x8000_0000; pub const IMAGE_PAGES: usize = 16; pub const GUARD_VA: u64 = USER_BASE + IMAGE_PAGES as u64 * PAGE_BYTES as u64; pub const STACK_VA: u64 = GUARD_VA + PAGE_BYTES as u64; pub const STACK_TOP: u64 = STACK_VA + PAGE_BYTES as u64; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { Header(HeaderError), UnsupportedType, Permissions, WritableExecutable, EmptySegment, FileLargerThanMemory, FileRange, UserRange, Alignment, SegmentTooLarge, Overlap, Order, NoSegments, Entry, Destination, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Permission { ReadOnly, ReadExecute, ReadWrite } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Segment { pub virtual_address: u64, pub page_address: u64, pub memory_size: usize, pub file_size: usize, pub permission: Permission, file_offset: usize, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Plan<'a> { file: &'a [u8], entry: u64, segments: [Option; MAX_PROGRAM_HEADERS], count: usize, } impl<'a> Plan<'a> { pub fn parse(file: &'a [u8]) -> Result { let headers = Headers::parse(file).map_err(Error::Header)?; let mut plan = Self { file, entry: headers.entry(), segments: [None; MAX_PROGRAM_HEADERS], count: 0 }; for index in 0..headers.count() { let p = headers.program(index).expect("bounded header iterator"); if p.kind == 0 { continue; } if p.kind != 1 { return Err(Error::UnsupportedType); } if p.flags & 3 == 3 { return Err(Error::WritableExecutable); } let permission = match p.flags { 4 => Permission::ReadOnly, 5 => Permission::ReadExecute, 6 => Permission::ReadWrite, _ => return Err(Error::Permissions), }; if p.memory_size == 0 { return Err(Error::EmptySegment); } if p.file_size > p.memory_size { return Err(Error::FileLargerThanMemory); } let file_end = p.offset.checked_add(p.file_size).ok_or(Error::FileRange)?; let file_offset = usize::try_from(p.offset).map_err(|_| Error::FileRange)?; let file_end = usize::try_from(file_end).map_err(|_| Error::FileRange)?; if file.get(file_offset..file_end).is_none() { return Err(Error::FileRange); } let memory_end = p.virtual_address.checked_add(p.memory_size).ok_or(Error::UserRange)?; if p.virtual_address < USER_BASE || memory_end > GUARD_VA { return Err(Error::UserRange); } let page_address = p.virtual_address & !(PAGE_BYTES as u64 - 1); if memory_end > page_address + PAGE_BYTES as u64 { return Err(Error::SegmentTooLarge); } // Even p_align=0/1 keeps page-offset congruence for PT_LOAD. if p.offset % PAGE_BYTES as u64 != p.virtual_address % PAGE_BYTES as u64 || p.alignment > 1 && (!p.alignment.is_power_of_two() || p.virtual_address % p.alignment != p.offset % p.alignment) { return Err(Error::Alignment); } for previous in plan.segments[..plan.count].iter().flatten() { // Distinct byte ranges sharing a physical mapping granule // cannot receive independent permissions in this loader. if previous.page_address == page_address { return Err(Error::Overlap); } if previous.virtual_address > p.virtual_address { return Err(Error::Order); } } plan.segments[plan.count] = Some(Segment { virtual_address: p.virtual_address, page_address, memory_size: p.memory_size as usize, file_size: p.file_size as usize, permission, file_offset }); plan.count += 1; } if plan.count == 0 { return Err(Error::NoSegments); } // An entry must identify a whole AArch64 instruction backed by RX // file bytes. This is mandatory even before later entry-specific gates. if plan.entry & 3 != 0 || !plan.segments[..plan.count].iter().flatten().any(|p| p.permission == Permission::ReadExecute && plan.entry >= p.virtual_address && plan.entry.checked_add(4).is_some_and(|end| end <= p.virtual_address + p.file_size as u64)) { return Err(Error::Entry); } Ok(plan) } pub fn entry(self) -> u64 { self.entry } pub fn count(self) -> usize { self.count } pub fn segment(self, index: usize) -> Option { self.segments.get(index).copied().flatten() } /// A full page is zeroed before the immutable file payload is copied. /// Invalid index/size leaves the caller's destination untouched. pub fn copy_page(self, index: usize, page: &mut [u8]) -> Result<(), Error> { let segment = self.segment(index).ok_or(Error::Destination)?; if page.len() != PAGE_BYTES { return Err(Error::Destination); } let start = (segment.virtual_address - segment.page_address) as usize; let source = &self.file[segment.file_offset..segment.file_offset + segment.file_size]; page[start..start + segment.file_size].copy_from_slice(source); Ok(()) } } #[derive(Debug, PartialEq, Eq)] pub enum PrepareError { Image(Error), Resource(E) } pub fn prepare<'a, T, E>(file: &'a [u8], acquire: impl FnOnce(Plan<'a>) -> Result) -> Result> { let plan = Plan::parse(file).map_err(PrepareError::Image)?; acquire(plan).map_err(PrepareError::Resource) }