//! Owned, unpublished page tables for a bounded static ELF image. use crate::{memory::FrameAllocator, mmu::Tables}; use super::elf_segments::Plan; use super::elf_segments::{ Permission, PAGE_BYTES, USER_BASE, STACK_VA}; const MAX_FRAMES: usize = 8; // Three tables, three ELF, one file page, stack. const PXN: u64 = 1 << 53; const UXN: u64 = 1 << 54; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { Context, OutOfFrames, Payload, Return } #[derive(Debug)] pub struct Space { frames: [u64; MAX_FRAMES], owned: usize, entry: u64, segments: usize, } fn descriptor(address: u64, permission: Permission) -> u64 { let common=address|3|0x700|0x40|0x800|PXN; match permission { Permission::ReadExecute => common|0x80, Permission::ReadOnly => common|0x80|UXN, Permission::ReadWrite => common|UXN, } } impl Space { /// # Safety /// The allocator exclusively owns writable identity-mapped RAM. The kernel /// table is retained and its user branch is empty. No CPU uses the new root /// until the caller synchronizes caches and explicitly installs it. pub unsafe fn acquire(plan: Plan<'_>, file: &super::file_map::Page<'_>, content:&[u8;4096], kernel: &Tables, allocator: &mut FrameAllocator, ram_base:u64,ram_size:u64) -> Result { let ram_end=ram_base.checked_add(ram_size).ok_or(Error::Context)?; if kernel.root%4096!=0 || kernel.rootram_end) || ram_end>USER_BASE || plan.count()!=3 || file.file_bytes()!=513 || file.permissions()!=super::page_tables::descriptor::Permissions{user:true,write:false,execute:false} || unsafe{core::ptr::read_volatile((kernel.root as *const u64).add(2))}!=0 {return Err(Error::Context);} let owned=MAX_FRAMES; let mut frames=[0;MAX_FRAMES]; for index in 0..owned { let Some(address)=allocator.allocate() else { if index!=0 { // These unpublished leases were just acquired from this // allocator. A refusal means corrupted ownership; halt. unsafe{allocator.release_many_zeroed(&frames[..index])} .expect("ELF partial owner return"); } return Err(Error::OutOfFrames); }; frames[index]=address; unsafe{core::ptr::write_bytes(address as *mut u8,0,PAGE_BYTES);} } let result=(|| { unsafe{core::ptr::copy_nonoverlapping(kernel.root as *const u8,frames[0] as *mut u8,PAGE_BYTES);} unsafe{core::ptr::write_volatile((frames[0] as *mut u64).add(2),frames[1]|3);} unsafe{core::ptr::write_volatile(frames[1] as *mut u64,frames[2]|3);} for index in 0..plan.count() { let segment=plan.segment(index).ok_or(Error::Payload)?; let page=unsafe{core::slice::from_raw_parts_mut(frames[3+index] as *mut u8,PAGE_BYTES)}; plan.copy_page(index,page).map_err(|_|Error::Payload)?; let slot=((segment.page_address-USER_BASE)/4096) as usize; unsafe{core::ptr::write_volatile((frames[2] as *mut u64).add(slot),descriptor(frames[3+index],segment.permission));} } // The file page is complete before this private root can be installed. unsafe{core::ptr::copy_nonoverlapping(content.as_ptr(),frames[6] as *mut u8,PAGE_BYTES); core::ptr::write_volatile((frames[2] as *mut u64).add(32),descriptor(frames[6],Permission::ReadOnly));} let slot=((STACK_VA-USER_BASE)/4096) as usize; unsafe{core::ptr::write_volatile((frames[2] as *mut u64).add(slot),descriptor(frames[owned-1],Permission::ReadWrite));} Ok(()) })(); if let Err(error)=result { unsafe{allocator.release_many_zeroed(&frames[..owned])}.expect("ELF unpublished owner return"); return Err(error); } Ok(Self{frames,owned,entry:plan.entry(),segments:plan.count()}) } pub fn root(&self)->u64 {self.frames[0]} pub fn entry(&self)->u64 {self.entry} pub fn frames(&self)->&[u64] {&self.frames[..self.owned]} pub fn segment_frame(&self,index:usize)->Option { if index>=self.segments {None}else{Some(self.frames[index+3])} } pub fn file_frame(&self)->u64{self.frames[6]} /// # Safety /// Every CPU has switched away from this root and completed TLB invalidation. /// The allocator is the original exclusive owner and all frames are retained. pub unsafe fn release_after_tlbi(self,allocator:&mut FrameAllocator,kernel_root:u64)->Result<(),(Error,Self)> { if self.root()==kernel_root {return Err((Error::Context,self));} if unsafe{allocator.release_many_zeroed(&self.frames[..self.owned])}.is_err() { return Err((Error::Return,self)); } Ok(()) } }