use super::decode::*;
use crate::image::{Image, SymKind};
use std::collections::HashMap;
#[derive(Clone, Debug, PartialEq)]
pub enum Val {
Imm(u32),
Sym(String, i32),
}
#[derive(Clone, Debug)]
pub enum Item {
Label(String),
Insn(Op, Option<Val>),
LoadLit(Reg, Val),
Data(u8, Val),
Align(u32),
Pool,
Section,
}
#[derive(Clone, Debug)]
pub struct Line {
pub item: Item,
pub line: u32,
pub text: String,
}
#[derive(Clone, Debug, Default)]
pub struct Source {
pub lines: Vec<Line>,
pub unified: bool,
pub funcs: Vec<String>,
}
fn reg(s: &str) -> Option<Reg> {
let s = s.trim();
Some(match s {
"sp" => 13,
"lr" => 14,
"pc" => 15,
"ip" => 12,
"fp" => 11,
"sl" => 10,
"sb" => 9,
_ => {
let n = s.strip_prefix('r')?.parse::<u8>().ok()?;
if n > 15 || s.len() > 3 || (s.len() == 3 && s.as_bytes()[1] == b'0') {
return None;
}
n
}
})
}
fn cond(s: &str) -> Option<Cond> {
Some(match s {
"eq" => Cond::Eq,
"ne" => Cond::Ne,
"cs" | "hs" => Cond::Cs,
"cc" | "lo" => Cond::Cc,
"mi" => Cond::Mi,
"pl" => Cond::Pl,
"vs" => Cond::Vs,
"vc" => Cond::Vc,
"hi" => Cond::Hi,
"ls" => Cond::Ls,
"ge" => Cond::Ge,
"lt" => Cond::Lt,
"gt" => Cond::Gt,
"le" => Cond::Le,
"al" => Cond::Al,
_ => return None,
})
}
const BASES: &[(&str, bool)] = &[
("cpsid", false),
("cpsie", false),
("ldrsb", false),
("ldrsh", false),
("ldmia", false),
("ldmfd", false),
("stmia", false),
("stmdb", false),
("stmfd", false),
("rev16", false),
("revsh", false),
("yield", false),
("ldrb", false),
("ldrh", false),
("strb", false),
("strh", false),
("push", false),
("movw", false),
("movt", false),
("cbnz", false),
("bkpt", false),
("uxtb", false),
("uxth", false),
("sxtb", false),
("sxth", false),
("udiv", false),
("sdiv", false),
("rbit", false),
("mov", true),
("mvn", true),
("add", true),
("adc", true),
("sub", true),
("sbc", true),
("rsb", true),
("neg", true),
("and", true),
("orr", true),
("orn", true),
("eor", true),
("bic", true),
("lsl", true),
("lsr", true),
("asr", true),
("ror", true),
("mul", true),
("mla", false),
("mls", false),
("cmp", false),
("cmn", false),
("tst", false),
("teq", false),
("ldr", false),
("ldm", false),
("str", false),
("stm", false),
("pop", false),
("blx", false),
("cbz", false),
("adr", false),
("nop", false),
("svc", false),
("udf", false),
("wfi", false),
("wfe", false),
("sev", false),
("dsb", false),
("dmb", false),
("isb", false),
("mrs", false),
("msr", false),
("rev", false),
("clz", false),
("bx", false),
("bl", false),
("b", false),
];
fn mnemonic(m: &str) -> Option<(&'static str, bool, Cond)> {
let m = m.strip_suffix(".n").or_else(|| m.strip_suffix(".w")).unwrap_or(m);
for &(base, may_s) in BASES {
let Some(rest) = m.strip_prefix(base) else { continue };
if rest.is_empty() {
return Some((base, false, Cond::Al));
}
if rest == "s" && may_s {
return Some((base, true, Cond::Al));
}
if let Some(c) = cond(rest) {
return Some((base, false, c));
}
if may_s && rest.len() == 3 {
if let Some(c) = rest.strip_prefix('s').and_then(cond) {
return Some((base, true, c));
}
if let Some(c) = rest.strip_suffix('s').and_then(cond) {
return Some((base, true, c));
}
}
}
None
}
fn sysm(name: &str) -> Option<u8> {
Some(match name.split('_').next().unwrap_or(name) {
"apsr" => 0,
"iapsr" => 1,
"eapsr" => 2,
"xpsr" | "psr" => 3,
"ipsr" => 5,
"epsr" => 6,
"iepsr" => 7,
"msp" => 8,
"psp" => 9,
"primask" => 16,
"basepri" if name == "basepri_max" => 18,
"basepri" => 17,
"faultmask" => 19,
"control" => 20,
_ => return None,
})
}
struct Parser {
equs: HashMap<String, u32>,
locals: HashMap<String, u32>,
}
impl Parser {
fn number(&self, s: &str) -> Option<u32> {
let s = s.trim();
let (neg, s) = match s.strip_prefix('-') {
Some(r) => (true, r.trim()),
None => (false, s.strip_prefix('+').unwrap_or(s).trim()),
};
let v = if let Some(h) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
u32::from_str_radix(h, 16).ok()?
} else if let Some(b) = s.strip_prefix("0b").or_else(|| s.strip_prefix("0B")) {
u32::from_str_radix(b, 2).ok()?
} else if s.len() == 3 && s.starts_with('\'') && s.ends_with('\'') {
s.as_bytes()[1] as u32
} else if s.chars().all(|c| c.is_ascii_digit()) && !s.is_empty() {
s.parse::<u64>().ok().filter(|&v| v <= u32::MAX as u64)? as u32
} else {
*self.equs.get(s)?
};
Some(if neg { v.wrapping_neg() } else { v })
}
fn symbol(&self, s: &str) -> Option<String> {
let s = s.trim();
if s.len() >= 2 && s[..s.len() - 1].chars().all(|c| c.is_ascii_digit()) {
let n = &s[..s.len() - 1];
let k = self.locals.get(n).copied().unwrap_or(0);
return match s.as_bytes()[s.len() - 1] {
b'b' if k > 0 => Some(format!("{n}\u{1}{k}")),
b'f' => Some(format!("{n}\u{1}{}", k + 1)),
_ => None,
};
}
let ok = !s.is_empty()
&& !s.starts_with(|c: char| c.is_ascii_digit())
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '$'));
ok.then(|| s.to_string())
}
fn value(&self, s: &str) -> Result<Val, String> {
let s = s.trim();
let s = s.strip_prefix('#').unwrap_or(s).trim();
let s = s.strip_prefix('(').and_then(|x| x.strip_suffix(')')).unwrap_or(s);
let mut terms: Vec<(bool, &str)> = Vec::new();
let (mut start, mut neg) = (0, false);
for (i, c) in s.char_indices() {
if (c == '+' || c == '-') && i > start && !s[start..i].trim().is_empty() {
terms.push((neg, s[start..i].trim()));
neg = c == '-';
start = i + 1;
} else if (c == '+' || c == '-') && s[start..i].trim().is_empty() {
neg ^= c == '-';
start = i + 1;
}
}
terms.push((neg, s[start..].trim()));
let (mut sym, mut k) = (None, 0u32);
for (neg, t) in terms {
if let Some(v) = self.number(t) {
k = if neg { k.wrapping_sub(v) } else { k.wrapping_add(v) };
} else if let (Some(name), false, true) = (self.symbol(t), neg, sym.is_none()) {
sym = Some(name);
} else {
return Err(format!("expression `{s}`"));
}
}
Ok(match sym {
Some(name) => Val::Sym(name, k as i32),
None => Val::Imm(k),
})
}
fn imm(&self, s: &str) -> Result<u32, String> {
match self.value(s)? {
Val::Imm(v) => Ok(v),
Val::Sym(..) => Err(format!("`{s}` is not a constant")),
}
}
}
fn operands(s: &str) -> Vec<&str> {
let (mut out, mut depth, mut start) = (Vec::new(), 0i32, 0);
for (i, c) in s.char_indices() {
match c {
'[' | '{' => depth += 1,
']' | '}' => depth -= 1,
',' if depth == 0 => {
out.push(s[start..i].trim());
start = i + 1;
}
_ => {}
}
}
if !s[start..].trim().is_empty() {
out.push(s[start..].trim());
}
out
}
fn shift_kind(s: &str) -> Option<Shift> {
Some(match s {
"lsl" | "asl" => Shift::Lsl,
"lsr" => Shift::Lsr,
"asr" => Shift::Asr,
"ror" => Shift::Ror,
_ => return None,
})
}
fn bad<T>(what: &str) -> Result<T, String> {
Err(what.to_string())
}
impl Parser {
fn operand2(&self, a: &[&str]) -> Result<Operand, String> {
match a {
[x] => match reg(x) {
Some(rm) => Ok(Operand::Reg {
rm,
shift: Shift::Lsl,
amount: 0,
}),
None => Ok(Operand::Imm {
value: self.imm(x)?,
carry: None,
}),
},
[x, sh] => {
let rm = reg(x).ok_or("register expected")?;
if *sh == "rrx" {
return Ok(Operand::Reg {
rm,
shift: Shift::Rrx,
amount: 1,
});
}
let (kind, n) = sh.split_once(char::is_whitespace).ok_or("shift expected")?;
let shift = shift_kind(kind).ok_or("shift expected")?;
let amount = self.imm(n)?;
if amount > 32 || reg(n).is_some() {
return bad("shift amount");
}
Ok(Operand::Reg {
rm,
shift,
amount: amount as u8,
})
}
_ => bad("operand"),
}
}
fn reglist(&self, s: &str) -> Result<u16, String> {
let inner = s
.trim()
.strip_prefix('{')
.and_then(|x| x.strip_suffix('}'))
.ok_or("register list expected")?;
let mut regs = 0u16;
for part in inner.split(',') {
let part = part.trim();
let (a, b) = match part.split_once('-') {
Some((a, b)) => (reg(a), reg(b)),
None => (reg(part), reg(part)),
};
let (Some(a), Some(b)) = (a, b) else {
return bad("register list");
};
if a > b {
return bad("register list");
}
for r in a..=b {
regs |= 1 << r;
}
}
Ok(regs)
}
fn address(&self, a: &[&str]) -> Result<(Addr, Option<Val>), String> {
let first = a.first().ok_or("address expected")?;
if !first.starts_with('[') {
if a.len() != 1 {
return bad("address");
}
return Ok((Addr::Lit(0), Some(self.value(first)?)));
}
let close = first.find(']').ok_or("`]` expected")?;
let inner = operands(&first[1..close]);
let after = first[close + 1..].trim();
let rn = reg(inner.first().ok_or("base register expected")?).ok_or("base register expected")?;
let pre = match after {
"" => false,
"!" => true,
_ => return bad("address"),
};
let offset = match &inner[1..] {
[] => Offset::Imm(0),
[x] => match reg(x) {
Some(rm) => Offset::Reg { rm, shift: 0 },
None => Offset::Imm(self.imm(x)? as i32),
},
[x, sh] => {
let rm = reg(x).ok_or("index register expected")?;
let n = sh.strip_prefix("lsl").ok_or("lsl expected")?;
let n = self.imm(n)?;
if n > 3 {
return bad("index shift");
}
Offset::Reg { rm, shift: n as u8 }
}
_ => return bad("address"),
};
match &a[1..] {
[] => Ok((
Addr::Base {
rn,
offset,
index: true,
wback: pre,
},
None,
)),
[post] if inner.len() == 1 && !pre => Ok((
Addr::Base {
rn,
offset: Offset::Imm(self.imm(post)? as i32),
index: false,
wback: true,
},
None,
)),
_ => bad("address"),
}
}
fn insn(&self, m: &str, rest: &str) -> Result<Item, String> {
if m.starts_with("it") && m.len() <= 5 && m[2..].chars().all(|c| c == 't' || c == 'e') {
let c = cond(rest.trim()).ok_or("condition expected")?;
let c0 = c as u8 & 1;
let mut mask = 0u8;
let n = m.len() - 2;
for (i, x) in m[2..].chars().enumerate() {
let bit = if x == 't' { c0 } else { c0 ^ 1 };
mask |= bit << (3 - i);
}
mask |= 1 << (3 - n);
return Ok(Item::Insn(Op::It { cond: c, mask }, None));
}
let (base, s, c) = mnemonic(m).ok_or("unknown instruction")?;
let a = operands(rest);
let r = |i: usize| -> Result<Reg, String> {
a.get(i)
.and_then(|x| reg(x))
.ok_or_else(|| "register expected".to_string())
};
let plain = |op: Op| Ok(Item::Insn(op, None));
let dp = |op: DpOp| -> Result<Item, String> {
let three = a.len() >= 3
&& reg(a[1]).is_some()
&& shift_kind(a[2].split_whitespace().next().unwrap_or("")).is_none()
&& a[2] != "rrx";
let (rd, rn, src) = if three {
(r(0)?, r(1)?, self.operand2(&a[2..])?)
} else {
(r(0)?, r(0)?, self.operand2(&a[1..])?)
};
if rn == 15 || matches!(src, Operand::Reg { rm: 15, .. }) && rd != 15 && op != DpOp::Add {
return bad("pc as an operand");
}
Ok(Item::Insn(
Op::Dp {
op,
s,
rd: Some(rd),
rn: Some(rn),
src,
},
None,
))
};
let shift = |shift: Shift| -> Result<Item, String> {
let (rd, rm, amt) = match a.len() {
3 => (r(0)?, r(1)?, a[2]),
2 => (r(0)?, r(0)?, a[1]),
_ => return bad("operands"),
};
if let Some(rs) = reg(amt) {
return plain(Op::ShiftReg {
shift,
s,
rd,
rn: rm,
rm: rs,
});
}
let amount = self.imm(amt)?;
if amount > 32 {
return bad("shift amount");
}
plain(Op::Dp {
op: DpOp::Mov,
s,
rd: Some(rd),
rn: None,
src: Operand::Reg {
rm,
shift,
amount: amount as u8,
},
})
};
let test = |op: DpOp| -> Result<Item, String> {
plain(Op::Dp {
op,
s: true,
rd: None,
rn: Some(r(0)?),
src: self.operand2(&a[1.min(a.len())..])?,
})
};
let mem = |size: u8, signed: bool, load: bool| -> Result<Item, String> {
let rt = r(0)?;
if load && size == 4 && a.len() == 2 && a[1].starts_with('=') {
return Ok(Item::LoadLit(rt, self.value(&a[1][1..])?));
}
let (addr, sym) = self.address(&a[1.min(a.len())..])?;
if !load && sym.is_some() {
return bad("store to a label");
}
Ok(Item::Insn(
if load {
Op::Load { rt, size, signed, addr }
} else {
Op::Store { rt, size, addr }
},
sym,
))
};
let multi = |load: bool, before: bool| -> Result<Item, String> {
let (base, wback) = match a.first().and_then(|x| x.strip_suffix('!')) {
Some(b) => (b, true),
None => (*a.first().ok_or("operands")?, false),
};
let rn = reg(base).ok_or("register expected")?;
let regs = self.reglist(a.get(1).ok_or("register list expected")?)?;
plain(if load {
Op::LoadMulti {
rn,
regs,
wback,
before,
}
} else {
Op::StoreMulti {
rn,
regs,
wback,
before,
}
})
};
let extend = |signed: bool, size: u8| -> Result<Item, String> {
let (rd, rm) = if a.len() == 1 { (r(0)?, r(0)?) } else { (r(0)?, r(1)?) };
plain(Op::Extend {
signed,
size,
rd,
rn: None,
rm,
rotation: 0,
})
};
let two = |f: fn(Reg, Reg) -> Op| -> Result<Item, String> { plain(f(r(0)?, r(1)?)) };
let small = |max: u32| -> Result<u8, String> {
let v = self.imm(a.first().ok_or("operand expected")?)?;
if v > max {
bad("operand out of range")
} else {
Ok(v as u8)
}
};
let none = |op: Op| -> Result<Item, String> { if a.is_empty() { plain(op) } else { bad("operands") } };
let barrier = |op: Op| -> Result<Item, String> {
match a[..] {
[] | ["sy"] => plain(op),
[x] if self.imm(x) == Ok(15) => plain(op),
_ => bad("barrier option"),
}
};
match base {
"mov" | "mvn" => {
if a.len() < 2 {
return bad("operands");
}
plain(Op::Dp {
op: if base == "mov" { DpOp::Mov } else { DpOp::Mvn },
s,
rd: Some(r(0)?),
rn: None,
src: self.operand2(&a[1..])?,
})
}
"movw" => plain(Op::Dp {
op: DpOp::Mov,
s: false,
rd: Some(r(0)?),
rn: None,
src: Operand::Imm {
value: self.imm(a.get(1).ok_or("operands")?)?,
carry: None,
},
}),
"movt" => {
let v = self.imm(a.get(1).ok_or("operands")?)?;
if v > 0xffff {
return bad("operand out of range");
}
plain(Op::Movt {
rd: r(0)?,
imm: v as u16,
})
}
"add" => dp(DpOp::Add),
"adc" => dp(DpOp::Adc),
"sub" => dp(DpOp::Sub),
"sbc" => dp(DpOp::Sbc),
"rsb" => dp(DpOp::Rsb),
"and" => dp(DpOp::And),
"orr" => dp(DpOp::Orr),
"orn" => dp(DpOp::Orn),
"eor" => dp(DpOp::Eor),
"bic" => dp(DpOp::Bic),
"neg" => plain(Op::Dp {
op: DpOp::Rsb,
s,
rd: Some(r(0)?),
rn: Some(if a.len() == 1 { r(0)? } else { r(1)? }),
src: Operand::Imm { value: 0, carry: None },
}),
"cmp" => test(DpOp::Sub),
"cmn" => test(DpOp::Add),
"tst" => test(DpOp::And),
"teq" => test(DpOp::Eor),
"lsl" => shift(Shift::Lsl),
"lsr" => shift(Shift::Lsr),
"asr" => shift(Shift::Asr),
"ror" => shift(Shift::Ror),
"mul" => {
let (rd, rn, rm) = if a.len() == 2 {
(r(0)?, r(0)?, r(1)?)
} else {
(r(0)?, r(1)?, r(2)?)
};
plain(Op::Mul { s, rd, rn, rm })
}
"mla" => plain(Op::Mla {
rd: r(0)?,
rn: r(1)?,
rm: r(2)?,
ra: r(3)?,
}),
"mls" => plain(Op::Mls {
rd: r(0)?,
rn: r(1)?,
rm: r(2)?,
ra: r(3)?,
}),
"udiv" | "sdiv" => {
let (rd, rn, rm) = if a.len() == 2 {
(r(0)?, r(0)?, r(1)?)
} else {
(r(0)?, r(1)?, r(2)?)
};
plain(Op::Div {
signed: base == "sdiv",
rd,
rn,
rm,
})
}
"ldr" => mem(4, false, true),
"ldrb" => mem(1, false, true),
"ldrh" => mem(2, false, true),
"ldrsb" => mem(1, true, true),
"ldrsh" => mem(2, true, true),
"str" => mem(4, false, false),
"strb" => mem(1, false, false),
"strh" => mem(2, false, false),
"push" => plain(Op::StoreMulti {
rn: 13,
regs: self.reglist(rest)?,
wback: true,
before: true,
}),
"pop" => plain(Op::LoadMulti {
rn: 13,
regs: self.reglist(rest)?,
wback: true,
before: false,
}),
"ldm" | "ldmia" | "ldmfd" => multi(true, false),
"stm" | "stmia" => multi(false, false),
"stmdb" | "stmfd" => multi(false, true),
"b" => Ok(Item::Insn(
Op::B { cond: c, target: 0 },
Some(self.value(a.first().ok_or("target expected")?)?),
)),
"bl" => Ok(Item::Insn(
Op::Bl { target: 0 },
Some(self.value(a.first().ok_or("target expected")?)?),
)),
"bx" => plain(Op::Bx { rm: r(0)? }),
"blx" => plain(Op::Blx { rm: r(0)? }),
"cbz" | "cbnz" => Ok(Item::Insn(
Op::Cbz {
nonzero: base == "cbnz",
rn: r(0)?,
target: 0,
},
Some(self.value(a.get(1).ok_or("target expected")?)?),
)),
"adr" => Ok(Item::Insn(
Op::Adr { rd: r(0)?, target: 0 },
Some(self.value(a.get(1).ok_or("label expected")?)?),
)),
"uxtb" => extend(false, 1),
"uxth" => extend(false, 2),
"sxtb" => extend(true, 1),
"sxth" => extend(true, 2),
"rev" => two(|rd, rm| Op::Rev { rd, rm }),
"rev16" => two(|rd, rm| Op::Rev16 { rd, rm }),
"revsh" => two(|rd, rm| Op::Revsh { rd, rm }),
"clz" => two(|rd, rm| Op::Clz { rd, rm }),
"rbit" => two(|rd, rm| Op::Rbit { rd, rm }),
"nop" => none(Op::Nop),
"bkpt" => Ok(Item::Insn(Op::Bkpt(small(255)?), None)),
"svc" => Ok(Item::Insn(Op::Svc(small(255)?), None)),
"udf" => plain(Op::Udf),
"wfi" => none(Op::Sys(SysOp::Wfi)),
"wfe" => none(Op::Sys(SysOp::Wfe)),
"sev" => none(Op::Sys(SysOp::Sev)),
"yield" => none(Op::Sys(SysOp::Yield)),
"dsb" => barrier(Op::Sys(SysOp::Dsb)),
"dmb" => barrier(Op::Sys(SysOp::Dmb)),
"isb" => barrier(Op::Sys(SysOp::Isb)),
"cpsid" | "cpsie" => {
let (i, f) = match a[..] {
["i"] => (true, false),
["f"] => (false, true),
["if"] | ["fi"] => (true, true),
_ => return bad("interrupt flags"),
};
plain(Op::Sys(SysOp::Cps {
enable: base == "cpsie",
i,
f,
}))
}
"mrs" => plain(Op::Sys(SysOp::Mrs {
rd: r(0)?,
sysm: a.get(1).and_then(|x| sysm(x)).ok_or("special register expected")?,
})),
"msr" => plain(Op::Sys(SysOp::Msr {
rn: r(1)?,
sysm: a.first().and_then(|x| sysm(x)).ok_or("special register expected")?,
})),
_ => bad("unknown instruction"),
}
}
}
fn strip_comments(text: &str) -> String {
let b = text.as_bytes();
let mut out = String::with_capacity(text.len());
let (mut i, mut quote) = (0, false);
while i < b.len() {
let c = b[i];
if quote {
out.push(c as char);
if c == b'\\' && i + 1 < b.len() {
out.push(b[i + 1] as char);
i += 1;
} else if c == b'"' {
quote = false;
}
} else if c == b'"' {
quote = true;
out.push('"');
} else if c == b'/' && b.get(i + 1) == Some(&b'*') {
i += 2;
while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) {
if b[i] == b'\n' {
out.push('\n');
}
i += 1;
}
i += 1;
out.push(' ');
} else if c == b'@' || (c == b'/' && b.get(i + 1) == Some(&b'/')) {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
continue;
} else {
out.push(c as char);
}
i += 1;
}
out
}
pub fn parse(text: &str) -> Result<Source, String> {
let text = strip_comments(text);
let mut p = Parser {
equs: HashMap::new(),
locals: HashMap::new(),
};
let mut out = Source::default();
for (n, full) in text.lines().enumerate() {
let line = n as u32 + 1;
if full.trim_start().starts_with('#') {
let rest = full.trim_start()[1..].trim_start();
if rest.is_empty() || rest.starts_with(|c: char| c.is_ascii_digit()) || rest.starts_with("line") {
continue;
}
return Err(format!(
"line {line}: `{}`: preprocessor directives are not interpreted",
full.trim()
));
}
for stmt in full.split(';') {
let mut s = stmt.trim();
while let Some(colon) = s.find(':') {
let name = s[..colon].trim();
let ok = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '$'));
if !ok {
break;
}
let name = if name.chars().all(|c| c.is_ascii_digit()) {
let k = p.locals.entry(name.to_string()).or_insert(0);
*k += 1;
format!("{name}\u{1}{k}")
} else {
name.to_string()
};
out.lines.push(Line {
item: Item::Label(name),
line,
text: stmt.trim().to_string(),
});
s = s[colon + 1..].trim();
}
if s.is_empty() {
continue;
}
let fail = |why: String| format!("line {line}: `{s}`: {why}");
let (word, rest) = match s.find(char::is_whitespace) {
Some(i) => (&s[..i], s[i..].trim()),
None => (s, ""),
};
let lower = word.to_ascii_lowercase();
let mut push = |item: Item| {
out.lines.push(Line {
item,
line,
text: s.to_string(),
})
};
if let Some((name, v)) = s.split_once('=')
&& !lower.starts_with('.')
&& p.symbol(name).is_some()
&& !name.trim().contains(char::is_whitespace)
{
let v = p.imm(v).map_err(&fail)?;
p.equs.insert(name.trim().to_string(), v);
continue;
}
if let Some(d) = lower.strip_prefix('.') {
match d {
"syntax" => out.unified |= rest.eq_ignore_ascii_case("unified"),
"equ" | "set" => {
let (name, v) = rest.split_once(',').ok_or_else(|| fail("operands".into()))?;
let v = p.imm(v).map_err(&fail)?;
p.equs.insert(name.trim().to_string(), v);
}
"word" | "long" | "4byte" | "int" | "short" | "hword" | "2byte" | "byte" => {
let size = match d {
"byte" => 1,
"short" | "hword" | "2byte" => 2,
_ => 4,
};
for x in operands(rest) {
push(Item::Data(size, p.value(x).map_err(&fail)?));
}
}
"space" | "skip" | "zero" => {
let a = operands(rest);
let n = a
.first()
.ok_or_else(|| fail("size expected".into()))
.and_then(|x| p.imm(x).map_err(&fail))?;
let fill = match a.get(1) {
Some(x) => p.imm(x).map_err(&fail)?,
None => 0,
};
if n > 4096 {
return Err(fail("too large".into()));
}
for _ in 0..n {
push(Item::Data(1, Val::Imm(fill & 0xff)));
}
}
"ascii" | "asciz" | "string" => {
let lit = rest.strip_prefix('"').and_then(|x| x.strip_suffix('"'));
let lit = lit.ok_or_else(|| fail("string expected".into()))?;
let mut it = lit.bytes();
while let Some(c) = it.next() {
let c = if c == b'\\' {
match it.next() {
Some(b'n') => b'\n',
Some(b't') => b'\t',
Some(b'r') => b'\r',
Some(b'0') => 0,
Some(b'\\') => b'\\',
Some(b'"') => b'"',
_ => return Err(fail("escape sequence".into())),
}
} else {
c
};
push(Item::Data(1, Val::Imm(c as u32)));
}
if d != "ascii" {
push(Item::Data(1, Val::Imm(0)));
}
}
"align" | "p2align" | "balign" => {
let a = operands(rest);
let n = match a.first() {
Some(x) => p.imm(x).map_err(&fail)?,
None => 2,
};
if a.len() > 1 && p.imm(a[1]).map_err(&fail)? != 0 {
return Err(fail("fill value".into()));
}
let bytes = if d == "balign" {
n
} else {
1u32.checked_shl(n).unwrap_or(0)
};
if bytes == 0 || bytes > 4096 || !bytes.is_power_of_two() {
return Err(fail("alignment".into()));
}
push(Item::Align(bytes));
}
"pool" | "ltorg" => push(Item::Pool),
"section" | "text" | "data" | "bss" | "pushsection" | "popsection" | "previous" | "org" => {
push(Item::Section)
}
"thumb_func" => {}
"global" | "globl" => out.funcs.extend(operands(rest).iter().map(|x| x.to_string())),
"type" => {
if let Some((name, kind)) = rest.split_once(',')
&& kind.contains("function")
{
out.funcs.push(name.trim().to_string());
}
}
"thumb" | "code" | "cpu" | "arch" | "fpu" | "file" | "ident" | "size" | "weak" | "local"
| "func" | "endfunc" | "fnstart" | "fnend" | "cantunwind" | "end" | "eabi_attribute" | "extern"
| "hidden" | "force_thumb" | "loc" => {
if d == "code" && rest.trim() != "16" {
return Err(fail("ARM (32-bit) code is not supported".into()));
}
}
_ if d.starts_with("cfi_") => {}
_ => return Err(fail("unknown directive".into())),
}
continue;
}
let item = p
.insn(&lower, rest)
.or_else(|e| p.insn(&lower, &rest.to_ascii_lowercase()).map_err(|_| e));
push(item.map_err(&fail)?);
}
}
Ok(out)
}
#[derive(Debug)]
pub enum Fail {
Differs(String),
Unsupported(String),
}
#[derive(Debug, Default)]
pub struct Matched {
pub end: u32,
pub insns: usize,
pub ranges: Vec<(u32, u32)>,
pub closed: bool,
}
fn canon(op: Op) -> Op {
match op {
Op::Dp {
op: DpOp::Mov,
s: false,
rd: Some(8),
rn: None,
src:
Operand::Reg {
rm: 8,
shift: Shift::Lsl,
amount: 0,
},
} => Op::Nop,
Op::Dp { op, s, rd, rn, src } => {
let src = match src {
Operand::Imm { value, .. } => Operand::Imm { value, carry: None },
r => r,
};
if let (
DpOp::Add | DpOp::Adc | DpOp::And | DpOp::Orr | DpOp::Eor,
Some(a),
Operand::Reg {
rm,
shift: Shift::Lsl,
amount: 0,
},
) = (op, rn, src)
&& rm < a
{
return Op::Dp {
op,
s,
rd,
rn: Some(rm),
src: Operand::Reg {
rm: a,
shift: Shift::Lsl,
amount: 0,
},
};
}
Op::Dp { op, s, rd, rn, src }
}
Op::Mul { s, rd, rn, rm } => Op::Mul {
s,
rd,
rn: rn.min(rm),
rm: rn.max(rm),
},
Op::Store {
rt,
size: 4,
addr:
Addr::Base {
rn: 13,
offset: Offset::Imm(-4),
index: true,
wback: true,
},
} => Op::StoreMulti {
rn: 13,
regs: 1 << rt,
wback: true,
before: true,
},
Op::Load {
rt,
size: 4,
signed: false,
addr:
Addr::Base {
rn: 13,
offset: Offset::Imm(4),
index: false,
wback: true,
},
} => Op::LoadMulti {
rn: 13,
regs: 1 << rt,
wback: true,
before: false,
},
o => o,
}
}
fn untarget(op: Op) -> (Op, Option<u32>) {
match op {
Op::B { cond, target } => (Op::B { cond, target: 0 }, Some(target)),
Op::Bl { target } => (Op::Bl { target: 0 }, Some(target)),
Op::Cbz { nonzero, rn, target } => (Op::Cbz { nonzero, rn, target: 0 }, Some(target)),
Op::Adr { rd, target } => (Op::Adr { rd, target: 0 }, Some(target)),
Op::Load {
rt,
size,
signed,
addr: Addr::Lit(a),
} => (
Op::Load {
rt,
size,
signed,
addr: Addr::Lit(0),
},
Some(a),
),
o => (o, None),
}
}
fn with_s(op: Op) -> Op {
match op {
Op::Dp { op, rd, rn, src, .. } => Op::Dp {
op,
s: true,
rd,
rn,
src,
},
Op::ShiftReg { shift, rd, rn, rm, .. } => Op::ShiftReg {
shift,
s: true,
rd,
rn,
rm,
},
Op::Mul { rd, rn, rm, .. } => Op::Mul { s: true, rd, rn, rm },
o => o,
}
}
fn symbol_values(image: &Image, name: &str) -> Vec<u32> {
let mut v: Vec<u32> = (image.symbols.iter())
.filter(|s| s.name == name)
.map(|s| s.addr | (s.kind == SymKind::Func) as u32)
.collect();
v.extend((image.externals.iter().filter(|e| e.1 == name)).flat_map(|e| [*e.0 & !1, *e.0 | 1]));
v.sort_unstable();
v.dedup();
v
}
pub fn compare(image: &Image, lines: &[Line], start: u32, lenient_s: bool) -> Result<Matched, Fail> {
let mut pc = start & !1;
let mut m = Matched::default();
let mut labels: HashMap<&str, u32> = HashMap::new();
let mut targets: Vec<(&Val, u32, &Line, bool)> = Vec::new();
let mut literals: Vec<(&Val, u32, &Line)> = Vec::new();
let mut it_left = 0u8;
let at = |l: &Line| format!("line {}: `{}`", l.line, l.text);
let read = |a: u32, n: u32| -> Result<&[u8], Fail> {
image
.read(a, n)
.ok_or_else(|| Fail::Differs(format!("the binary ends at {a:#x}, the source goes on")))
};
let pad = |pc: &mut u32, n: u32, m: &mut Matched| -> Result<(), Fail> {
let from = *pc;
while !(*pc).is_multiple_of(n) {
if *pc & 1 == 1 {
if read(*pc, 1)?[0] != 0 {
return Err(Fail::Differs(format!("alignment padding at {:#x} is not zero", *pc)));
}
*pc += 1;
continue;
}
let b = read(*pc, 2)?;
if !matches!(u16::from_le_bytes([b[0], b[1]]), 0 | 0xbf00 | 0x46c0) {
return Err(Fail::Differs(format!(
"the binary has something other than padding at {:#x}, where the source aligns",
*pc
)));
}
*pc += 2;
}
if *pc > from {
m.ranges.push((from, *pc));
}
Ok(())
};
let pool = |pc: &mut u32, literals: &[(&Val, u32, &Line)], m: &mut Matched| -> Result<(), Fail> {
loop {
let a = (*pc).next_multiple_of(4);
if !literals.iter().any(|l| l.1 == a) {
return Ok(());
}
pad(pc, 4, m)?;
*pc = a + 4;
}
};
for l in lines {
match &l.item {
Item::Label(name) => {
labels.insert(name, pc);
}
Item::Section => {
return Err(Fail::Unsupported(format!(
"{}: a change of section in the middle of a routine",
at(l)
)));
}
Item::Align(n) => {
pool(&mut pc, &literals, &mut m)?;
pad(&mut pc, *n, &mut m)?
}
Item::Pool => pool(&mut pc, &literals, &mut m)?,
Item::Data(size, val) => {
let b = read(pc, *size as u32)?;
let have = b.iter().rev().fold(0u32, |v, &x| v << 8 | x as u32);
match val {
Val::Imm(v) => {
let mask = if *size == 4 { u32::MAX } else { (1 << (8 * *size)) - 1 };
if have != v & mask {
return Err(Fail::Differs(format!("{}: the binary has {have:#x} at {pc:#x}", at(l))));
}
}
Val::Sym(..) if *size == 4 => literals.push((val, pc, l)),
Val::Sym(..) => return Err(Fail::Unsupported(format!("{}: a symbol in less than a word", at(l)))),
}
m.ranges.push((pc, pc + *size as u32));
pc += *size as u32;
}
Item::LoadLit(rt, val) => {
let b = read(pc, 4).or_else(|_| read(pc, 2))?;
let insn = decode(b, pc, it_left > 0).unwrap();
it_left = it_left.saturating_sub(1);
match (canon(insn.op), val) {
(
Op::Load {
rt: r,
size: 4,
signed: false,
addr: Addr::Lit(a),
},
_,
) if r == *rt => literals.push((val, a, l)),
(
Op::Dp {
op: DpOp::Mov,
s: false,
rd: Some(r),
rn: None,
src: Operand::Imm { value, .. },
},
Val::Imm(v),
) if r == *rt && value == *v => {}
(
Op::Dp {
op: DpOp::Mvn,
s: false,
rd: Some(r),
rn: None,
src: Operand::Imm { value, .. },
},
Val::Imm(v),
) if r == *rt && !value == *v => {}
(have, _) => {
return Err(Fail::Differs(format!("{}: the binary has `{have}` at {pc:#x}", at(l))));
}
}
m.closed = false;
m.ranges.push((pc, pc + insn.len as u32));
m.insns += 1;
pc += insn.len as u32;
}
Item::Insn(op, sym) => {
let b = read(pc, 4).or_else(|_| read(pc, 2))?;
let insn = decode(b, pc, it_left > 0).unwrap();
let (mut have, mut target) = untarget(canon(insn.op));
let mut want = canon(*op);
if let Op::Load {
rt,
size,
signed,
addr:
Addr::Base {
rn: 15,
offset: Offset::Imm(n),
index: true,
wback: false,
},
} = want
&& sym.is_none()
&& target.is_some()
&& matches!(have, Op::Load { .. })
{
let addr = Addr::Lit(((pc + 4) & !3).wrapping_add(n as u32));
want = Op::Load { rt, size, signed, addr };
have = canon(insn.op);
target = None;
}
let low_mov = match want {
Op::Dp {
op: DpOp::Mov,
s: false,
rd: Some(rd),
rn: None,
src:
Operand::Reg {
rm,
shift: Shift::Lsl,
amount: 0,
},
} if rd < 8 && rm < 8 => Some(Op::Dp {
op: DpOp::Add,
s: true,
rd: Some(rd),
rn: Some(rm),
src: Operand::Imm { value: 0, carry: None },
}),
_ => None,
};
let same = have == want
|| (lenient_s && insn.len == 2 && it_left == 0 && (have == with_s(want) || Some(have) == low_mov));
if !same || target.is_some() != sym.is_some() {
return Err(Fail::Differs(format!(
"{}: the binary has `{}` at {pc:#x}",
at(l),
insn.op
)));
}
if let (Some(t), Some(v)) = (target, sym) {
if matches!(have, Op::Load { .. }) {
targets.push((v, t, l, false));
} else {
targets.push((v, t, l, true));
}
}
m.closed = it_left == 0
&& match insn.op {
Op::B { cond: Cond::Al, .. } | Op::Bx { .. } | Op::Udf => true,
Op::LoadMulti { regs, .. } => regs & 0x8000 != 0,
_ => false,
};
it_left = match insn.op {
Op::It { mask, .. } if mask & 0xf != 0 => 4 - (mask & 0xf).trailing_zeros() as u8,
_ => it_left.saturating_sub(1),
};
m.ranges.push((pc, pc + insn.len as u32));
m.insns += 1;
pc += insn.len as u32;
}
}
}
pool(&mut pc, &literals, &mut m)?;
m.end = pc;
let resolve = |v: &Val, l: &Line| -> Result<Vec<u32>, Fail> {
match v {
Val::Imm(k) => Ok(vec![*k]),
Val::Sym(name, add) => {
let mut c: Vec<u32> = match labels.get(name.as_str()) {
Some(&a) => vec![a, a | 1],
None => symbol_values(image, name),
};
if c.is_empty() && image.meta.present && !image.soft_bounds {
return Err(Fail::Differs(format!(
"{}: the binary neither defines nor refers to `{}`",
at(l),
name.split('\u{1}').next().unwrap_or(name)
)));
}
if c.is_empty() {
return Err(Fail::Unsupported(format!(
"{}: `{}` is not a label of the routine nor a symbol of the binary",
at(l),
name.split('\u{1}').next().unwrap_or(name)
)));
}
for x in &mut c {
*x = x.wrapping_add(*add as u32);
}
Ok(c)
}
}
};
for (v, t, l, code) in targets {
let c = resolve(v, l)?;
if !c.iter().any(|&x| if code { x & !1 == t & !1 } else { x == t }) {
return Err(Fail::Differs(format!(
"{}: in the binary it refers to {t:#x}, in the source to {}",
at(l),
c.iter()
.map(|x| format!("{:#x}", x & !(code as u32)))
.collect::<Vec<_>>()
.join(" or ")
)));
}
}
for (v, a, l) in literals {
let b = read(a, 4)?;
let have = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
let c = resolve(v, l)?;
if !c.contains(&have) {
return Err(Fail::Differs(format!(
"{}: the binary's literal at {a:#x} is {have:#x}, the source's value is {}",
at(l),
c.iter().map(|x| format!("{x:#x}")).collect::<Vec<_>>().join(" or ")
)));
}
m.ranges.push((a, a + 4));
}
Ok(m)
}
#[cfg(test)]
mod tests {
use super::*;
fn ops(text: &str) -> Vec<Op> {
(parse(text).unwrap().lines.into_iter())
.filter_map(|l| match l.item {
Item::Insn(op, _) => Some(op),
_ => None,
})
.collect()
}
#[test]
fn mnemonics() {
assert_eq!(mnemonic("bls"), Some(("b", false, Cond::Ls)));
assert_eq!(mnemonic("bl"), Some(("bl", false, Cond::Al)));
assert_eq!(mnemonic("bics"), Some(("bic", true, Cond::Al)));
assert_eq!(mnemonic("bcs"), Some(("b", false, Cond::Cs)));
assert_eq!(mnemonic("movseq"), Some(("mov", true, Cond::Eq)));
assert_eq!(mnemonic("ldrsb"), Some(("ldrsb", false, Cond::Al)));
assert_eq!(mnemonic("b.n"), Some(("b", false, Cond::Al)));
assert_eq!(mnemonic("blx"), Some(("blx", false, Cond::Al)));
assert_eq!(mnemonic("teq"), Some(("teq", false, Cond::Al)));
assert_eq!(mnemonic("frob"), None);
}
#[test]
fn statements() {
let o = ops("str r4, [r0, #12] @ c\n mov r1, r8; movs r0, #1\n push {r4-r6, lr}\n ldr r3, [r1], #4");
assert_eq!(o.len(), 5);
assert_eq!(
o[0],
Op::Store {
rt: 4,
size: 4,
addr: Addr::Base {
rn: 0,
offset: Offset::Imm(12),
index: true,
wback: false
}
}
);
assert_eq!(
o[3],
Op::StoreMulti {
rn: 13,
regs: 0x4070,
wback: true,
before: true
}
);
assert!(parse("frob r0").is_err());
assert!(parse(".code 32").is_err());
let s = parse("1: b 1b\n b 1f\n1: .word 0x10, sym+4\n x = 3\n .byte x").unwrap();
assert!(matches!(&s.lines[1].item, Item::Insn(_, Some(Val::Sym(n, 0))) if n == "1\u{1}1"));
assert!(matches!(&s.lines[2].item, Item::Insn(_, Some(Val::Sym(n, 0))) if n == "1\u{1}2"));
assert!(matches!(&s.lines[5].item, Item::Data(4, Val::Sym(n, 4)) if n == "sym"));
assert!(matches!(&s.lines[6].item, Item::Data(1, Val::Imm(3))));
}
}