use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use object::elf::{FileHeader32, FileHeader64, PT_LOAD, SHF_ALLOC, SHT_NOBITS};
use object::read::elf::{FileHeader, ProgramHeader, SectionHeader};
use object::{Endianness, FileKind};
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ElfSegment {
pub start: u64,
pub end: u64,
pub sections: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElfImage {
pub start: u64,
pub bytes: Vec<u8>,
pub skipped: Vec<ElfSegment>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ElfError {
Invalid {
message: String,
},
OutOfMemory {
size: u64,
},
}
impl ElfError {
fn invalid(message: impl Into<String>) -> Self {
ElfError::Invalid {
message: message.into(),
}
}
fn unreadable(error: object::Error) -> Self {
ElfError::invalid(format!("it is not an ELF file that can be read: {error}"))
}
}
impl fmt::Display for ElfError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ElfError::Invalid { message } => formatter.write_str(message),
ElfError::OutOfMemory { size } => {
write!(formatter, "there is not enough memory for 0x{size:x} bytes")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElfWindow {
pub start: u64,
pub end: u64,
pub maximum_span: u64,
pub skip_from: Option<u64>,
}
const MAXIMUM_NAMES: usize = 8;
const MAXIMUM_NAME_BYTES: usize = 32;
const MAXIMUM_NAMED_SKIPPED: usize = 16;
struct NamedSection {
start: u64,
end: u64,
name: String,
}
struct Loaded<'a> {
index: usize,
start: u64,
end: u64,
virtual_start: u64,
virtual_end: u64,
data: &'a [u8],
}
impl Loaded<'_> {
fn names(&self, sections: &[NamedSection]) -> String {
let mut names = String::new();
let mut count = 0usize;
for section in sections {
if section.start < self.virtual_start || section.end > self.virtual_end {
continue;
}
if count == MAXIMUM_NAMES {
names.push_str(",...");
break;
}
if count > 0 {
names.push(',');
}
names.push_str(§ion.name);
count += 1;
}
if names.is_empty() {
names = format!("segment {}", self.index);
}
names
}
fn describe(&self, sections: &[NamedSection]) -> ElfSegment {
ElfSegment {
start: self.start,
end: self.end,
sections: self.names(sections),
}
}
}
struct Collected<'a> {
segments: Vec<Loaded<'a>>,
sections: Vec<NamedSection>,
}
fn push<T>(vector: &mut Vec<T>, item: T) -> Result<(), ElfError> {
vector.try_reserve(1).map_err(|_| ElfError::OutOfMemory {
size: (vector.len() as u64)
.saturating_add(1)
.saturating_mul(core::mem::size_of::<T>() as u64),
})?;
vector.push(item);
Ok(())
}
pub fn validate_elf(bytes: &[u8]) -> Result<(), ElfError> {
match FileKind::parse(bytes).map_err(ElfError::unreadable)? {
FileKind::Elf32 => validate::<FileHeader32<Endianness>>(bytes),
FileKind::Elf64 => validate::<FileHeader64<Endianness>>(bytes),
_ => Err(ElfError::invalid(
"it is not an ELF file that can be read: it is another kind of file",
)),
}
}
fn validate<Elf: FileHeader<Endian = Endianness>>(bytes: &[u8]) -> Result<(), ElfError> {
let header = Elf::parse(bytes).map_err(ElfError::unreadable)?;
let endian = header.endian().map_err(ElfError::unreadable)?;
let segments = header
.program_headers(endian, bytes)
.map_err(ElfError::unreadable)?;
for (index, segment) in segments.iter().enumerate() {
if segment.p_type(endian) == PT_LOAD {
segment.data(endian, bytes).map_err(|()| {
ElfError::invalid(format!(
"it is not an ELF file that can be read: the data of the segment at 0x{:x} (segment {index}) is not in the file",
segment.p_paddr(endian).into()
))
})?;
}
}
let sections = header
.sections(endian, bytes)
.map_err(ElfError::unreadable)?;
for section in sections.iter() {
section
.data(endian, bytes)
.map_err(|error| {
ElfError::invalid(format!(
"it is not an ELF file that can be read: the data of the section at 0x{:x}: {error}",
section.sh_addr(endian).into()
))
})?;
}
Ok(())
}
pub fn is_avr_elf(bytes: &[u8]) -> bool {
const EM_AVR: u16 = 83;
if !super::is_elf(bytes) {
return false;
}
let machine = bytes
.get(18..20)
.and_then(|field| <[u8; 2]>::try_from(field).ok());
match (bytes.get(5), machine) {
(Some(1), Some(field)) => u16::from_le_bytes(field) == EM_AVR,
(Some(2), Some(field)) => u16::from_be_bytes(field) == EM_AVR,
_ => false,
}
}
pub fn decode_elf(bytes: &[u8], window: &ElfWindow) -> Result<ElfImage, ElfError> {
let collected = match FileKind::parse(bytes).map_err(ElfError::unreadable)? {
FileKind::Elf32 => collect::<FileHeader32<Endianness>>(bytes)?,
FileKind::Elf64 => collect::<FileHeader64<Endianness>>(bytes)?,
_ => {
return Err(ElfError::invalid(
"it is not an ELF file that can be read: it is another kind of file",
));
}
};
let Collected { segments, sections } = collected;
let mut skipped = Vec::new();
let mut written = Vec::new();
for segment in segments {
if window.skip_from.is_some_and(|from| segment.start >= from) {
let names: &[NamedSection] = if skipped.len() < MAXIMUM_NAMED_SKIPPED {
§ions
} else {
&[]
};
push(&mut skipped, segment.describe(names))?;
} else {
push(&mut written, segment)?;
}
}
for segment in &written {
if segment.start < window.start || segment.end > window.end {
return Err(ElfError::invalid(format!(
"its segment 0x{:x}..0x{:x} ({}) is outside the flash, mapped at 0x{:x}..0x{:x}: link it for the flash (memory.x), or fix the base address of the layout",
segment.start,
segment.end,
segment.names(§ions),
window.start,
window.end
)));
}
}
written.sort_unstable_by_key(|segment| (segment.start, segment.end));
for pair in written.windows(2) {
if let [first, second] = pair
&& second.start < first.end
{
return Err(ElfError::invalid(format!(
"its segments 0x{:x}..0x{:x} ({}) and 0x{:x}..0x{:x} ({}) overlap",
first.start,
first.end,
first.names(§ions),
second.start,
second.end,
second.names(§ions)
)));
}
}
let (Some(first), Some(last)) = (written.first(), written.last()) else {
return Err(ElfError::invalid(
"it has no segment to load (no PT_LOAD segment with data)",
));
};
let start = first.start;
let end = last.end;
let span = end.checked_sub(start).ok_or_else(|| {
ElfError::invalid(format!(
"its segments 0x{start:x}..0x{end:x} are not in increasing order"
))
})?;
if span > window.maximum_span {
return Err(ElfError::invalid(format!(
"its segments span 0x{start:x}..0x{end:x}, 0x{span:x} bytes, more than the 0x{:x} bytes it may span",
window.maximum_span
)));
}
let size = usize::try_from(span).map_err(|_| ElfError::OutOfMemory { size: span })?;
let mut image = Vec::new();
image
.try_reserve_exact(size)
.map_err(|_| ElfError::OutOfMemory { size: span })?;
image.resize(size, 0xFF);
for segment in &written {
let offset = segment
.start
.checked_sub(start)
.and_then(|offset| usize::try_from(offset).ok())
.ok_or(ElfError::OutOfMemory { size: span })?;
if let Some(target) = image
.get_mut(offset..)
.and_then(|rest| rest.get_mut(..segment.data.len()))
{
target.copy_from_slice(segment.data);
}
}
Ok(ElfImage {
start,
bytes: image,
skipped,
})
}
fn collect<Elf: FileHeader<Endian = Endianness>>(bytes: &[u8]) -> Result<Collected<'_>, ElfError> {
let header = Elf::parse(bytes).map_err(ElfError::unreadable)?;
let endian = header.endian().map_err(ElfError::unreadable)?;
let segments = header
.program_headers(endian, bytes)
.map_err(ElfError::unreadable)?;
let mut named = Vec::new();
if let Ok(table) = header.sections(endian, bytes) {
for section in table.iter() {
let start: u64 = section.sh_addr(endian).into();
let size: u64 = section.sh_size(endian).into();
if section.sh_flags(endian).0 & SHF_ALLOC.0 == 0
|| section.sh_type(endian) == SHT_NOBITS
|| size == 0
{
continue;
}
let (Some(end), Ok(name)) =
(start.checked_add(size), table.section_name(endian, section))
else {
continue;
};
let name = name.get(..MAXIMUM_NAME_BYTES).unwrap_or(name);
push(
&mut named,
NamedSection {
start,
end,
name: String::from_utf8_lossy(name).into_owned(),
},
)?;
}
}
let mut loaded = Vec::new();
for (index, segment) in segments.iter().enumerate() {
if segment.p_type(endian) != PT_LOAD {
continue;
}
let file_size: u64 = segment.p_filesz(endian).into();
if file_size == 0 {
continue;
}
let address: u64 = segment.p_paddr(endian).into();
let data = segment.data(endian, bytes).map_err(|()| {
ElfError::invalid(format!(
"it is not an ELF file that can be read: the data of the segment at 0x{address:x} (segment {index}) is not in the file"
))
})?;
let end = address.checked_add(file_size).ok_or_else(|| {
ElfError::invalid(format!(
"its segment at 0x{address:x} (segment {index}) ends beyond the 64-bit address space"
))
})?;
let virtual_start: u64 = segment.p_vaddr(endian).into();
let virtual_end = virtual_start.saturating_add(segment.p_memsz(endian).into());
push(
&mut loaded,
Loaded {
index,
start: address,
end,
virtual_start,
virtual_end,
data,
},
)?;
}
Ok(Collected {
segments: loaded,
sections: named,
})
}
#[cfg(test)]
pub(crate) mod writer {
use alloc::vec;
use alloc::vec::Vec;
pub(crate) const PT_LOAD: u32 = 1;
pub(crate) const PT_NOTE: u32 = 4;
pub(crate) const EM_ARM: u16 = 40;
pub(crate) const EM_AVR: u16 = 83;
pub(crate) const EM_XTENSA: u16 = 94;
#[derive(Clone)]
pub(crate) struct Segment<'a> {
pub(crate) p_type: u32,
pub(crate) paddr: u64,
pub(crate) vaddr: u64,
pub(crate) data: &'a [u8],
pub(crate) memsz: u64,
pub(crate) name: &'a str,
pub(crate) flags: &'a str,
}
pub(crate) fn segment<'a>(
paddr: u64,
vaddr: u64,
data: &'a [u8],
memsz: u64,
name: &'a str,
flags: &'a str,
) -> Segment<'a> {
Segment {
p_type: PT_LOAD,
paddr,
vaddr,
data,
memsz,
name,
flags,
}
}
pub(crate) fn simple<'a>(address: u64, data: &'a [u8], name: &'a str) -> Segment<'a> {
segment(address, address, data, data.len() as u64, name, "AX")
}
pub(crate) fn write_elf(
is_64: bool,
big_endian: bool,
machine: u16,
entry: u64,
segments: &[Segment<'_>],
) -> Vec<u8> {
struct Out {
bytes: Vec<u8>,
big: bool,
}
impl Out {
fn u16(&mut self, value: u16) {
let b = if self.big {
value.to_be_bytes()
} else {
value.to_le_bytes()
};
self.bytes.extend_from_slice(&b);
}
fn u32(&mut self, value: u32) {
let b = if self.big {
value.to_be_bytes()
} else {
value.to_le_bytes()
};
self.bytes.extend_from_slice(&b);
}
fn u64(&mut self, value: u64) {
let b = if self.big {
value.to_be_bytes()
} else {
value.to_le_bytes()
};
self.bytes.extend_from_slice(&b);
}
fn word(&mut self, is_64: bool, value: u64) {
if is_64 {
self.u64(value);
} else {
self.u32(value as u32);
}
}
}
let header_size: u64 = if is_64 { 64 } else { 52 };
let program_size: u64 = if is_64 { 56 } else { 32 };
let section_size: u64 = if is_64 { 64 } else { 40 };
let named: Vec<&Segment<'_>> = segments.iter().filter(|s| !s.name.is_empty()).collect();
let mut offset = header_size + program_size * segments.len() as u64;
let mut data_offsets = Vec::new();
for segment in segments {
data_offsets.push(offset);
offset += segment.data.len() as u64;
}
let mut names = vec![0u8];
let mut name_offsets = Vec::new();
for segment in &named {
name_offsets.push(names.len() as u32);
names.extend_from_slice(segment.name.as_bytes());
names.push(0);
}
let shstrtab_name = names.len() as u32;
names.extend_from_slice(b".shstrtab\0");
let names_offset = offset;
offset += names.len() as u64;
let section_headers_offset = offset;
let section_count = named.len() as u16 + 2;
let mut out = Out {
bytes: Vec::new(),
big: big_endian,
};
out.bytes
.extend_from_slice(&[0x7f, b'E', b'L', b'F', if is_64 { 2 } else { 1 }]);
out.bytes.push(if big_endian { 2 } else { 1 });
out.bytes.push(1);
out.bytes.resize(16, 0);
out.u16(2);
out.u16(machine);
out.u32(1);
out.word(is_64, entry);
out.word(is_64, header_size);
out.word(is_64, section_headers_offset);
out.u32(0);
out.u16(header_size as u16);
out.u16(program_size as u16);
out.u16(segments.len() as u16);
out.u16(section_size as u16);
out.u16(section_count);
out.u16(section_count - 1);
for (segment, data_offset) in segments.iter().zip(&data_offsets) {
let flags = 4 | if segment.flags.contains('X') { 1 } else { 0 };
let flags = flags | if segment.flags.contains('W') { 2 } else { 0 };
if is_64 {
out.u32(segment.p_type);
out.u32(flags);
out.u64(*data_offset);
out.u64(segment.vaddr);
out.u64(segment.paddr);
out.u64(segment.data.len() as u64);
out.u64(segment.memsz);
out.u64(4);
} else {
out.u32(segment.p_type);
out.u32(*data_offset as u32);
out.u32(segment.vaddr as u32);
out.u32(segment.paddr as u32);
out.u32(segment.data.len() as u32);
out.u32(segment.memsz as u32);
out.u32(flags);
out.u32(4);
}
}
for segment in segments {
out.bytes.extend_from_slice(segment.data);
}
out.bytes.extend_from_slice(&names);
let section = |out: &mut Out,
name: u32,
kind: u32,
flags: u64,
address: u64,
offset: u64,
size: u64| {
out.u32(name);
out.u32(kind);
out.word(is_64, flags);
out.word(is_64, address);
out.word(is_64, offset);
out.word(is_64, size);
out.u32(0);
out.u32(0);
out.word(is_64, 4);
out.word(is_64, 0);
};
section(&mut out, 0, 0, 0, 0, 0, 0);
for (segment, name_offset) in named.iter().zip(&name_offsets) {
let index = segments
.iter()
.position(|candidate| core::ptr::eq(candidate, *segment))
.unwrap();
let nobits = segment.data.is_empty();
let mut flags = 2u64;
if segment.flags.contains('X') {
flags |= 4;
}
if segment.flags.contains('W') {
flags |= 1;
}
section(
&mut out,
*name_offset,
if nobits { 8 } else { 1 },
flags,
segment.vaddr,
data_offsets[index],
if nobits {
segment.memsz
} else {
segment.data.len() as u64
},
);
}
section(
&mut out,
shstrtab_name,
3,
0,
0,
names_offset,
names.len() as u64,
);
out.bytes
}
pub(crate) fn elf32(machine: u16, entry: u64, segments: &[Segment<'_>]) -> Vec<u8> {
write_elf(false, false, machine, entry, segments)
}
}
#[cfg(test)]
mod tests {
use super::writer::*;
use super::*;
use alloc::string::ToString;
use alloc::vec;
use proptest::collection::vec as proptest_vec;
use proptest::prelude::*;
use std::path::PathBuf;
const APPLICATION_BIN: &[u8] = include_bytes!("../../tests/images/application.bin");
fn fixture(name: &str) -> Vec<u8> {
std::fs::read(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/images")
.join(name),
)
.unwrap()
}
fn window(start: u64, end: u64) -> ElfWindow {
ElfWindow {
start,
end,
maximum_span: 0x200_0000,
skip_from: None,
}
}
fn application_segments() -> Vec<Segment<'static>> {
vec![
segment(
0x10000,
0x10000,
&APPLICATION_BIN[..0x1000],
0x1000,
".text",
"AX",
),
segment(
0x11000,
0x2000_0000,
&APPLICATION_BIN[0x1000..],
0x1000,
".data",
"WA",
),
segment(0x12000, 0x2000_1000, &[], 0x100, ".bss", "WA"),
Segment {
p_type: PT_NOTE,
paddr: 0,
vaddr: 0,
data: &[],
memsz: 0,
name: "",
flags: "",
},
]
}
fn avr_hex_image() -> Vec<u8> {
let hex = include_bytes!("../../tests/images/avr-application.hex");
crate::flash::decode_intel_hex(hex, 0x10_0000)
.unwrap()
.bytes
}
fn esp32s3_segments() -> Vec<Segment<'static>> {
static BYTES: [u8; 64] = {
let mut bytes = [0u8; 64];
let mut index = 0;
while index < 64 {
bytes[index] = index as u8;
index += 1;
}
bytes
};
vec![
segment(0x3C00_0020, 0x3C00_0020, &BYTES, 64, ".flash.rodata", "A"),
segment(0x4200_0020, 0x4200_0020, &BYTES, 64, ".flash.text", "AX"),
segment(
0x4037_8000,
0x4037_8000,
&BYTES[..32],
32,
".iram0.text",
"AX",
),
segment(
0x3FC8_8000,
0x3FC8_8000,
&BYTES[..16],
16,
".dram0.data",
"WA",
),
]
}
fn fixture_files() -> Vec<(&'static str, Vec<u8>)> {
let mut avr = vec![simple(0, &[], ".text")];
let image = avr_hex_image();
avr[0].data = ℑ
avr[0].memsz = image.len() as u64;
let eeprom = [1u8, 2, 3, 4];
avr.push(segment(0x81_0000, 0x81_0000, &eeprom, 4, ".eeprom", "WA"));
vec![
(
"application.elf",
elf32(EM_ARM, 0x10101, &application_segments()),
),
(
"avr-application.elf",
write_elf(false, false, EM_AVR, 0, &avr),
),
(
"esp32s3-application.elf",
elf32(EM_XTENSA, 0x4037_8000, &esp32s3_segments()),
),
]
}
#[test]
fn committed_fixtures_are_current() {
let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/images");
for (name, bytes) in fixture_files() {
let path = directory.join(name);
if std::env::var_os("NANOFLASH_UPDATE_FIXTURES").is_some() {
std::fs::write(&path, &bytes).unwrap();
}
let committed = std::fs::read(&path).unwrap();
assert!(
committed == bytes,
"{name} is out of date: run with NANOFLASH_UPDATE_FIXTURES=1"
);
}
}
#[test]
fn loads_segments_at_their_physical_address() {
let image = decode_elf(&fixture("application.elf"), &window(0, 0x10_0000)).unwrap();
assert_eq!(
(image.start, image.bytes.as_slice()),
(0x10000, APPLICATION_BIN)
);
assert!(image.skipped.is_empty());
}
#[test]
fn gaps_read_as_erased_flash() {
let file = elf32(
EM_ARM,
0,
&[
simple(0x10000, &[1, 2, 3, 4], ".a"),
simple(0x10008, &[5, 6, 7, 8], ".b"),
],
);
let image = decode_elf(&file, &window(0, 0x10_0000)).unwrap();
assert_eq!(image.start, 0x10000);
assert_eq!(
image.bytes,
[1, 2, 3, 4, 0xFF, 0xFF, 0xFF, 0xFF, 5, 6, 7, 8]
);
}
#[test]
fn avr_spaces_are_skipped() {
let options = ElfWindow {
skip_from: Some(0x80_0000),
..window(0, 0x8000)
};
let image = decode_elf(&fixture("avr-application.elf"), &options).unwrap();
assert_eq!(image.start, 0);
assert_eq!(image.bytes, avr_hex_image());
assert_eq!(
image.skipped,
[ElfSegment {
start: 0x81_0000,
end: 0x81_0004,
sections: ".eeprom".into()
}]
);
let error = decode_elf(&fixture("avr-application.elf"), &window(0, 0x8000)).unwrap_err();
assert!(error.to_string().contains("0x810000"), "{error}");
}
fn message(file: &[u8], options: &ElfWindow) -> String {
decode_elf(file, options).unwrap_err().to_string()
}
#[test]
fn refusals_name_sections_and_addresses() {
let overlap = elf32(
EM_ARM,
0,
&[
simple(0x10000, &[0; 0x10], ".a"),
simple(0x10008, &[0; 0x10], ".b"),
],
);
let text = message(&overlap, &window(0, 0x10_0000));
assert!(text.contains("0x10000..0x10010 (.a)"), "{text}");
assert!(text.contains("0x10008..0x10018 (.b)"), "{text}");
assert!(text.contains("overlap"), "{text}");
let ram = elf32(
EM_ARM,
0,
&[segment(0x2000_0000, 0x2000_0000, &[1; 4], 4, ".data", "WA")],
);
let text = message(&ram, &window(0, 0x10_0000));
assert!(text.contains("0x20000000"), "{text}");
assert!(text.contains("(.data)"), "{text}");
assert!(text.contains("outside the flash"), "{text}");
let low = elf32(EM_ARM, 0, &[simple(0x1000, &[1; 4], ".text")]);
let text = message(&low, &window(0x800_0000, 0x810_0000));
assert!(
text.contains("outside the flash, mapped at 0x8000000..0x8100000"),
"{text}"
);
let wide = elf32(
EM_ARM,
0,
&[simple(0, &[1], ".a"), simple(0x200_0000, &[1], ".b")],
);
let text = message(&wide, &window(0, u64::MAX));
assert!(
text.contains("span 0x0..0x2000001, 0x2000001 bytes, more than the 0x2000000 bytes"),
"{text}"
);
let bss = elf32(
EM_ARM,
0,
&[segment(0x10000, 0x10000, &[], 0x100, ".bss", "WA")],
);
assert!(message(&bss, &window(0, 0x10_0000)).contains("no segment to load"));
let text = message(b"\x7fELF", &window(0, 0x10_0000));
assert!(text.starts_with("it is not an ELF file"), "{text}");
assert!(message(&[], &window(0, 0x10_0000)).starts_with("it is not an ELF file"));
}
#[test]
fn sections_are_named_by_virtual_address() {
let file = elf32(
EM_ARM,
0,
&[
segment(0x10000, 0x2000_0000, &[1; 4], 4, ".data", "WA"),
segment(0x10010, 0x3000_0000, &[1; 4], 4, "", "WA"),
simple(0x10008, &[2; 4], ".text"),
simple(0x10010, &[2; 4], ".more"),
],
);
let text = message(&file, &window(0, 0x10_0000));
assert!(text.contains("0x10010..0x10014 (segment 1)"), "{text}");
let text = message(&file, &window(0x20000, 0x30000));
assert!(text.contains("(.data)"), "{text}");
}
#[test]
fn section_names_are_bounded() {
let long = "n".repeat(4000);
let data = [1u8; 4];
let mut segments = vec![
segment(0x100, 0x100, &data, 0xFFFF_FFFF, ".text", "AX"),
segment(0x10000, 0, &data, 0xFFFF_FFFF, "", "AX"),
];
for index in 0..200u64 {
segments.push(segment(
0x20000 + index * 4,
0x1000 + index * 4,
&data,
4,
&long,
"AX",
));
}
let file = write_elf(false, false, EM_ARM, 0, &segments);
let options = ElfWindow {
skip_from: Some(0x10000),
..window(0, 0x1000)
};
let image = decode_elf(&file, &options).unwrap();
let text = &image.skipped[0].sections;
assert!(text.len() < 600, "{} bytes: {text}", text.len());
assert!(text.ends_with(",..."), "{text}");
assert!(text.contains(&"n".repeat(32)), "{text}");
assert!(!text.contains(&"n".repeat(33)), "{text}");
let text = message(&file, &window(0, 0x10));
assert!(text.len() < 600, "{} bytes: {text}", text.len());
assert!(text.contains(",..."), "{text}");
}
#[test]
fn only_the_first_skipped_segments_are_named() {
let data = [1u8; 4];
let names: Vec<String> = (0..3000).map(|index| alloc::format!(".s{index}")).collect();
let mut segments = vec![segment(0x100, 0x100, &data, 4, ".text", "AX")];
for (index, name) in names.iter().enumerate() {
let index = index as u64;
segments.push(segment(
0x10000 + index * 4,
0x1000 + index * 4,
&data,
4,
name,
"AX",
));
}
let file = write_elf(false, false, EM_AVR, 0, &segments);
let options = ElfWindow {
skip_from: Some(0x10000),
..window(0, 0x1000)
};
let image = decode_elf(&file, &options).unwrap();
assert_eq!(image.skipped.len(), 3000);
for (index, segment) in image.skipped.iter().enumerate() {
if index < 16 {
assert_eq!(segment.sections, alloc::format!(".s{index}"));
} else {
assert_eq!(segment.sections, alloc::format!("segment {}", index + 1));
}
}
}
#[test]
fn sixty_four_bit_and_big_endian_files_are_read() {
let expected = decode_elf(&fixture("application.elf"), &window(0, 0x10_0000)).unwrap();
for (is_64, big) in [(true, false), (false, true), (true, true)] {
let file = write_elf(is_64, big, EM_ARM, 0x10101, &application_segments());
assert_eq!(
decode_elf(&file, &window(0, 0x10_0000)).unwrap(),
expected,
"64-bit {is_64}, big endian {big}"
);
validate_elf(&file).unwrap();
}
}
#[test]
fn the_espressif_fixture_is_valid() {
let file = elf32(EM_XTENSA, 0x4037_8000, &esp32s3_segments());
validate_elf(&file).unwrap();
let text = message(&file, &window(0, 0x100_0000));
assert!(text.contains("(.flash.rodata)"), "{text}");
}
#[test]
fn validation_refuses_ranges_outside_the_file() {
let mut file = elf32(EM_ARM, 0, &[simple(0x10000, &[1; 16], ".text")]);
validate_elf(&file).unwrap();
file.truncate(file.len() - 100);
assert!(validate_elf(&file).is_err());
assert!(decode_elf(&file, &window(0, 0x10_0000)).is_ok());
file.truncate(52 + 32 + 8);
assert!(validate_elf(&file).is_err());
assert!(decode_elf(&file, &window(0, 0x10_0000)).is_err());
}
#[test]
fn a_file_is_an_elf_by_its_magic() {
assert!(crate::flash::is_elf(&fixture("application.elf")));
assert!(!crate::flash::is_elf(b":10000000"));
assert!(!crate::flash::is_elf(b""));
}
proptest! {
#[test]
fn arbitrary_bytes_never_panic(bytes in proptest_vec(any::<u8>(), 0..4096)) {
let _ = decode_elf(&bytes, &window(0, 0x10_0000));
let _ = validate_elf(&bytes);
}
#[test]
fn mutated_fixtures_never_panic(
index in any::<usize>(),
value in any::<u8>(),
truncate in any::<usize>(),
) {
let mut file = fixture("application.elf");
let length = file.len();
file[index % length] = value;
file.truncate(truncate % (length + 1));
let options = window(0, 0x10_0000);
if let Ok(image) = decode_elf(&file, &options) {
prop_assert!(image.bytes.len() as u64 <= options.maximum_span);
}
let _ = validate_elf(&file);
}
#[test]
fn mutated_headers_never_panic(
index in 0usize..0x200,
value in any::<u8>(),
) {
let mut file = fixture("application.elf");
let index = index.min(file.len() - 1);
file[index] = value;
let options = window(0, u64::MAX);
if let Ok(image) = decode_elf(&file, &options) {
prop_assert!(image.bytes.len() as u64 <= options.maximum_span);
}
let _ = validate_elf(&file);
}
}
#[test]
fn avr_files_are_found_by_their_machine() {
let avr = write_elf(false, false, EM_AVR, 0, &[simple(0, &[1; 4], ".text")]);
assert!(is_avr_elf(&avr));
let big_endian = write_elf(false, true, EM_AVR, 0, &[simple(0, &[1; 4], ".text")]);
assert!(is_avr_elf(&big_endian));
let arm = write_elf(false, false, EM_ARM, 0, &[simple(0, &[1; 4], ".text")]);
assert!(!is_avr_elf(&arm));
assert!(!is_avr_elf(&avr[..19]));
assert!(!is_avr_elf(&[]));
let mut other = avr.clone();
other[0] = 0;
assert!(!is_avr_elf(&other));
}
}