use std::collections::HashMap;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SymKind {
Func,
Object,
Other,
}
#[derive(Clone, Debug)]
pub struct Symbol {
pub name: String,
pub addr: u32,
pub size: u32,
pub kind: SymKind,
pub global: bool,
pub file: Option<String>,
}
#[derive(Clone, Debug)]
pub struct Segment {
pub name: String,
pub addr: u32,
pub data: Vec<u8>,
pub writable: bool,
pub exec: bool,
pub load_addr: Option<u32>,
}
#[derive(Clone, Default, Debug)]
pub struct Image {
pub segments: Vec<Segment>,
pub symbols: Vec<Symbol>,
pub externals: HashMap<u32, String>,
pub data_ranges: Vec<(u32, u32)>,
pub comment: Option<String>,
pub producer: Option<String>,
pub short_enums: Option<bool>,
pub static_base: Option<u32>,
pub rwpi: bool,
pub needs_static_base: bool,
pub owners: Vec<(u32, String)>,
pub meta: ElfMeta,
pub hard_float: bool,
pub soft_bounds: bool,
pub set_aside: Vec<(u32, u32, String)>,
}
pub const OBJECT_STATIC_BASE: u32 = 0x2000_0000;
fn u16le(b: &[u8], o: usize) -> u32 {
u16::from_le_bytes([b[o], b[o + 1]]) as u32
}
fn u32le(b: &[u8], o: usize) -> u32 {
u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
}
fn cstr(b: &[u8], o: usize) -> String {
let end = b[o.min(b.len())..]
.iter()
.position(|&c| c == 0)
.map_or(b.len(), |p| o + p);
String::from_utf8_lossy(&b[o.min(b.len())..end]).into_owned()
}
fn load_view(bytes: &[u8], secs: &[Section], img: &mut Image) -> Result<(), String> {
let (phoff, phentsize, phnum) = (
u32le(bytes, 28) as usize,
u16le(bytes, 42) as usize,
u16le(bytes, 44) as usize,
);
if phoff == 0 || phnum == 0 {
return Ok(());
}
if phentsize < 32 || phoff + phnum * phentsize > bytes.len() {
return Err("ELF program headers extend past the end of the file".into());
}
let mut loads: Vec<(u64, u64, u64, bool)> = Vec::new();
for i in 0..phnum {
let o = phoff + i * phentsize;
if u32le(bytes, o) != 1 {
continue;
}
let (off, vaddr, filesz) = (
u32le(bytes, o + 4) as u64,
u32le(bytes, o + 8) as u64,
u32le(bytes, o + 16) as u64,
);
if filesz == 0 {
continue;
}
if off + filesz > bytes.len() as u64 {
return Err("ELF load segment extends past the end of the file".into());
}
if loads.iter().any(|l| vaddr < l.1 + l.2 && l.1 < vaddr + filesz) {
return Err("ELF load segments overlap".into());
}
loads.push((off, vaddr, filesz, u32le(bytes, o + 24) & 1 != 0));
}
if loads.is_empty() {
return Ok(());
}
let mut described: Vec<(u64, u64)> = Vec::new();
for s in secs {
if s.flags & SHF_ALLOC == 0 || s.size == 0 || s.flags & 0x400 != 0 {
continue;
}
let (a, e) = (s.addr as u64, s.addr as u64 + s.size as u64);
if described.iter().any(|d| a < d.1 && d.0 < e) {
return Err(format!("section {} overlaps another section", s.name));
}
described.push((a, e));
if s.ty == SHT_NOBITS {
continue;
}
let same = loads
.iter()
.any(|l| a >= l.1 && e <= l.1 + l.2 && l.0 + (a - l.1) == s.offset as u64);
if !same {
return Err(format!(
"section {} does not hold the bytes the program headers load at {:#x}",
s.name, s.addr
));
}
}
described.sort_unstable();
for (n, &(off, vaddr, filesz, exec)) in loads.iter().enumerate() {
if !exec {
continue;
}
let mut at = vaddr;
let end = vaddr + filesz;
let mut gaps = Vec::new();
for &(a, e) in &described {
if e <= at || a >= end {
continue;
}
if a > at {
gaps.push((at, a));
}
at = at.max(e);
}
if at < end {
gaps.push((at, end));
}
for (a, e) in gaps {
let o = (off + (a - vaddr)) as usize;
img.segments.push(Segment {
name: format!("<load segment {n}, no section>"),
addr: a as u32,
data: bytes[o..o + (e - a) as usize].to_vec(),
writable: false,
exec: true,
load_addr: None,
});
}
}
Ok(())
}
struct Section {
name: String,
ty: u32,
flags: u32,
addr: u32,
offset: usize,
size: usize,
link: u32,
info: u32,
align: u32,
}
const SHT_PROGBITS: u32 = 1;
const SHT_SYMTAB: u32 = 2;
const SHT_NOBITS: u32 = 8;
const SHT_REL: u32 = 9;
const SHT_INIT_ARRAY: u32 = 14;
const SHF_WRITE: u32 = 1;
const SHF_ALLOC: u32 = 2;
const SHF_EXEC: u32 = 4;
impl Image {
pub fn is_elf(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x7fELF")
}
pub fn from_elf(bytes: &[u8]) -> Result<Image, String> {
if bytes.len() < 52 || !Self::is_elf(bytes) {
return Err("not an ELF file".into());
}
if bytes[4] != 1 || bytes[5] != 1 {
return Err("only 32-bit little-endian ELF files are supported".into());
}
let etype = u16le(bytes, 16);
if u16le(bytes, 18) != 40 {
return Err("not an ARM ELF file".into());
}
let shoff = u32le(bytes, 32) as usize;
let shentsize = u16le(bytes, 46) as usize;
let shnum = u16le(bytes, 48) as usize;
let shstrndx = u16le(bytes, 50) as usize;
if shoff == 0 || shnum == 0 || shoff + shnum * shentsize > bytes.len() || shentsize < 40 {
return Err("ELF file has no usable section headers".into());
}
let mut secs: Vec<Section> = (0..shnum)
.map(|i| {
let o = shoff + i * shentsize;
Section {
name: String::new(),
ty: u32le(bytes, o + 4),
flags: u32le(bytes, o + 8),
addr: u32le(bytes, o + 12),
offset: u32le(bytes, o + 16) as usize,
size: u32le(bytes, o + 20) as usize,
link: u32le(bytes, o + 24),
info: u32le(bytes, o + 28),
align: u32le(bytes, o + 32),
}
})
.collect();
let name_offs: Vec<usize> = (0..shnum)
.map(|i| u32le(bytes, shoff + i * shentsize) as usize)
.collect();
if shstrndx < shnum {
let stroff = secs[shstrndx].offset;
for (s, no) in secs.iter_mut().zip(&name_offs) {
s.name = cstr(bytes, stroff + no);
}
}
for s in &secs {
if s.ty != SHT_NOBITS && s.offset + s.size > bytes.len() {
return Err(format!("section {} extends past the end of the file", s.name));
}
}
let relocatable = etype == 1;
if relocatable {
let mut addr = 0x0001_0000u32;
for s in secs.iter_mut() {
if s.flags & SHF_ALLOC != 0 {
addr = addr.next_multiple_of(s.align.max(1));
s.addr = addr;
addr += s.size as u32;
addr += 16;
}
}
}
let phoff = u32le(bytes, 28) as usize;
let phentsize = u16le(bytes, 42) as usize;
let phnum = u16le(bytes, 44) as usize;
let mut loads: Vec<(u32, u32, u32, u32)> = Vec::new(); if !relocatable && phoff != 0 && phentsize >= 32 && phoff + phnum * phentsize <= bytes.len() {
for i in 0..phnum {
let o = phoff + i * phentsize;
if u32le(bytes, o) == 1 {
loads.push((
u32le(bytes, o + 4),
u32le(bytes, o + 8),
u32le(bytes, o + 12),
u32le(bytes, o + 16),
));
}
}
}
let load_addr = |s: &Section| -> Option<u32> {
if s.ty == SHT_NOBITS {
return None;
}
loads
.iter()
.find(|l| s.offset as u32 >= l.0 && (s.offset as u32) < l.0 + l.3)
.map(|l| l.2 + (s.offset as u32 - l.0))
};
let mut img = Image::default();
let mut seg_of_sec: HashMap<usize, usize> = HashMap::new();
for (i, s) in secs.iter().enumerate() {
if s.flags & SHF_ALLOC != 0
&& s.size > 0
&& matches!(s.ty, SHT_PROGBITS | SHT_NOBITS | SHT_INIT_ARRAY | 15 | 16)
{
let data = if s.ty == SHT_NOBITS {
vec![0; s.size]
} else {
bytes[s.offset..s.offset + s.size].to_vec()
};
seg_of_sec.insert(i, img.segments.len());
img.segments.push(Segment {
name: s.name.clone(),
addr: s.addr,
data,
writable: s.flags & SHF_WRITE != 0,
exec: s.flags & SHF_EXEC != 0,
load_addr: load_addr(s).filter(|&l| l != s.addr),
});
}
let raw = || &bytes[s.offset..s.offset + s.size];
if s.ty == 0x7000_0003 && s.offset + s.size <= bytes.len() {
img.rwpi = aeabi_attribute(raw(), 15) == Some(2);
img.hard_float |= crate::fp::vfp_args(raw());
img.short_enums = match aeabi_attribute(raw(), 26) {
Some(1) => Some(true),
Some(2) => Some(false),
_ => img.short_enums,
};
}
if s.name == ".comment" && s.ty == SHT_PROGBITS {
let text: Vec<String> = raw()
.split(|&c| c == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect();
img.comment = Some(text.join("; "));
}
if (s.name == ".debug_str" || s.name == ".debug_info" || s.name == ".debug_line_str")
&& img.producer.is_none()
{
let d = raw();
if let Some(p) = d.windows(5).position(|w| w == b"GNU C") {
img.producer = Some(cstr(d, p));
}
}
}
if !relocatable {
load_view(bytes, &secs, &mut img)?;
}
struct RawSym {
name: String,
value: u32,
shndx: usize,
info: u8,
}
let mut raw_syms: Vec<RawSym> = Vec::new();
let mut ext_next = img
.segments
.iter()
.map(|s| s.addr + s.data.len() as u32)
.max()
.unwrap_or(0x10000)
.next_multiple_of(16)
+ 0x100;
let mut ext_by_name: HashMap<String, u32> = HashMap::new();
let mut sym_addr: Vec<u32> = Vec::new();
if let Some(st) = secs.iter().find(|s| s.ty == SHT_SYMTAB) {
let stroff = secs.get(st.link as usize).map_or(0, |s| s.offset);
let mut code_marks: Vec<(u32, bool)> = Vec::new();
let mut cur_file: Option<String> = None;
for i in 0..st.size / 16 {
let o = st.offset + i * 16;
let name = cstr(bytes, stroff + u32le(bytes, o) as usize);
let value = u32le(bytes, o + 4);
let size = u32le(bytes, o + 8);
let info = bytes[o + 12];
let shndx = u16le(bytes, o + 14) as usize;
let ty = info & 0xf;
if ty == 4 {
cur_file = Some(name.clone());
}
let local = info >> 4 == 0;
let base = if relocatable && shndx != 0 && shndx < shnum {
secs[shndx].addr
} else {
0
};
let mut addr = base.wrapping_add(value);
if shndx == 0 && i != 0 && ty != 3 {
addr = *ext_by_name.entry(name.clone()).or_insert_with(|| {
let a = ext_next;
ext_next += 16;
a
});
img.externals.insert(addr, name.clone());
if ty == 2 || ty == 0 {
addr |= 1;
}
} else if shndx == 0xfff1 && !relocatable && ty == 0 && !name.is_empty() {
img.symbols.push(Symbol {
name: name.clone(),
addr,
size: 0,
kind: SymKind::Other,
global: !local,
file: None,
});
} else if shndx != 0 && shndx < shnum {
if local
&& secs[shndx].flags & SHF_ALLOC != 0
&& ty != 3
&& let Some(f) = &cur_file
{
img.owners.push((addr & !1, f.clone()));
}
if name == "$t" || name == "$a" || name.starts_with("$t.") {
code_marks.push((addr, true));
} else if name == "$d" || name.starts_with("$d.") {
if secs[shndx].flags & SHF_EXEC != 0 {
code_marks.push((addr, false));
}
} else if !name.is_empty() && matches!(ty, 0..=2) && secs[shndx].flags & SHF_ALLOC != 0 {
let kind = match ty {
2 => SymKind::Func,
1 => SymKind::Object,
_ => SymKind::Other,
};
img.symbols.push(Symbol {
name: name.clone(),
addr: addr & !((kind == SymKind::Func) as u32),
size,
kind,
global: info >> 4 != 0,
file: if local { cur_file.clone() } else { None },
});
}
}
sym_addr.push(addr);
raw_syms.push(RawSym {
name,
value,
shndx,
info,
});
}
code_marks.sort();
for (i, &(a, is_code)) in code_marks.iter().enumerate() {
if is_code {
continue;
}
let seg_end = img
.segments
.iter()
.find(|s| a >= s.addr && a < s.addr + s.data.len() as u32)
.map(|s| s.addr + s.data.len() as u32);
let Some(seg_end) = seg_end else { continue };
let end = code_marks[i + 1..]
.iter()
.find(|m| m.1)
.map_or(seg_end, |m| m.0.min(seg_end));
img.data_ranges.push((a, end));
}
}
let _ = &raw_syms;
if relocatable {
for s in &secs {
if s.ty != SHT_REL {
continue;
}
let Some(&seg) = seg_of_sec.get(&(s.info as usize)) else {
continue;
};
let target = &secs[s.info as usize];
for i in 0..s.size / 8 {
let o = s.offset + i * 8;
let off = u32le(bytes, o);
let info = u32le(bytes, o + 4);
let (symi, rty) = ((info >> 8) as usize, info & 0xff);
let Some(&sv) = sym_addr.get(symi) else {
return Err("relocation refers to a bad symbol".into());
};
let rs = &raw_syms[symi];
let is_func = rs.info & 0xf == 2 || (rs.shndx == 0 && rs.info & 0xf == 0);
let _ = rs.value;
let t = if is_func { sv & 1 } else { 0 };
let s_addr = sv & !t;
let p = target.addr + off;
let o = off as usize;
let data = &img.segments[seg].data;
let width = if matches!(rty, 102 | 103) { 2 } else { 4 };
if o + width > data.len() {
return Err("relocation outside its section".into());
}
let (rty, s_addr, t) = match rty {
9 | 87..=89 => {
img.static_base = Some(OBJECT_STATIC_BASE);
let rel = s_addr.wrapping_sub(OBJECT_STATIC_BASE);
(
if rty == 9 {
2
} else if rty == 88 {
48
} else {
47
},
rel,
0,
)
}
_ => (rty, s_addr, t),
};
let data = &mut img.segments[seg].data;
apply_reloc(data, o, rty, s_addr, t, p).map_err(|e| format!("{e} (symbol {})", rs.name))?;
}
}
}
img.needs_static_base = !relocatable;
if !relocatable {
let mut votes: HashMap<u32, u32> = HashMap::new();
for s in secs.iter().filter(|s| s.ty == SHT_REL) {
for i in 0..s.size / 8 {
let o = s.offset + i * 8;
let (off, info) = (u32le(bytes, o), u32le(bytes, o + 4));
let (symi, rty) = ((info >> 8) as usize, info & 0xff);
let Some(&sv) = sym_addr.get(symi) else { continue };
let value = match rty {
9 => img.read(off, 4).map(|d| u32le(d, 0)),
87 | 89 => img.read(off, 8).and_then(|d| {
let imm = |o: usize| {
let (hw1, hw2) = (u16le(d, o), u16le(d, o + 2));
(hw1 & 0xf) << 12 | (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | (hw2 & 0xff)
};
(u16le(d, 4) & 0xfbf0 == 0xf2c0).then(|| imm(4) << 16 | imm(0))
}),
_ => None,
};
if let Some(v) = value {
*votes.entry((sv & !1).wrapping_sub(v)).or_default() += 1;
}
}
}
let total: u32 = votes.values().sum();
if let Some((&sb, &n)) = votes.iter().max_by_key(|(sb, n)| (**n, std::cmp::Reverse(**sb)))
&& n * 2 > total
{
img.static_base = Some(sb);
}
}
img.meta = ElfMeta::parse(bytes);
img.finish();
Ok(img)
}
pub fn from_raw(bytes: &[u8], base: u32, symtab: &str) -> Result<Image, String> {
let info = crate::inputs::parse_symbols(symtab)?;
crate::inputs::build_image(vec![(base, bytes.to_vec())], &info)
}
pub(crate) fn finish(&mut self) {
self.symbols
.sort_by_key(|s| (s.addr, s.kind != SymKind::Func, s.name.clone()));
let addrs: Vec<u32> = self.symbols.iter().map(|s| s.addr).collect();
for i in 0..self.symbols.len() {
if self.symbols[i].size != 0 || self.symbols[i].kind == SymKind::Other {
continue;
}
let a = self.symbols[i].addr;
let seg_end = self
.segments
.iter()
.find(|s| a >= s.addr && a < s.addr + s.data.len() as u32)
.map(|s| s.addr + s.data.len() as u32);
let next = addrs.iter().copied().filter(|&x| x > a).min();
if let Some(end) = match (seg_end, next) {
(Some(e), Some(n)) => Some(e.min(n)),
(Some(e), None) => Some(e),
_ => None,
} {
self.symbols[i].size = end - a;
}
}
self.data_ranges.sort();
self.owners.sort();
self.owners.dedup();
for i in 0..self.symbols.len() {
if self.symbols[i].file.is_none() && self.symbols[i].kind != SymKind::Other {
self.symbols[i].file = self.owner(self.symbols[i].addr).map(str::to_string);
}
}
}
pub fn owner(&self, addr: u32) -> Option<&str> {
let seg = self.segment_at(addr)?;
let i = self.owners.partition_point(|o| o.0 <= addr);
let (start, name) = self.owners.get(i.checked_sub(1)?)?;
(*start >= seg.addr).then_some(name.as_str())
}
pub fn named(&self, name: &str, func: bool) -> impl Iterator<Item = &Symbol> {
self.symbols
.iter()
.filter(move |s| (s.kind == SymKind::Func) == func && s.name == name)
}
pub fn segment_at(&self, addr: u32) -> Option<&Segment> {
self.segments
.iter()
.find(|s| addr >= s.addr && addr - s.addr < s.data.len() as u32)
}
pub fn read(&self, addr: u32, n: u32) -> Option<&[u8]> {
let s = self.segment_at(addr)?;
let o = (addr - s.addr) as usize;
s.data.get(o..o + n as usize)
}
pub fn read_const(&self, addr: u32, n: u32) -> Option<&[u8]> {
let s = self.segment_at(addr)?;
if s.writable {
return None;
}
let o = (addr - s.addr) as usize;
s.data.get(o..o + n as usize)
}
pub fn func(&self, name: &str) -> Option<&Symbol> {
self.symbols.iter().find(|s| s.kind == SymKind::Func && s.name == name)
}
pub fn func_at(&self, addr: u32) -> Option<&Symbol> {
self.symbols.iter().find(|s| s.kind == SymKind::Func && s.addr == addr)
}
pub fn object(&self, name: &str) -> Option<&Symbol> {
self.symbols.iter().find(|s| s.kind != SymKind::Func && s.name == name)
}
pub fn is_data_in_code(&self, addr: u32) -> bool {
self.data_ranges.iter().any(|&(a, b)| addr >= a && addr < b)
}
}
fn aeabi_attribute(d: &[u8], want: u32) -> Option<u32> {
fn uleb(d: &[u8], p: &mut usize) -> Option<u32> {
let (mut v, mut shift) = (0u32, 0);
loop {
let b = *d.get(*p)?;
*p += 1;
v |= ((b & 0x7f) as u32).checked_shl(shift).unwrap_or(0);
shift += 7;
if b & 0x80 == 0 {
return Some(v);
}
}
}
fn ntbs(d: &[u8], p: &mut usize) -> Option<()> {
*p += d.get(*p..)?.iter().position(|&c| c == 0)? + 1;
Some(())
}
if d.first() != Some(&b'A') {
return None;
}
let mut p = 1;
while p + 4 <= d.len() {
let len = u32le(d, p) as usize;
let end = (p + len).min(d.len());
let mut q = p + 4;
let vendor_end = q + d.get(q..end)?.iter().position(|&c| c == 0)?;
let is_aeabi = &d[q..vendor_end] == b"aeabi";
q = vendor_end + 1;
while is_aeabi && q + 5 <= end {
let tag = d[q];
let sub_end = (q + u32le(d, q + 1) as usize).min(end);
let mut r = q + 5;
while tag == 1 && r < sub_end {
let t = uleb(d, &mut r)?;
match t {
4 | 5 | 65 | 67 => ntbs(d, &mut r)?,
32 => {
uleb(d, &mut r)?;
ntbs(d, &mut r)?;
}
t if t > 32 && t % 2 == 1 => ntbs(d, &mut r)?,
_ => {
let v = uleb(d, &mut r)?;
if t == want {
return Some(v);
}
}
}
}
if sub_end <= q {
break;
}
q = sub_end;
}
if len == 0 {
break;
}
p = end;
}
None
}
fn sign_extend(v: u32, bits: u32) -> i32 {
((v << (32 - bits)) as i32) >> (32 - bits)
}
fn apply_reloc(d: &mut [u8], o: usize, rty: u32, s: u32, t: u32, p: u32) -> Result<(), String> {
let rd16 = |d: &[u8], o: usize| u16::from_le_bytes([d[o], d[o + 1]]) as u32;
let wr16 = |d: &mut [u8], o: usize, v: u32| d[o..o + 2].copy_from_slice(&(v as u16).to_le_bytes());
let rd32 = |d: &[u8], o: usize| u32::from_le_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]);
match rty {
0 | 40 => {} 2 | 38 => {
let v = rd32(d, o).wrapping_add(s) | t;
d[o..o + 4].copy_from_slice(&v.to_le_bytes());
}
3 => {
let v = (rd32(d, o).wrapping_add(s) | t).wrapping_sub(p);
d[o..o + 4].copy_from_slice(&v.to_le_bytes());
}
42 => {
let a = sign_extend(rd32(d, o) & 0x7fff_ffff, 31) as u32;
let v = (a.wrapping_add(s) | t).wrapping_sub(p);
let w = (rd32(d, o) & 0x8000_0000) | (v & 0x7fff_ffff);
d[o..o + 4].copy_from_slice(&w.to_le_bytes());
}
10 | 30 => {
let (hw1, hw2) = (rd16(d, o), rd16(d, o + 2));
let sgn = hw1 >> 10 & 1;
let (j1, j2) = (hw2 >> 13 & 1, hw2 >> 11 & 1);
let (i1, i2) = (!(j1 ^ sgn) & 1, !(j2 ^ sgn) & 1);
let imm = sgn << 24 | i1 << 23 | i2 << 22 | (hw1 & 0x3ff) << 12 | (hw2 & 0x7ff) << 1;
let a = sign_extend(imm, 25) as u32;
let v = a.wrapping_add(s).wrapping_sub(p);
let sv = v as i32;
if !(-(1 << 24)..(1 << 24)).contains(&sv) {
return Err("branch relocation out of range".into());
}
let sgn = v >> 24 & 1;
let (i1, i2) = (v >> 23 & 1, v >> 22 & 1);
let (j1, j2) = (!(i1 ^ sgn) & 1, !(i2 ^ sgn) & 1);
wr16(d, o, (hw1 & 0xf800) | sgn << 10 | (v >> 12 & 0x3ff));
wr16(d, o + 2, (hw2 & 0xd000) | j1 << 13 | j2 << 11 | (v >> 1 & 0x7ff));
}
102 | 103 => {
let bits = if rty == 102 { 11 } else { 8 };
let hw = rd16(d, o);
let mask = (1u32 << bits) - 1;
let a = sign_extend((hw & mask) << 1, bits + 1) as u32;
let v = a.wrapping_add(s).wrapping_sub(p);
if !(-(1 << bits)..(1 << bits)).contains(&(v as i32)) {
return Err("short branch relocation out of range".into());
}
wr16(d, o, (hw & !mask) | (v >> 1 & mask));
}
51 => {
let (hw1, hw2) = (rd16(d, o), rd16(d, o + 2));
let sgn = hw1 >> 10 & 1;
let (j1, j2) = (hw2 >> 13 & 1, hw2 >> 11 & 1);
let imm = sgn << 20 | j2 << 19 | j1 << 18 | (hw1 & 0x3f) << 12 | (hw2 & 0x7ff) << 1;
let a = sign_extend(imm, 21) as u32;
let v = a.wrapping_add(s).wrapping_sub(p);
if !(-(1 << 20)..(1 << 20)).contains(&(v as i32)) {
return Err("conditional branch relocation out of range".into());
}
wr16(d, o, (hw1 & 0xfbc0) | (v >> 20 & 1) << 10 | (v >> 12 & 0x3f));
wr16(
d,
o + 2,
(hw2 & 0xd000) | (v >> 18 & 1) << 13 | (v >> 19 & 1) << 11 | (v >> 1 & 0x7ff),
);
}
47 | 48 => {
let (hw1, hw2) = (rd16(d, o), rd16(d, o + 2));
let imm = (hw1 & 0xf) << 12 | (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | (hw2 & 0xff);
let a = sign_extend(imm, 16) as u32;
let x = a.wrapping_add(s) | t;
let v = if rty == 47 { x & 0xffff } else { x >> 16 };
wr16(d, o, (hw1 & 0xfbf0) | (v >> 11 & 1) << 10 | (v >> 12 & 0xf));
wr16(d, o + 2, (hw2 & 0x8f00) | (v >> 8 & 7) << 12 | (v & 0xff));
}
other => return Err(format!("unsupported relocation type {other}")),
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RelocTarget {
Code,
ReadOnlyData,
WritableData,
Undefined,
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RelocInfo {
pub rtype: u32,
pub in_code: bool,
pub target: RelocTarget,
pub symbol: String,
}
#[derive(Clone, Debug, Default)]
pub struct ElfMeta {
pub present: bool,
pub relocatable: bool,
pub e_flags: u32,
pub attributes: Vec<u8>,
pub sections: Vec<(String, u32, u32, u32)>,
pub relocs: Vec<RelocInfo>,
pub undefined: Vec<String>,
pub producers: Vec<String>,
pub command_line: Option<String>,
}
impl ElfMeta {
pub fn parse(b: &[u8]) -> ElfMeta {
let mut m = ElfMeta::default();
if b.len() < 52 || !b.starts_with(b"\x7fELF") || b[4] != 1 || b[5] != 1 {
return m;
}
m.present = true;
m.relocatable = u16le(b, 16) == 1;
m.e_flags = u32le(b, 36);
let (shoff, shentsize, shnum, shstrndx) = (
u32le(b, 32) as usize,
u16le(b, 46) as usize,
u16le(b, 48) as usize,
u16le(b, 50) as usize,
);
if shoff == 0 || shentsize < 40 || shoff.saturating_add(shnum * shentsize) > b.len() {
return m;
}
let hdr = |i: usize| {
let o = shoff + i * shentsize;
(
u32le(b, o) as usize,
u32le(b, o + 4),
u32le(b, o + 8),
u32le(b, o + 16) as usize,
u32le(b, o + 20) as usize,
u32le(b, o + 24) as usize,
u32le(b, o + 28) as usize,
)
};
let data = |i: usize| -> &[u8] {
let h = hdr(i);
if h.1 == 8 || h.3.saturating_add(h.4) > b.len() {
&[]
} else {
&b[h.3..h.3 + h.4]
}
};
let stroff = if shstrndx < shnum { hdr(shstrndx).3 } else { 0 };
let names: Vec<String> = (0..shnum).map(|i| cstr(b, stroff + hdr(i).0)).collect();
for (i, name) in names.iter().enumerate() {
let h = hdr(i);
m.sections.push((name.clone(), h.1, h.2, h.4 as u32));
let d = data(i);
match names[i].as_str() {
".ARM.attributes" => m.attributes = d.to_vec(),
".GCC.command.line" => {
let parts: Vec<String> = d
.split(|&c| c == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect();
m.command_line = Some(parts.join(" "));
}
".debug_str" | ".debug_info" | ".debug_line_str" | ".comment" => {
for pat in [&b"clang version"[..], b"GNU C", b"GNU GIMPLE", b"GCC: "] {
let mut from = 0;
while let Some(p) = d[from..].windows(pat.len()).position(|w| w == pat) {
let at = from + p;
if at == 0 || d[at - 1] == 0 || name == ".debug_info" {
let s = cstr(d, at);
if !m.producers.contains(&s) {
m.producers.push(s);
}
}
from = at + pat.len();
}
}
}
_ => {}
}
}
let Some(symtab) = (0..shnum).find(|&i| hdr(i).1 == 2) else {
return m;
};
let st = data(symtab);
let sym_str = hdr(hdr(symtab).5.min(shnum - 1)).3;
let syms: Vec<(String, usize, u8)> = (0..st.len() / 16)
.map(|i| {
let o = i * 16;
(
cstr(b, sym_str + u32le(st, o) as usize),
u16le(st, o + 14) as usize,
st[o + 12] & 0xf,
)
})
.collect();
for (i, (name, shndx, ty)) in syms.iter().enumerate() {
if i != 0 && *shndx == 0 && *ty != 3 && !name.is_empty() {
m.undefined.push(name.clone());
}
}
if !m.relocatable {
return m;
}
for i in 0..shnum {
let h = hdr(i);
if h.1 != 9 || h.6 >= shnum || hdr(h.6).2 & SHF_ALLOC == 0 {
continue;
}
let in_code = hdr(h.6).2 & SHF_EXEC != 0;
let d = data(i);
for r in 0..d.len() / 8 {
let info = u32le(d, r * 8 + 4);
let Some((name, shndx, _)) = syms.get((info >> 8) as usize) else {
continue;
};
let target = if *shndx == 0 {
RelocTarget::Undefined
} else if *shndx >= shnum {
RelocTarget::Other
} else {
let f = hdr(*shndx).2;
if f & SHF_EXEC != 0 {
RelocTarget::Code
} else if f & SHF_WRITE != 0 {
RelocTarget::WritableData
} else if f & SHF_ALLOC != 0 {
RelocTarget::ReadOnlyData
} else {
RelocTarget::Other
}
};
m.relocs.push(RelocInfo {
rtype: info & 0xff,
in_code,
target,
symbol: name.clone(),
});
}
}
m
}
}