pub const BOOTSTRAP_X86_64: &[u8] = include_bytes!("payload/bootstrap_x86_64.bin");
pub const BOOTSTRAP_AARCH64: &[u8] = include_bytes!("payload/bootstrap_aarch64.bin");
pub const ONELF_ENV_X86_64: &[u8] = include_bytes!("payload/onelf_env_x86_64.so");
pub const ONELF_ENV_AARCH64: &[u8] = include_bytes!("payload/onelf_env_aarch64.so");
pub const ONELF_ENV_SONAME: &str = "libonelf-env.so";
pub fn onelf_env_blob(e_machine: u16) -> Option<&'static [u8]> {
const EM_X86_64: u16 = 62;
const EM_AARCH64: u16 = 183;
let blob = match e_machine {
EM_X86_64 => ONELF_ENV_X86_64,
EM_AARCH64 => ONELF_ENV_AARCH64,
_ => return None,
};
if blob.len() < 20 || &blob[0..4] != b"\x7fELF" {
return None;
}
let m = u16::from_le_bytes([blob[18], blob[19]]);
if m != e_machine {
return None;
}
Some(blob)
}
pub const X86_64_METADATA_LEA_DISP_OFFSET: usize = 0x0d;
pub const X86_64_METADATA_LEA_RIP: usize = 0x11;
pub const AARCH64_METADATA_ADR_OFFSET: usize = 0x10;
pub fn patch_aarch64_adr(blob: &mut [u8], target_offset: usize) {
let pc = AARCH64_METADATA_ADR_OFFSET;
let offset = (target_offset as i64) - (pc as i64);
assert!(
(-1048576..=1048575).contains(&offset),
"adr offset out of range"
);
let off = offset as u32;
let immlo = off & 0x3;
let immhi = (off >> 2) & 0x7ffff;
let mut insn = u32::from_le_bytes(blob[pc..pc + 4].try_into().unwrap());
insn = (insn & 0x9f00001f) | (immlo << 29) | (immhi << 5);
blob[pc..pc + 4].copy_from_slice(&insn.to_le_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
const EM_X86_64: u16 = 62;
const EM_AARCH64: u16 = 183;
#[test]
fn blobs_are_valid_elf_for_their_machine() {
for em in [EM_X86_64, EM_AARCH64] {
let blob = onelf_env_blob(em)
.unwrap_or_else(|| panic!("onelf-env blob for EM {em} must be built/committed"));
assert_eq!(&blob[0..4], b"\x7fELF");
assert_eq!(u16::from_le_bytes([blob[18], blob[19]]), em);
}
}
#[test]
fn unknown_arch_returns_none() {
assert!(onelf_env_blob(0xffff).is_none());
}
#[test]
fn machine_mismatch_is_rejected() {
if let Some(b) = onelf_env_blob(EM_AARCH64) {
assert_eq!(u16::from_le_bytes([b[18], b[19]]), EM_AARCH64);
}
}
}