garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/programs.rs

raw

//! The programs built into the kernel image, until they come from storage:
//! an archive `cargo xtask` packs (`PPAK`, a count, then per program a
//! 16-bit name length, the name, a 32-bit size and the ELF), embedded here.

static ARCHIVE: &[u8] = include_bytes!(env!("PINNACLE_PROGRAMS"));

/// The ELF of program `name`.
pub fn find(name: &[u8]) -> Option<&'static [u8]> {
    let bytes = ARCHIVE;
    if bytes.get(..4) != Some(b"PPAK") {
        return None;
    }
    let count = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?);
    let mut at = 8;
    for _ in 0..count {
        let name_len = u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?) as usize;
        let entry_name = bytes.get(at + 2..at + 2 + name_len)?;
        at += 2 + name_len;
        let size = u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?) as usize;
        let elf = bytes.get(at + 4..at + 4 + size)?;
        at += 4 + size;
        if entry_name == name {
            return Some(elf);
        }
    }
    None
}

/// Every program's name, one a line.
pub fn names() -> alloc::vec::Vec<u8> {
    let mut out = alloc::vec::Vec::new();
    let bytes = ARCHIVE;
    let Some(count) = bytes
        .get(4..8)
        .and_then(|b| b.try_into().ok())
        .map(u32::from_le_bytes)
    else {
        return out;
    };
    let mut at = 8;
    for _ in 0..count {
        let Some(len) = bytes
            .get(at..at + 2)
            .map(|b| u16::from_le_bytes([b[0], b[1]]) as usize)
        else {
            break;
        };
        out.extend_from_slice(&bytes[at + 2..at + 2 + len]);
        out.push(b'\n');
        at += 2 + len;
        let size = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;
        at += 4 + size;
    }
    out
}