git clone https://garage44.eu/jeroen/pinnacle.git.. /kernel/src/process.rs
//! Programs: an ELF image loaded into an address space of its own and run
//! in user mode (EL0) as a task.
use crate::mm::PAGE;
use crate::mm::space::{Access, AddressSpace, OutOfMemory, USER_TOP};
/// Every program's stack: 64 KiB just below the top of the lower half,
/// growing a page at a time as it is first touched ([`grow_stack`]) to
/// [`STACK_MOST`].
const STACK_PAGES: usize = 16;
pub const STACK_TOP: usize = USER_TOP - PAGE;
/// How far a program's main stack may grow: Linux's usual 8 MiB, which
/// std programs are written for (Cartopolis's first frame takes over 64 KiB).
const STACK_MOST: usize = 8 << 20;
/// Maps a zeroed page at `va` if it is in the main stack's reach and not
/// yet mapped: a program's fault there is its stack growing. Whether the
/// page is there now.
pub fn grow_stack(space: &mut AddressSpace, va: usize) -> bool {
if !(STACK_TOP - STACK_MOST..STACK_TOP).contains(&va) {
return false;
}
let page = va & !(PAGE - 1);
if space.allows(page, 1, true) {
// Another thread's fault mapped it first.
return true;
}
let Some(frame) = crate::mm::pages::alloc(0) else {
return false;
};
// SAFETY: just allocated, ours alone.
unsafe { core::ptr::write_bytes(frame as *mut u8, 0, PAGE) };
if space.map(page, frame, Access::ReadWrite).is_err() {
crate::mm::pages::free(frame, 0);
return false;
}
crate::arch::tables_written();
true
}
#[derive(Debug)]
pub enum Error {
NotAnElf,
Segment,
OutOfMemory,
}
impl From<OutOfMemory> for Error {
fn from(_: OutOfMemory) -> Self {
Error::OutOfMemory
}
}
fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {
Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?))
}
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?))
}
fn u64_at(bytes: &[u8], at: usize) -> Option<usize> {
Some(u64::from_le_bytes(bytes.get(at..at + 8)?.try_into().ok()?) as usize)
}
/// Where a program's ELF is read from, a range at a time: a program built
/// in is all in memory, an installed one is read from its disk as it loads
/// (a large one would not fit in one allocation of the kernel's).
pub trait Image {
/// The `len` bytes at `offset`; None when they are not all there.
fn read(&mut self, offset: usize, len: usize) -> Option<alloc::borrow::Cow<'_, [u8]>>;
}
impl Image for &[u8] {
fn read(&mut self, offset: usize, len: usize) -> Option<alloc::borrow::Cow<'_, [u8]>> {
self.get(offset..offset.checked_add(len)?)
.map(alloc::borrow::Cow::Borrowed)
}
}
/// An installed program's ELF, read from its file on a disk.
pub struct OnDisk<'p>(pub &'p str);
impl Image for OnDisk<'_> {
fn read(&mut self, offset: usize, len: usize) -> Option<alloc::borrow::Cow<'_, [u8]>> {
let bytes =
crate::drivers::block::with_disk(self.0, |fs, p| fs.read_at(p, offset as u64, len as u64))?
.ok()?;
(bytes.len() == len).then_some(alloc::borrow::Cow::Owned(bytes))
}
}
/// How much of a segment is read at a time.
const CHUNK: usize = 1 << 20;
/// Copies an ELF's loadable segments into `space`, each on pages of its own
/// with the access its flags give, maps the stack, and returns the entry.
/// The ELF is read a range at a time, never whole.
pub fn load(elf: &mut dyn Image, space: &mut AddressSpace) -> Result<usize, Error> {
const PT_LOAD: u32 = 1;
const PF_X: u32 = 1;
const PF_W: u32 = 2;
let header = elf.read(0, 64).ok_or(Error::NotAnElf)?.into_owned();
if header.get(..4) != Some(b"\x7fELF")
|| header.get(4) != Some(&2)
|| u16_at(&header, 18) != Some(crate::arch::ELF_MACHINE)
{
return Err(Error::NotAnElf);
}
let entry = u64_at(&header, 24).ok_or(Error::NotAnElf)?;
let phoff = u64_at(&header, 32).ok_or(Error::NotAnElf)?;
let phentsize = u16_at(&header, 54).ok_or(Error::NotAnElf)? as usize;
let phnum = u16_at(&header, 56).ok_or(Error::NotAnElf)? as usize;
let table = elf
.read(phoff, phnum * phentsize)
.ok_or(Error::NotAnElf)?
.into_owned();
for i in 0..phnum {
let header = i * phentsize;
if u32_at(&table, header) != Some(PT_LOAD) {
continue;
}
let flags = u32_at(&table, header + 4).ok_or(Error::Segment)?;
let offset = u64_at(&table, header + 8).ok_or(Error::Segment)?;
let va = u64_at(&table, header + 16).ok_or(Error::Segment)?;
let file_size = u64_at(&table, header + 32).ok_or(Error::Segment)?;
let memory_size = u64_at(&table, header + 40).ok_or(Error::Segment)?;
if !va.is_multiple_of(PAGE) || va.checked_add(memory_size).is_none_or(|end| end > STACK_TOP) {
return Err(Error::Segment);
}
let access = match (flags & PF_X != 0, flags & PF_W != 0) {
(true, false) => Access::ReadExecute,
(false, false) => Access::Read,
(false, true) => Access::ReadWrite,
(true, true) => return Err(Error::Segment),
};
// A chunk of the file at a time (pages, CHUNK apart), its pages
// filled from it; past the file's bytes, zeros.
for chunk in (0..memory_size).step_by(CHUNK) {
let in_file = file_size.saturating_sub(chunk).min(CHUNK);
let bytes = match in_file {
0 => alloc::borrow::Cow::Borrowed(&[][..]),
n => elf.read(offset + chunk, n).ok_or(Error::Segment)?,
};
for page_offset in (chunk..(chunk + CHUNK).min(memory_size)).step_by(PAGE) {
let page = crate::mm::pages::alloc(0).ok_or(Error::OutOfMemory)?;
let from = bytes.get(page_offset - chunk..).unwrap_or(&[]);
let copied = from.len().min(PAGE);
// SAFETY: a page just allocated, ours alone.
unsafe {
core::ptr::copy_nonoverlapping(from.as_ptr(), page as *mut u8, copied);
core::ptr::write_bytes((page + copied) as *mut u8, 0, PAGE - copied);
}
if access == Access::ReadExecute {
make_executable(page);
}
space.map(va + page_offset, page, access)?;
}
}
}
for page in 0..STACK_PAGES {
let frame = crate::mm::pages::alloc(0).ok_or(Error::OutOfMemory)?;
space.map(STACK_TOP - (page + 1) * PAGE, frame, Access::ReadWrite)?;
}
crate::arch::tables_written();
Ok(entry)
}
/// Code written through the data cache must reach the instruction cache.
fn make_executable(page: usize) {
crate::arch::make_executable(page, PAGE);
}