artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Linux chooses the ELF reader from the machine ABI, not from EI_CLASS alone.

use std::{
    ffi::OsStr,
    fs::File,
    io::{self, Read},
    os::unix::{ffi::OsStrExt, fs::FileExt},
    path::{Path, PathBuf},
};

/// Linux release builds support native little-endian x86-64 and AArch64.
#[cfg(target_arch = "x86_64")]
const MACHINE: u16 = 62;
#[cfg(target_arch = "aarch64")]
const MACHINE: u16 = 183;
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
const MACHINE: u16 = 0; // No native reader is declared for this target.
/// Program-header type for the loader, from the ELF ABI.
const PT_INTERP: u32 = 3;
/// The kernel bounds the interpreter name including its NUL to PATH_MAX.
const MAX_LOADER_NAME: u64 = libc::PATH_MAX as u64;
/// Native ELF64 header and program-header sizes.
const ELF_HEADER: usize = 64;
const PROGRAM_HEADER: usize = 56;
/// The kernel rejects zero or oversized tables before opening any loader.
const MAX_TABLE_BYTES: u64 = 65_536;

pub(in crate::platform) struct Loader {
    pub path: PathBuf,
    entry: u64,
}

impl Loader {
    pub fn bound_image<'a>(&self, file: &'a File, pinned: &'a Path) -> io::Result<impl Read + 'a> {
        // The original has already been sealed and checked. Only redirect the
        // kernel's pathname lookup to a sealed snapshot of its original loader.
        let path = pinned.as_os_str().as_bytes();
        let start = file.metadata()?.len().to_le_bytes();
        let length = (path.len() as u64 + 1).to_le_bytes();
        // ELF64 p_offset and p_filesz are the fields Linux reads for PT_INTERP.
        const OFFSET: u64 = 8;
        const FILE_SIZE: u64 = 32;
        const WORD: u64 = size_of::<u64>() as u64;
        let prefix = Segment::new(file, 0, self.entry + OFFSET);
        let middle = Segment::new(file, self.entry + OFFSET + WORD, FILE_SIZE - OFFSET - WORD);
        let body = Segment::new(
            file,
            self.entry + FILE_SIZE + WORD,
            u64::from_le_bytes(start) - (self.entry + FILE_SIZE + WORD),
        );
        Ok(prefix
            .chain(io::Cursor::new(start))
            .chain(middle)
            .chain(io::Cursor::new(length))
            .chain(body)
            .chain(path)
            .chain(&[0_u8][..]))
    }
}

// File clones share a seek cursor. Positional reads let each slice hold a
// separate cursor without depending on another slice's previous read length.
struct Segment<'a> {
    file: &'a File,
    offset: u64,
    remaining: u64,
}

impl<'a> Segment<'a> {
    fn new(file: &'a File, offset: u64, remaining: u64) -> Self {
        Self {
            file,
            offset,
            remaining,
        }
    }
}

impl Read for Segment<'_> {
    fn read(&mut self, data: &mut [u8]) -> io::Result<usize> {
        let limit = (data.len() as u64).min(self.remaining) as usize;
        let count = self.file.read_at(&mut data[..limit], self.offset)?;
        self.offset += count as u64;
        self.remaining -= count as u64;
        Ok(count)
    }
}

pub(in crate::platform) fn loader(file: &File) -> io::Result<Option<Loader>> {
    let mut header = [0; ELF_HEADER];
    file.read_exact_at(&mut header, 0)?;
    // Reject competing ABI or binfmt interpretations (including ELF32 compat
    // binaries); the only accepted layout is the native one checked below.
    if MACHINE == 0
        || &header[..7] != b"\x7fELF\x02\x01\x01"
        || u16_at(&header, 18) != MACHINE
        || !matches!(u16_at(&header, 16), 2 | 3) // ET_EXEC or ET_DYN
        || usize::from(u16_at(&header, 52)) != ELF_HEADER
        || usize::from(u16_at(&header, 54)) != PROGRAM_HEADER
    {
        return Err(invalid());
    }
    let table = u64_at(&header, 32);
    let size = PROGRAM_HEADER as u64;
    let count = u64::from(u16_at(&header, 56));
    let end = table.checked_add(size * count).ok_or_else(invalid)?;
    if table < ELF_HEADER as u64
        || count == 0
        || size * count > MAX_TABLE_BYTES
        || end > file.metadata()?.len()
    {
        return Err(invalid());
    }
    let mut loader = None;
    let mut program = [0; PROGRAM_HEADER];
    for entry in (table..end).step_by(PROGRAM_HEADER) {
        file.read_exact_at(&mut program, entry)?;
        if u32::from_le_bytes(program[..4].try_into().expect("ELF p_type")) != PT_INTERP {
            continue;
        }
        // One declaration, as produced by normal linkers. Reject ambiguity rather
        // than choose among duplicated entries or reinterpret an embedded NUL.
        let start = u64_at(&program, 8);
        let length = u64_at(&program, 32);
        if loader.is_some() || !(2..=MAX_LOADER_NAME).contains(&length) {
            return Err(invalid());
        }
        let mut name = vec![0; length as usize];
        file.read_exact_at(&mut name, start)?;
        let raw = name
            .strip_suffix(&[0])
            .filter(|name| !name.contains(&0))
            .ok_or_else(invalid)?;
        let path = Path::new(OsStr::from_bytes(raw)).to_owned();
        loader = Some(Loader { path, entry });
    }
    Ok(loader)
}

fn u16_at(bytes: &[u8], offset: usize) -> u16 {
    u16::from_le_bytes(bytes[offset..offset + 2].try_into().expect("ELF halfword"))
}

fn u64_at(bytes: &[u8], offset: usize) -> u64 {
    u64::from_le_bytes(
        bytes[offset..offset + 8]
            .try_into()
            .expect("ELF doubleword"),
    )
}

fn invalid() -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, "unsupported verified ELF image")
}