artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Production Darwin loads only the OS's dyld. Refuse any alternate declaration,
//! including a declaration in another architecture of a universal binary.

use std::{fs::File, io, os::unix::fs::FileExt, path::Path};

/// The signed system volume (or another superuser-controlled system root) owns dyld.
const SYSTEM_LOADER: &str = "/usr/lib/dyld";
/// Supported Mach-O image and universal container magic numbers, in file byte order.
const MACH64_LE: [u8; 4] = [0xcf, 0xfa, 0xed, 0xfe];
const FAT32_BE: [u8; 4] = [0xca, 0xfe, 0xba, 0xbe];
/// LC_LOAD_DYLINKER in mach-o/loader.h.
const LOAD_DYLINKER: u32 = 0xe;
/// Mach-O 64-bit header size, including its reserved word.
const HEADER: u64 = 32;
/// Universal header and architecture entry sizes.
const FAT_HEADER: u64 = 8;
const FAT_ENTRY: u64 = 20;
/// Require the table to fit the smallest kernel image activator page.
const FAT_TABLE_LIMIT: u64 = 4096;

pub(in crate::platform::executable::unix) fn loader(file: &File) -> io::Result<Option<File>> {
    loader_path(file)?
        .map(|path| super::trusted(path).map(|(_, file)| file))
        .transpose()
}

fn loader_path(file: &File) -> io::Result<Option<&'static Path>> {
    let len = file.metadata()?.len();
    let mut start = [0; FAT_HEADER as usize];
    file.read_exact_at(&mut start, 0)?;
    let magic: [u8; 4] = start[..4].try_into().expect("Mach-O magic");
    let needs_dyld = match magic {
        MACH64_LE => slice_loader(file, 0, len)?,
        FAT32_BE => {
            let count = u64::from(be(&start[4..]));
            let end = FAT_HEADER + count * FAT_ENTRY;
            if count == 0 || end > FAT_TABLE_LIMIT || end > len {
                return Err(invalid());
            }
            let mut needs_dyld = false;
            for location in (FAT_HEADER..end).step_by(FAT_ENTRY as usize) {
                let mut arch = [0; FAT_ENTRY as usize];
                file.read_exact_at(&mut arch, location)?;
                let offset = u64::from(be(&arch[8..12]));
                let size = u64::from(be(&arch[12..16]));
                if offset < end || offset.checked_add(size).is_none_or(|end| end > len) {
                    return Err(invalid());
                }
                needs_dyld |= slice_loader(file, offset, size)?;
            }
            needs_dyld
        }
        _ => return Err(invalid()),
    };
    Ok(needs_dyld.then(|| Path::new(SYSTEM_LOADER)))
}

fn slice_loader(file: &File, offset: u64, len: u64) -> io::Result<bool> {
    let mut header = [0; HEADER as usize];
    if len < HEADER {
        return Err(invalid());
    }
    file.read_exact_at(&mut header, offset)?;
    if header[..4] != MACH64_LE {
        return Err(invalid());
    }
    let count = u64::from(le(&header[16..20]));
    let length = u64::from(le(&header[20..24]));
    let start = offset + HEADER;
    let end = start.checked_add(length).ok_or_else(invalid)?;
    let mut position = start;
    let mut found = false;
    // Every load command has two 32-bit fields, type and total size.
    const COMMAND: u64 = 8;
    if length > len - HEADER || count > length / COMMAND {
        return Err(invalid());
    }
    for _ in 0..count {
        let mut command = [0; COMMAND as usize];
        file.read_exact_at(&mut command, position)?;
        let length = u64::from(le(&command[4..]));
        let next = position.checked_add(length).ok_or_else(invalid)?;
        if length < COMMAND || next > end {
            return Err(invalid());
        }
        if le(&command[..4]) == LOAD_DYLINKER {
            // The loader name is a command-relative NUL-terminated string.
            const NAME_OFFSET: u64 = 4;
            if found || length < COMMAND + NAME_OFFSET {
                return Err(invalid());
            }
            let mut relative = [0; NAME_OFFSET as usize];
            file.read_exact_at(&mut relative, position + COMMAND)?;
            let relative = u64::from(u32::from_le_bytes(relative));
            let mut name = [0; SYSTEM_LOADER.len() + 1];
            if relative
                .checked_add(name.len() as u64)
                .is_none_or(|last| last > length)
            {
                return Err(invalid());
            }
            file.read_exact_at(&mut name, position + relative)?;
            if name.strip_suffix(&[0]) != Some(SYSTEM_LOADER.as_bytes()) {
                return Err(invalid());
            }
            found = true;
        }
        position = next;
    }
    if position != end {
        return Err(invalid());
    }
    Ok(found)
}

fn le(bytes: &[u8]) -> u32 {
    u32::from_le_bytes(bytes.try_into().expect("Mach-O word"))
}

fn be(bytes: &[u8]) -> u32 {
    u32::from_be_bytes(bytes.try_into().expect("fat word"))
}

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