use crate::image::{Image, SymKind};
use crate::thumb::decode::{Addr, Cond, DpOp, Insn, Offset, Op, Operand, decode};
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OptLevel {
O0,
O1,
O2,
O3,
Os,
Oz,
Og,
}
impl OptLevel {
pub const ALL: [OptLevel; 7] = [
OptLevel::O0,
OptLevel::O1,
OptLevel::O2,
OptLevel::O3,
OptLevel::Os,
OptLevel::Oz,
OptLevel::Og,
];
}
impl fmt::Display for OptLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
OptLevel::O0 => "-O0",
OptLevel::O1 => "-O1",
OptLevel::O2 => "-O2",
OptLevel::O3 => "-O3",
OptLevel::Os => "-Os",
OptLevel::Oz => "-Oz",
OptLevel::Og => "-Og",
})
}
}
#[derive(Clone, Debug, Default)]
pub struct Features {
pub funcs: u32,
pub insns: u32,
pub frame_pointer_funcs: u32,
pub frame_accesses: u32,
pub loops_top_tested: u32,
pub loops_entry_jump: u32,
pub loops_rotated: u32,
pub loops_with_remainder: u32,
pub loop_funcs: u32,
pub loop_func_bytes: u32,
pub branch_adjacent: u32,
pub branch_separated: u32,
pub it_blocks: u32,
pub div_by_immediate: u32,
pub long_multiplies: u32,
pub starts_padded: u32,
pub starts_unpadded: u32,
pub clones: u32,
pub dual_accesses: u32,
pub windows: u32,
pub repeated_windows: u32,
pub wide_baseline: u32,
pub wide_mainline: u32,
pub cbz: u32,
pub hw_divides: u32,
pub movw_movt: u32,
pub dsp_insns: u32,
pub fp_insns: u32,
pub undecoded: u32,
pub leaf_funcs: u32,
pub nonleaf_funcs: u32,
pub fp_leaf: u32,
pub fp_nonleaf: u32,
pub framed_leaf: u32,
pub arg_spills: u32,
pub push_r7_lr_pad: u32,
pub push_r3_pad: u32,
pub push_r4_pad: u32,
pub fp_add: u32,
pub fp_mov: u32,
pub add_pc: u32,
pub literal_loads: u32,
pub r9_reads: u32,
pub r9_writes: u32,
pub table_branches: u32,
pub computed_jumps: u32,
pub dense_compare_chains: u32,
pub longest_compare_chain: u32,
pub bytewise_loads: u32,
pub bytewise_stores: u32,
pub direct_calls: u32,
pub indirect_calls: u32,
pub literal_calls: u32,
pub tail_calls: u32,
pub helper_div_by_immediate: u32,
pub outlined: u32,
pub code_bytes: u32,
pub local_funcs: u32,
pub local_tiny_single_caller: u32,
pub pad_nop: u32,
pub pad_mov_r8: u32,
pub pad_zero: u32,
pub movs_lsls_consts: u32,
pub abs_ro_refs: u32,
pub abs_rw_refs: u32,
pub assembled_words: u32,
pub odd_word_access: u32,
pub direct_extern_calls: u32,
pub soft_float_calls: u32,
}
struct Decoded {
addr: u32,
insn: Insn,
in_it: bool,
}
fn decode_function(image: &Image, start: u32, size: u32) -> Vec<Decoded> {
let mut out = Vec::new();
let mut pc = start;
let end = start.saturating_add(size);
let mut it_left = 0u32;
let guess_pools = image.data_ranges.is_empty();
let mut literals: std::collections::BTreeSet<u32> = Default::default();
while pc < end {
if guess_pools && literals.contains(&(pc & !3)) {
pc = (pc & !3) + 4;
it_left = 0;
continue;
}
if image.is_data_in_code(pc) {
match image.data_ranges.iter().find(|&&(a, b)| pc >= a && pc < b) {
Some(&(_, b)) => pc = b.max(pc + 2),
None => pc += 2,
}
it_left = 0;
continue;
}
let n = (end - pc).min(4);
let Some(bytes) = image.read(pc, n) else { break };
let in_it = it_left > 0;
let Some(insn) = decode(bytes, pc, in_it) else { break };
if in_it {
it_left -= 1;
} else if let Op::It { mask, .. } = insn.op {
it_left = 4 - (mask & 0xf).trailing_zeros().min(3);
}
if let Op::Load { addr: Addr::Lit(a), .. } = insn.op {
literals.insert(a & !3);
}
out.push(Decoded { addr: pc, insn, in_it });
pc += insn.len as u32;
}
out
}
fn sets_flags(op: &Op) -> bool {
match *op {
Op::Dp { s, rd, .. } => s || rd.is_none(),
Op::ShiftReg { s, .. } | Op::Mul { s, .. } => s,
_ => false,
}
}
fn is_compare(op: &Op) -> bool {
matches!(op, Op::Dp { rd: None, .. })
}
fn shape(op: &Op) -> u32 {
match *op {
Op::Dp { op, s, rd, src, .. } => {
1 | (op as u32) << 8
| (s as u32) << 16
| (rd.is_none() as u32) << 17
| (matches!(src, Operand::Imm { .. }) as u32) << 18
}
Op::Load { size, signed, addr, .. } => 2 | (size as u32) << 8 | (signed as u32) << 16 | addr_shape(&addr) << 17,
Op::Store { size, addr, .. } => 3 | (size as u32) << 8 | addr_shape(&addr) << 17,
Op::B { cond, .. } => 4 | (cond as u32) << 8,
Op::ShiftReg { shift, .. } => 5 | (shift as u32) << 8,
Op::Mul { .. } => 6,
Op::Mla { .. } => 7,
Op::Mls { .. } => 8,
Op::MulLong { signed, accumulate, .. } => 9 | (signed as u32) << 8 | (accumulate as u32) << 9,
Op::Div { signed, .. } => 10 | (signed as u32) << 8,
Op::LoadDual { .. } => 11,
Op::StoreDual { .. } => 12,
Op::LoadMulti { .. } => 13,
Op::StoreMulti { .. } => 14,
Op::Bl { .. } => 15,
Op::Bx { .. } => 16,
Op::Blx { .. } => 17,
Op::Cbz { nonzero, .. } => 18 | (nonzero as u32) << 8,
Op::It { cond, mask } => 19 | (cond as u32) << 8 | (mask as u32) << 16,
Op::Extend { signed, size, .. } => 20 | (signed as u32) << 8 | (size as u32) << 9,
Op::Bfx { signed, .. } => 21 | (signed as u32) << 8,
Op::Movt { .. } => 22,
Op::Adr { .. } => 23,
Op::TableBranch { .. } => 24,
Op::Nop => 25,
_ => 26,
}
}
fn addr_shape(a: &Addr) -> u32 {
match a {
Addr::Lit(_) => 0,
Addr::Base {
offset: Offset::Imm(_),
wback: false,
..
} => 1,
Addr::Base {
offset: Offset::Imm(_), ..
} => 2,
Addr::Base { .. } => 3,
}
}
fn frame_access(addr: &Addr) -> bool {
matches!(
addr,
Addr::Base {
rn: 7 | 13,
offset: Offset::Imm(_),
wback: false,
..
}
)
}
pub fn features(image: &Image) -> Features {
let mut f = Features::default();
let mut funcs: Vec<(u32, u32, &str)> = image
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func && s.size >= 2 && image.segment_at(s.addr).is_some_and(|g| g.exec))
.map(|s| (s.addr, s.size, s.name.as_str()))
.collect();
funcs.sort();
funcs.dedup_by_key(|x| x.0);
for &(_, _, name) in &funcs {
if [".constprop", ".isra", ".part"].iter().any(|k| name.contains(k)) {
f.clones += 1;
}
}
for w in funcs.windows(2) {
let end = w[0].0 + w[0].1;
if end % 4 == 2 {
if w[1].0 == end {
f.starts_unpadded += 1;
} else if w[1].0 == end + 2 {
f.starts_padded += 1;
}
}
}
let starts: Vec<u32> = funcs.iter().map(|x| x.0).collect();
for &(addr, size, _) in &funcs {
let code = decode_function(image, addr, size);
if code.is_empty() {
continue;
}
f.funcs += 1;
f.insns += code.len() as u32;
let is_fp = code.iter().take(6).any(|d| {
matches!(
d.insn.op,
Op::Dp {
op: DpOp::Add,
rd: Some(7),
rn: Some(13),
src: Operand::Imm { .. },
..
} | Op::Dp {
op: DpOp::Mov,
rd: Some(7),
src: Operand::Reg { rm: 13, .. },
..
}
)
});
f.frame_pointer_funcs += is_fp as u32;
let shapes: Vec<u32> = code.iter().map(|d| shape(&d.insn.op)).collect();
let mut seen = std::collections::HashSet::new();
for w in shapes.windows(4) {
f.windows += 1;
if !seen.insert([w[0], w[1], w[2], w[3]]) {
f.repeated_windows += 1;
}
}
let mut has_loop = false;
for (i, d) in code.iter().enumerate() {
let prev = if i > 0 { Some(&code[i - 1]) } else { None };
match d.insn.op {
Op::Load { addr: a, .. } | Op::Store { addr: a, .. } => f.frame_accesses += frame_access(&a) as u32,
Op::LoadDual { addr: a, .. } | Op::StoreDual { addr: a, .. } => {
if frame_access(&a) {
f.frame_accesses += 1;
} else {
f.dual_accesses += 1;
}
}
Op::It { .. } => f.it_blocks += 1,
Op::MulLong { accumulate: false, .. } => f.long_multiplies += 1,
Op::Div { rm, .. } => {
if let Some(p) = prev
&& matches!(p.insn.op, Op::Dp { op: DpOp::Mov, rd: Some(r), src: Operand::Imm { .. }, .. } if r == rm)
{
f.div_by_immediate += 1;
}
}
Op::B { cond, target } => {
if cond != Cond::Al
&& !d.in_it
&& let Some(p) = prev
{
if sets_flags(&p.insn.op) {
f.branch_adjacent += 1;
} else {
f.branch_separated += 1;
}
}
if target <= d.addr && target >= addr && !d.in_it {
if cond == Cond::Al {
let tested = code.iter().skip_while(|e| e.addr < target).take(4).any(|e| {
matches!(e.insn.op, Op::B { cond: c, target: t } if c != Cond::Al && t > e.addr)
|| matches!(e.insn.op, Op::Cbz { .. })
});
if tested {
has_loop = true;
f.loops_top_tested += 1;
}
} else {
has_loop = true;
let entry = code.iter().any(|e| {
e.addr < target
&& matches!(e.insn.op, Op::B { cond: Cond::Al, target: t } if t > target && t <= d.addr)
});
if entry {
f.loops_entry_jump += 1;
} else {
f.loops_rotated += 1;
let next = &code[i + 1..];
let rem = next.iter().take(2).any(|n| is_compare(&n.insn.op))
&& next.iter().take(3).any(|n| {
matches!(n.insn.op, Op::B { cond: c, target: t } if c != Cond::Al && t > n.addr)
});
f.loops_with_remainder += rem as u32;
}
}
}
}
_ => {}
}
}
if has_loop {
f.loop_funcs += 1;
f.loop_func_bytes += size;
}
function_features(image, addr, size, &code, &starts, &mut f);
}
global_features(image, &funcs, &mut f);
f
}
fn operand_reads(src: &Operand) -> u16 {
match *src {
Operand::Reg { rm, .. } => 1 << rm,
Operand::Imm { .. } => 0,
}
}
fn addr_reads(a: &Addr) -> u16 {
match *a {
Addr::Lit(_) => 0,
Addr::Base { rn, offset, .. } => {
(1 << rn)
| match offset {
Offset::Reg { rm, .. } => 1 << rm,
Offset::Imm(_) => 0,
}
}
}
}
fn reg_use(op: &Op) -> (u16, u16) {
let b = |r: u8| 1u16 << r;
let o = |r: Option<u8>| r.map_or(0, b);
match *op {
Op::Dp { rd, rn, src, .. } => (o(rn) | operand_reads(&src), o(rd)),
Op::ShiftReg { rd, rn, rm, .. } | Op::Mul { rd, rn, rm, .. } | Op::Div { rd, rn, rm, .. } => {
(b(rn) | b(rm), b(rd))
}
Op::Movt { rd, .. } => (b(rd), b(rd)),
Op::Adr { rd, .. } => (0, b(rd)),
Op::Mla { rd, rn, rm, ra } | Op::Mls { rd, rn, rm, ra } => (b(rn) | b(rm) | b(ra), b(rd)),
Op::MulHalves { rd, rn, rm, ra, .. } => (b(rn) | b(rm) | o(ra), b(rd)),
Op::MulLong { rdlo, rdhi, rn, rm, .. } => (b(rn) | b(rm), b(rdlo) | b(rdhi)),
Op::Load { rt, addr, .. } => (addr_reads(&addr), b(rt)),
Op::Store { rt, addr, .. } => (addr_reads(&addr) | b(rt), 0),
Op::LoadDual { rt, rt2, addr } => (addr_reads(&addr), b(rt) | b(rt2)),
Op::StoreDual { rt, rt2, addr } => (addr_reads(&addr) | b(rt) | b(rt2), 0),
Op::LoadMulti { rn, regs, .. } => (b(rn), regs),
Op::StoreMulti { rn, regs, .. } => (b(rn) | regs, 0),
Op::Bx { rm } | Op::Blx { rm } => (b(rm), 0),
Op::Cbz { rn, .. } => (b(rn), 0),
Op::TableBranch { rn, rm, .. } => (b(rn) | b(rm), 0),
Op::Bfi { rd, rn, .. } => (b(rd) | b(rn), b(rd)),
Op::Bfc { rd, .. } => (b(rd), b(rd)),
Op::Bfx { rd, rn, .. } | Op::Sat { rd, rn, .. } => (b(rn), b(rd)),
Op::Extend { rd, rn, rm, .. } => (o(rn) | b(rm), b(rd)),
Op::Clz { rd, rm } | Op::Rbit { rd, rm } | Op::Rev { rd, rm } | Op::Rev16 { rd, rm } | Op::Revsh { rd, rm } => {
(b(rm), b(rd))
}
_ => (0, 0),
}
}
const DIV_HELPERS: [&str; 8] = [
"__aeabi_uidiv",
"__aeabi_idiv",
"__aeabi_uidivmod",
"__aeabi_idivmod",
"__udivsi3",
"__divsi3",
"__umodsi3",
"__modsi3",
];
fn function_features(image: &Image, start: u32, size: u32, code: &[Decoded], starts: &[u32], f: &mut Features) {
let end = start + size;
f.code_bytes += size;
let mut leaf = true;
let (mut reads, mut writes) = (0u16, 0u16);
let mut cmp_consts: [Vec<u32>; 16] = Default::default();
for (i, d) in code.iter().enumerate() {
let op = &d.insn.op;
let (r, w) = reg_use(op);
if !matches!(op, Op::StoreMulti { rn: 13, .. } | Op::LoadMulti { rn: 13, .. }) {
reads |= r;
writes |= w;
f.r9_reads += (r >> 9 & 1) as u32;
f.r9_writes += (w >> 9 & 1) as u32;
}
if d.insn.len == 4 {
match op {
Op::Bl { .. } | Op::Sys(_) => {}
Op::B { .. } | Op::Movt { .. } | Op::Div { .. } => f.wide_baseline += 1,
Op::Dp {
op: DpOp::Mov,
s: false,
src: Operand::Imm { .. },
..
} => f.wide_baseline += 1,
Op::Unsupported(w) => {
f.undecoded += 1;
if (w >> 24) & 0xec == 0xec && (w >> 24) & 0x10 == 0 {
f.fp_insns += 1;
}
}
_ => f.wide_mainline += 1,
}
} else if matches!(op, Op::Unsupported(_)) {
f.undecoded += 1;
}
match *op {
Op::Cbz { .. } => f.cbz += 1,
Op::Div { .. } => f.hw_divides += 1,
Op::Movt { .. } => f.movw_movt += 1,
Op::MulHalves { .. } => f.dsp_insns += 1,
Op::TableBranch { .. } => f.table_branches += 1,
Op::Load { addr: Addr::Lit(_), .. } => f.literal_loads += 1,
Op::Dp {
op: DpOp::Add,
src: Operand::Reg { rm: 15, .. },
rd,
..
} if rd != Some(15) => f.add_pc += 1,
Op::Dp {
op: DpOp::Sub,
rd: None,
rn: Some(rn),
src: Operand::Imm { value, .. },
..
} if !cmp_consts[rn as usize].contains(&value) => cmp_consts[rn as usize].push(value),
Op::Bl { target } => {
leaf = false;
f.direct_calls += 1;
let name = image
.externals
.get(&(target & !1))
.map(String::as_str)
.or_else(|| image.func_at(target & !1).map(|s| s.name.as_str()))
.unwrap_or("");
if DIV_HELPERS.contains(&name) {
let konst = code[i.saturating_sub(3)..i].iter().any(|p| {
matches!(
p.insn.op,
Op::Dp {
op: DpOp::Mov,
rd: Some(1),
src: Operand::Imm { .. },
..
}
) || matches!(
p.insn.op,
Op::Load {
rt: 1,
addr: Addr::Lit(_),
..
}
)
});
f.helper_div_by_immediate += konst as u32;
}
}
Op::Blx { rm } => {
leaf = false;
f.indirect_calls += 1;
if code[i.saturating_sub(3)..i]
.iter()
.any(|p| matches!(p.insn.op, Op::Load { rt, addr: Addr::Lit(_), .. } if rt == rm))
{
f.literal_calls += 1;
}
}
Op::B { cond: Cond::Al, target }
if !d.in_it
&& (target < start || target >= end)
&& (starts.binary_search(&(target & !1)).is_ok()
|| image.externals.contains_key(&(target & !1))) =>
{
leaf = false;
f.tail_calls += 1;
}
_ => {}
}
let abs = match *op {
Op::Load {
size: 4,
addr: Addr::Lit(a),
..
} => image.read(a, 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
Op::Movt { rd, imm } => code[i.saturating_sub(2)..i].iter().rev().find_map(|p| match p.insn.op {
Op::Dp {
op: DpOp::Mov,
s: false,
rd: Some(r),
src: Operand::Imm { value, .. },
..
} if r == rd && p.insn.len == 4 => Some((imm as u32) << 16 | (value & 0xffff)),
_ => None,
}),
_ => None,
};
if let Some(v) = abs
&& let Some(seg) = image.segment_at(v & !1)
{
if seg.writable {
f.abs_rw_refs += 1;
} else {
f.abs_ro_refs += 1;
}
}
match *op {
Op::Load {
size: 2 | 4,
addr:
Addr::Base {
rn,
offset: Offset::Imm(o),
..
},
..
}
| Op::Store {
size: 2 | 4,
addr:
Addr::Base {
rn,
offset: Offset::Imm(o),
..
},
..
} if o & 1 == 1 && rn != 13 && rn != 15 => f.odd_word_access += 1,
Op::Bl { target } => {
if let Some(name) = image.externals.get(&(target & !1)) {
f.direct_extern_calls += 1;
let n = name.as_str();
if (n.starts_with("__aeabi_f")
|| n.starts_with("__aeabi_d")
|| n.starts_with("__aeabi_i2")
|| n.starts_with("__aeabi_ui2")
|| n.starts_with("__aeabi_l2")
|| n.starts_with("__aeabi_ul2"))
&& !n.contains("div")
{
f.soft_float_calls += 1;
}
}
}
_ => {}
}
let (_, w) = reg_use(op);
if w >> 15 & 1 == 1 && !matches!(op, Op::LoadMulti { rn: 13, .. }) {
f.computed_jumps += 1;
}
if let Op::Dp {
op: DpOp::Mov,
rd: Some(rd),
src: Operand::Imm { .. },
..
} = *op
&& d.insn.len == 2
&& let Some(n) = code.get(i + 1)
&& matches!(n.insn.op, Op::Dp { op: DpOp::Mov, rd: Some(r2), src: Operand::Reg { rm, shift: crate::thumb::decode::Shift::Lsl, amount }, .. } if r2 == rd && rm == rd && amount > 0)
{
f.movs_lsls_consts += 1;
}
}
for consts in &cmp_consts {
let n = consts.len() as u32;
f.longest_compare_chain = f.longest_compare_chain.max(n);
if n >= 5 {
let (lo, hi) = (*consts.iter().min().unwrap(), *consts.iter().max().unwrap());
if hi - lo < 3 * n {
f.dense_compare_chains += 1;
}
}
}
let mut assembled = 0;
for (kind, counter) in [(false, &mut f.bytewise_loads), (true, &mut f.bytewise_stores)] {
let mut seen: Vec<(u8, i32, usize)> = Vec::new(); for (i, d) in code.iter().enumerate() {
let hit = match d.insn.op {
Op::Load {
size: 1,
addr:
Addr::Base {
rn,
offset: Offset::Imm(o),
wback: false,
..
},
..
} if !kind => Some((rn, o)),
Op::Store {
size: 1,
addr:
Addr::Base {
rn,
offset: Offset::Imm(o),
wback: false,
..
},
..
} if kind => Some((rn, o)),
_ => None,
};
if let Some((rn, o)) = hit
&& rn != 13
&& rn != 7
{
seen.push((rn, o, i));
}
}
let mut used = vec![false; seen.len()];
for a in 0..seen.len() {
if used[a] {
continue;
}
let (rn, o, i) = seen[a];
let group: Vec<usize> = (0..4)
.filter_map(|k| {
seen.iter()
.position(|&(r2, o2, i2)| r2 == rn && o2 == o + k && i2 >= i && i2 - i <= 16)
})
.collect();
if group.len() == 4 {
let (first, last) = (seen[group[0]].2, group.iter().map(|&g| seen[g].2).max().unwrap());
for &g in &group {
used[g] = true;
}
*counter += 1;
let shifts = code[first..(last + 8).min(code.len())]
.iter()
.filter(|d| {
matches!(
d.insn.op,
Op::Dp {
src: Operand::Reg {
shift: crate::thumb::decode::Shift::Lsl,
amount: 8 | 16 | 24,
..
},
..
}
)
})
.count();
if !kind && shifts >= 2 {
assembled += 1;
}
}
}
}
f.assembled_words += assembled;
let head = &code[..code.len().min(8)];
let push = head.iter().find_map(|d| match d.insn.op {
Op::StoreMulti {
rn: 13,
regs,
wback: true,
before: true,
} => Some(regs),
_ => None,
});
let sp_adjust = head.iter().any(|d| {
matches!(
d.insn.op,
Op::Dp {
op: DpOp::Sub,
rd: Some(13),
rn: Some(13),
..
}
)
});
let fp_add = head.iter().any(|d| {
matches!(
d.insn.op,
Op::Dp {
op: DpOp::Add,
rd: Some(7),
rn: Some(13),
src: Operand::Imm { .. },
..
}
)
});
let fp_mov = head.iter().any(|d| {
matches!(
d.insn.op,
Op::Dp {
op: DpOp::Mov,
rd: Some(7),
src: Operand::Reg { rm: 13, .. },
..
}
)
});
let is_fp = fp_add || fp_mov;
f.fp_add += fp_add as u32;
f.fp_mov += fp_mov as u32;
if leaf {
f.leaf_funcs += 1;
f.fp_leaf += is_fp as u32;
f.framed_leaf += (push.is_some() || sp_adjust) as u32;
} else {
f.nonleaf_funcs += 1;
f.fp_nonleaf += is_fp as u32;
}
if let Some(regs) = push {
let untouched = |r: u8| (reads | writes) >> r & 1 == 0;
if regs == (1 << 7 | 1 << 14) && untouched(7) {
f.push_r7_lr_pad += 1;
}
if regs >> 3 & 1 == 1 {
f.push_r3_pad += 1;
}
if regs >> 4 & 1 == 1 && regs >> 14 & 1 == 1 && untouched(4) {
f.push_r4_pad += 1;
}
}
f.arg_spills +=
head.iter()
.any(|d| matches!(d.insn.op, Op::Store { rt: 0, size: 4, addr, .. } if frame_access(&addr))) as u32;
}
fn global_features(image: &Image, funcs: &[(u32, u32, &str)], f: &mut Features) {
f.outlined = funcs.iter().filter(|x| x.2.starts_with("OUTLINED_FUNCTION_")).count() as u32;
for w in funcs.windows(2) {
let (mut a, b) = (w[0].0 + w[0].1, w[1].0);
if b <= a || b - a > 14 || image.is_data_in_code(a) {
continue;
}
while a + 2 <= b {
match image.read(a, 2).map(|x| u16::from_le_bytes([x[0], x[1]])) {
Some(0xbf00) => f.pad_nop += 1,
Some(0x46c0) => f.pad_mov_r8 += 1,
Some(0) => f.pad_zero += 1,
_ => {}
}
a += 2;
}
}
let mut callers: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
for &(addr, size, _) in funcs {
for d in decode_function(image, addr, size) {
if let Op::Bl { target } = d.insn.op {
*callers.entry(target & !1).or_default() += 1;
}
}
}
for s in image
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func && !s.global && s.size >= 2)
{
if s.name.starts_with("OUTLINED_FUNCTION_") {
continue;
}
f.local_funcs += 1;
if s.size <= 24 && callers.get(&s.addr) == Some(&1) {
f.local_tiny_single_caller += 1;
}
}
}
fn ratio(a: u32, b: u32) -> f32 {
if a + b == 0 { 0.0 } else { a as f32 / (a + b) as f32 }
}
pub fn build_attributes(raw: &[u8]) -> Vec<(&'static str, String)> {
fn uleb(b: &[u8], p: &mut usize) -> Option<u64> {
let mut v = 0u64;
let mut shift = 0;
loop {
let c = *b.get(*p)?;
*p += 1;
if shift < 64 {
v |= ((c & 0x7f) as u64) << shift;
}
shift += 7;
if c & 0x80 == 0 {
return Some(v);
}
}
}
fn ntbs(b: &[u8], p: &mut usize) -> Option<String> {
let end = b[*p..].iter().position(|&c| c == 0)? + *p;
let s = String::from_utf8_lossy(&b[*p..end]).into_owned();
*p = end + 1;
Some(s)
}
fn pick(names: &[&str], v: u64) -> String {
names.get(v as usize).map_or_else(|| v.to_string(), |s| s.to_string())
}
let mut out = Vec::new();
if raw.first() != Some(&b'A') {
return out;
}
let mut p = 1;
while p + 4 <= raw.len() {
let len = u32::from_le_bytes([raw[p], raw[p + 1], raw[p + 2], raw[p + 3]]) as usize;
let end = (p + len).min(raw.len());
let mut q = p + 4;
let Some(vendor) = ntbs(&raw[..end], &mut q) else { break };
while vendor == "aeabi" && q + 5 <= end {
let tag = raw[q];
let sublen = u32::from_le_bytes([raw[q + 1], raw[q + 2], raw[q + 3], raw[q + 4]]) as usize;
let subend = (q + sublen).min(end);
let b = &raw[..subend];
let mut r = q + 5;
while tag == 1 && r < subend {
let Some(t) = uleb(b, &mut r) else { break };
let is_str = matches!(t, 4 | 5 | 65 | 67) || (t > 32 && t % 2 == 1);
if t == 32 {
let _ = uleb(b, &mut r);
let _ = ntbs(b, &mut r);
continue;
}
if is_str {
let Some(s) = ntbs(b, &mut r) else { break };
match t {
4 => out.push(("Tag_CPU_raw_name", s)),
5 => out.push(("Tag_CPU_name", s)),
67 => out.push(("Tag_conformance", s)),
_ => {}
}
continue;
}
let Some(v) = uleb(b, &mut r) else { break };
let e: Option<(&'static str, String)> = match t {
6 => Some((
"Tag_CPU_arch",
pick(
&[
"pre-v4",
"v4",
"v4T",
"v5T",
"v5TE",
"v5TEJ",
"v6",
"v6KZ",
"v6T2",
"v6K",
"v7",
"v6-M",
"v6S-M",
"v7E-M",
"v8-A",
"v8-R",
"v8-M.baseline",
"v8-M.mainline",
"v8.1-A",
"v8.2-A",
"v8.3-A",
"v8.1-M.mainline",
"v9",
],
v,
),
)),
7 => Some(("Tag_CPU_arch_profile", (v as u8 as char).to_string())),
9 => Some(("Tag_THUMB_ISA_use", pick(&["none", "Thumb-1", "Thumb-2", "yes"], v))),
10 => Some(("Tag_FP_arch", if v == 0 { "none".into() } else { format!("FP v{v}") })),
14 => Some(("Tag_ABI_PCS_R9_use", pick(&["V6", "SB", "TLS", "unused"], v))),
15 => Some((
"Tag_ABI_PCS_RW_data",
pick(&["absolute", "PC-relative", "SB-relative", "none"], v),
)),
16 => Some(("Tag_ABI_PCS_RO_data", pick(&["absolute", "PC-relative", "none"], v))),
17 => Some(("Tag_ABI_PCS_GOT_use", pick(&["none", "direct", "GOT-indirect"], v))),
18 => Some(("Tag_ABI_PCS_wchar_t", v.to_string())),
24 => Some(("Tag_ABI_align_needed", v.to_string())),
25 => Some(("Tag_ABI_align_preserved", v.to_string())),
26 => Some(("Tag_ABI_enum_size", pick(&["unused", "small", "int", "forced-int"], v))),
27 => Some(("Tag_ABI_HardFP_use", v.to_string())),
28 => Some((
"Tag_ABI_VFP_args",
pick(&["soft", "hard", "toolchain", "compatible"], v),
)),
30 => Some((
"Tag_ABI_optimization_goals",
pick(
&[
"none",
"prefer speed",
"aggressive speed",
"prefer size",
"aggressive size",
"prefer debug",
"aggressive debug",
],
v,
),
)),
31 => Some(("Tag_ABI_FP_optimization_goals", v.to_string())),
34 => Some(("Tag_CPU_unaligned_access", pick(&["none", "allowed"], v))),
44 => Some(("Tag_DIV_use", pick(&["if in architecture", "none", "allowed"], v))),
46 => Some(("Tag_DSP_extension", pick(&["none", "allowed"], v))),
_ => None,
};
out.extend(e);
}
q = subend.max(q + 5);
}
p = end.max(p + 4);
}
out
}
fn declared_level(producer: &str) -> Option<OptLevel> {
let mut found = None;
for tok in producer.split_whitespace() {
let l = match tok {
"-O0" => OptLevel::O0,
"-O" | "-O1" => OptLevel::O1,
"-O2" => OptLevel::O2,
"-O3" | "-Ofast" => OptLevel::O3,
"-Os" => OptLevel::Os,
"-Oz" => OptLevel::Oz,
"-Og" => OptLevel::Og,
_ => continue,
};
found = Some(l);
}
found
}
fn goal_levels(family: Option<Compiler>, goal: &str) -> Option<Vec<OptLevel>> {
use OptLevel::*;
let gcc = family != Some(Compiler::Clang);
Some(match goal {
"aggressive debug" => vec![O0],
"prefer speed" if gcc => vec![O1, Og],
"prefer speed" => vec![O1, O2],
"aggressive speed" if gcc => vec![O2, O3],
"aggressive speed" => vec![O3],
"prefer size" => vec![Os],
"aggressive size" if gcc => vec![Os, Oz],
"aggressive size" => vec![Oz],
_ => return None,
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Compiler {
Gcc,
Clang,
}
impl fmt::Display for Compiler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Compiler::Gcc => "GCC",
Compiler::Clang => "clang",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Verdict {
Yes,
No,
Unknown,
}
impl Verdict {
pub fn label(self) -> &'static str {
match self {
Verdict::Yes => "yes",
Verdict::No => "no",
Verdict::Unknown => "unknown",
}
}
}
#[derive(Clone, Debug)]
pub struct Finding {
pub flag: &'static str,
pub verdict: Verdict,
pub confidence: f32,
pub evidence: Vec<String>,
pub declared: Option<(bool, String)>,
}
impl Finding {
fn new(flag: &'static str) -> Finding {
Finding {
flag,
verdict: Verdict::Unknown,
confidence: 0.0,
evidence: Vec::new(),
declared: None,
}
}
fn set(&mut self, yes: bool, confidence: f32, why: String) {
self.verdict = if yes { Verdict::Yes } else { Verdict::No };
self.confidence = confidence.clamp(0.0, 1.0);
self.evidence.push(why);
}
fn note(&mut self, why: impl Into<String>) {
self.evidence.push(why.into());
}
pub fn effective(&self) -> Option<bool> {
match self.verdict {
Verdict::Yes => Some(true),
Verdict::No => Some(false),
Verdict::Unknown => self.declared.as_ref().map(|d| d.0),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct FlagReport {
pub compiler: Option<String>,
pub declared: Option<String>,
pub candidates: Vec<(OptLevel, f32)>,
pub evidence: Vec<String>,
pub family: Option<Compiler>,
pub family_from_code: Option<(Compiler, f32)>,
pub family_evidence: Vec<String>,
pub version: Option<String>,
pub arch: Option<&'static str>,
pub arch_evidence: Vec<String>,
pub attributes: Vec<(&'static str, String)>,
pub declared_levels: Vec<OptLevel>,
pub findings: Vec<Finding>,
pub contradictions: Vec<String>,
pub undecidable: Vec<(&'static str, &'static str)>,
pub command_line: String,
}
impl FlagReport {
pub fn best(&self) -> Option<OptLevel> {
self.candidates.first().map(|c| c.0)
}
pub fn tied(&self) -> Vec<OptLevel> {
let Some(best) = self.candidates.first() else {
return Vec::new();
};
self.candidates
.iter()
.filter(|c| c.1 >= best.1 * 0.5)
.map(|c| c.0)
.collect()
}
pub fn level(&self) -> Option<OptLevel> {
let best = self.candidates.first()?;
self.candidates
.iter()
.find(|c| self.declared_levels.contains(&c.0) && c.1 >= best.1 * 0.25)
.or(Some(best))
.map(|c| c.0)
}
pub fn finding(&self, flag: &str) -> Option<&Finding> {
self.findings.iter().find(|f| f.flag == flag)
}
pub fn attribute(&self, tag: &str) -> Option<&str> {
self.attributes.iter().find(|a| a.0 == tag).map(|a| a.1.as_str())
}
pub fn render(&self, explain: bool) -> String {
use std::fmt::Write;
let mut o = String::new();
let fam = match (self.family, &self.family_from_code) {
(Some(f), _) => f.to_string(),
(None, _) => "unknown".into(),
};
match &self.compiler {
Some(c) => {
let mut ids: Vec<&str> = Vec::new();
for part in c.split("; ") {
if !ids.contains(&part) {
ids.push(part);
}
}
let _ = writeln!(o, "compiler: {}", ids.join("; "));
}
None => {
let how = match self.family_from_code {
Some((_, c)) => format!(" (from code style, {:.0}%)", c * 100.0),
None => String::new(),
};
let _ = writeln!(o, "compiler: {fam}{how}");
}
}
if let Some(d) = &self.declared {
let _ = writeln!(o, "declared flags: {d}");
}
if let Some(a) = self.arch {
let cpu = self
.attribute("Tag_CPU_name")
.map(|c| format!("; declared CPU {c}"))
.unwrap_or_default();
let _ = writeln!(o, "target: {a}{cpu}");
}
if !self.candidates.is_empty() {
let best = self.candidates[0].1;
let c: Vec<String> = self
.candidates
.iter()
.filter(|c| c.1 >= best - 0.15)
.map(|(l, s)| format!("{l} ({:.0}%)", s * 100.0))
.collect();
let decl = if self.declared_levels.is_empty() {
String::new()
} else {
let d: Vec<String> = self.declared_levels.iter().map(|l| l.to_string()).collect();
format!("; recorded goal: {}", d.join("/"))
};
let _ = writeln!(o, "optimisation: {}{decl}", c.join(", "));
}
let pick = |v: Verdict| -> Vec<String> {
self.findings
.iter()
.filter(|f| f.verdict == v)
.map(|f| format!("{} ({:.0}%)", f.flag, f.confidence * 100.0))
.collect()
};
let (on, off) = (pick(Verdict::Yes), pick(Verdict::No));
if !on.is_empty() {
let _ = writeln!(o, "flags in effect: {}", on.join(", "));
}
if !off.is_empty() {
let _ = writeln!(o, "flags not used: {}", off.join(", "));
}
let declared: Vec<String> = self
.findings
.iter()
.filter(|f| f.verdict == Verdict::Unknown)
.filter_map(|f| {
f.declared
.as_ref()
.map(|d| format!("{} {}", f.flag, if d.0 { "on" } else { "off" }))
})
.collect();
if !declared.is_empty() {
let _ = writeln!(o, "declared only: {}", declared.join(", "));
}
if !self.command_line.is_empty() {
let _ = writeln!(o, "likely built as: {}", self.command_line);
}
for c in &self.contradictions {
let _ = writeln!(o, "CONTRADICTION: {c}");
}
if explain {
for e in &self.family_evidence {
let _ = writeln!(o, " compiler: {e}");
}
for e in &self.arch_evidence {
let _ = writeln!(o, " target: {e}");
}
for e in &self.evidence {
let _ = writeln!(o, " optimisation: {e}");
}
for f in &self.findings {
let conf = match f.verdict {
Verdict::Unknown => String::new(),
_ => format!(" ({:.0}%)", f.confidence * 100.0),
};
let _ = writeln!(o, " {}: {}{conf}", f.flag, f.verdict.label());
for e in &f.evidence {
let _ = writeln!(o, " {e}");
}
if let Some((_, d)) = &f.declared {
let _ = writeln!(o, " declared: {d}");
}
}
for (name, value) in &self.attributes {
let _ = writeln!(o, " attribute {name}: {value}");
}
for (flag, why) in &self.undecidable {
let _ = writeln!(o, " cannot tell {flag}: {why}");
}
}
o
}
pub fn json(&self) -> String {
fn q(s: &str) -> String {
let mut o = String::from("\"");
for c in s.chars() {
match c {
'"' => o.push_str("\\\""),
'\\' => o.push_str("\\\\"),
'\n' => o.push_str("\\n"),
c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
c => o.push(c),
}
}
o.push('"');
o
}
let opt = |s: &Option<String>| s.as_deref().map_or("null".to_string(), q);
let list = |v: &[String]| format!("[{}]", v.iter().map(|s| q(s)).collect::<Vec<_>>().join(","));
let mut parts = Vec::new();
parts.push(format!("\"compiler\":{}", opt(&self.compiler)));
parts.push(format!(
"\"compiler_family\":{}",
self.family.map_or("null".to_string(), |f| q(&f.to_string()))
));
parts.push(format!("\"compiler_evidence\":{}", list(&self.family_evidence)));
parts.push(format!("\"declared\":{}", opt(&self.declared)));
parts.push(format!("\"architecture\":{}", self.arch.map_or("null".to_string(), q)));
let cands: Vec<String> = self
.candidates
.iter()
.map(|(l, c)| format!("{{\"level\":{},\"confidence\":{c:.3}}}", q(&l.to_string())))
.collect();
parts.push(format!("\"optimisation\":[{}]", cands.join(",")));
let dl: Vec<String> = self.declared_levels.iter().map(|l| l.to_string()).collect();
parts.push(format!("\"optimisation_recorded_goal\":{}", list(&dl)));
parts.push(format!("\"optimisation_evidence\":{}", list(&self.evidence)));
let flags: Vec<String> = self
.findings
.iter()
.map(|f| {
format!(
"{{\"flag\":{},\"verdict\":{},\"confidence\":{:.2},\"evidence\":{},\"declared\":{}}}",
q(f.flag),
q(f.verdict.label()),
f.confidence,
list(&f.evidence),
f.declared.as_ref().map_or("null".to_string(), |(v, why)| format!(
"{{\"value\":{v},\"source\":{}}}",
q(why)
))
)
})
.collect();
parts.push(format!("\"flags\":[{}]", flags.join(",")));
let attrs: Vec<String> = self
.attributes
.iter()
.map(|(k, v)| format!("{}:{}", q(k), q(v)))
.collect();
parts.push(format!("\"attributes\":{{{}}}", attrs.join(",")));
parts.push(format!("\"contradictions\":{}", list(&self.contradictions)));
let und: Vec<String> = self
.undecidable
.iter()
.map(|(f, w)| format!("{}:{}", q(f), q(w)))
.collect();
parts.push(format!("\"undecidable\":{{{}}}", und.join(",")));
parts.push(format!("\"command_line\":{}", q(&self.command_line)));
format!("{{{}}}", parts.join(","))
}
}
const O0: usize = 0;
const O1: usize = 1;
const O2: usize = 2;
const O3: usize = 3;
const OS: usize = 4;
const OZ: usize = 5;
const OG: usize = 6;
fn looks_unoptimised(f: &Features) -> bool {
let spill = f.arg_spills as f32 / f.funcs.max(1) as f32;
let frame = f.frame_accesses as f32 / f.insns.max(1) as f32;
spill >= 0.45 || frame >= 0.2
}
fn is_thumb2(f: &Features) -> bool {
f.wide_mainline > 0 || f.it_blocks > 0
}
fn identify_compiler(f: &Features, image: &Image, r: &mut FlagReport) {
let mut texts: Vec<&str> = image.meta.producers.iter().map(String::as_str).collect();
texts.extend(image.comment.as_deref());
texts.extend(image.producer.as_deref());
let says_clang = texts.iter().any(|t| t.contains("clang"));
let says_gcc = texts
.iter()
.any(|t| t.contains("GCC:") || t.contains("GNU C") || t.contains("GNU GIMPLE"));
for t in &texts {
let v = if let Some(p) = t.find("clang version ") {
t[p + 14..].split_whitespace().next()
} else if t.contains("GCC:") || t.contains("GNU C") {
let rest = t.rfind(')').map_or(*t, |p| &t[p + 1..]);
rest.split_whitespace().find(|w| {
w.split('.').count() >= 2
&& w.split('.')
.all(|x| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit()))
})
} else {
None
};
if r.version.is_none() {
r.version = v.map(str::to_string);
}
}
let (mut c, mut g) = (0.0f32, 0.0f32);
let pads = f.push_r7_lr_pad + f.push_r3_pad + f.push_r4_pad;
if pads > 0 {
let framed = f.fp_nonleaf * 2 >= f.nonleaf_funcs.max(1);
let w = pads.min(6) as f32 * if framed { 0.3 } else { 1.0 };
c += w * f.push_r7_lr_pad as f32 / pads as f32;
g += w * (f.push_r3_pad + f.push_r4_pad) as f32 / pads as f32;
r.family_evidence.push(format!(
"stack-alignment pushes: {} of {{r7, lr}} with r7 unused (clang), {} including r3 or an unused r4 (GCC)",
f.push_r7_lr_pad,
f.push_r3_pad + f.push_r4_pad
));
}
if f.outlined > 0 {
c += 3.0 * f.outlined.min(2) as f32;
r.family_evidence.push(format!(
"{} OUTLINED_FUNCTION_n symbols (LLVM machine outliner)",
f.outlined
));
}
if f.clones > 0 {
g += 2.0 * f.clones.min(3) as f32;
r.family_evidence.push(format!(
"{} .constprop/.isra/.part function clones (GCC naming)",
f.clones
));
}
let case_helpers = thumb1_case_helpers(image);
if case_helpers > 0 {
g += 3.0;
r.family_evidence
.push("uses __gnu_thumb1_case_* switch helpers (GCC, Thumb-1)".into());
}
if is_thumb2(f) && f.movw_movt >= 4 && f.movw_movt >= 2 * f.literal_loads {
c += 2.0;
r.family_evidence.push(format!(
"addresses are built with movw/movt ({} pairs against {} literal-pool loads): clang's default on ARMv7-M",
f.movw_movt, f.literal_loads
));
} else if is_thumb2(f) && f.movw_movt == 0 && f.literal_loads >= 8 {
g += 1.0;
r.family_evidence.push(format!(
"addresses come from literal pools ({} loads, no movw/movt): GCC's default (clang does this at -Oz)",
f.literal_loads
));
}
if is_thumb2(f) && f.fp_add >= 3 && f.fp_mov == 0 {
g += 3.0;
r.family_evidence.push(format!(
"{} frame pointers set up with `add r7, sp, #n` (GCC)",
f.fp_add
));
} else if f.fp_mov >= 3 && f.fp_add == 0 {
c += 1.0;
r.family_evidence
.push(format!("{} frame pointers set up with `mov r7, sp`", f.fp_mov));
}
let total = c + g;
if total >= 1.5 && (c - g).abs() >= 1.0 {
let fam = if c > g { Compiler::Clang } else { Compiler::Gcc };
r.family_from_code = Some((fam, c.max(g) / (total + 1.0)));
}
r.family = match (says_clang, says_gcc) {
(true, false) => Some(Compiler::Clang),
(false, true) => Some(Compiler::Gcc),
(true, true) => {
r.family_evidence
.push("the file carries both GCC and clang identification strings (objects from both)".into());
r.family_from_code.map(|x| x.0)
}
(false, false) => {
if image.meta.present {
r.family_evidence
.push("no compiler identification recorded in the file".into());
}
r.family_from_code.map(|x| x.0)
}
};
if let (true, false) | (false, true) = (says_clang, says_gcc)
&& let Some((code, conf)) = r.family_from_code
&& Some(code) != r.family
&& conf >= 0.75
{
r.contradictions.push(format!(
"the file identifies its compiler as {}, but the code is in the style of {code}",
r.family.unwrap()
));
}
}
fn thumb1_case_helpers(image: &Image) -> u32 {
let n = |s: &str| s.starts_with("__gnu_thumb1_case_");
(image.externals.values().filter(|s| n(s)).count() + image.symbols.iter().filter(|s| n(&s.name)).count()) as u32
}
fn identify_target(f: &Features, r: &mut FlagReport) {
if f.insns == 0 {
return;
}
let ev = &mut r.arch_evidence;
let arch = if is_thumb2(f) {
ev.push(format!(
"{} Thumb-2 instructions that only ARMv7-M and ARMv8-M Mainline have ({} IT blocks)",
f.wide_mainline, f.it_blocks
));
ev.push(
"ARMv7-M and ARMv8-M Mainline cannot be told apart unless security or v8-only instructions appear".into(),
);
match (f.dsp_insns > 0, f.fp_insns > 0) {
(false, false) => "ARMv7-M or ARMv8-M Mainline",
(true, false) => "ARMv7E-M or ARMv8-M Mainline with DSP",
(false, true) => "ARMv7-M or ARMv8-M Mainline with FPU",
(true, true) => "ARMv7E-M or ARMv8-M Mainline with DSP and FPU",
}
} else if f.wide_baseline > 0 || f.cbz > 0 || f.hw_divides > 0 {
ev.push(format!(
"no IT blocks or other Thumb-2 instructions, but {} wide branches/movw/movt, {} cbz, {} hardware divides",
f.wide_baseline, f.cbz, f.hw_divides
));
"ARMv8-M Baseline"
} else {
ev.push(format!(
"all {} instructions are 16-bit Thumb-1 (plus bl): ARMv6-M code, or code for a larger core that happens to need nothing more",
f.insns
));
"ARMv6-M"
};
if f.dsp_insns > 0 {
ev.push(format!("{} DSP-extension multiplies", f.dsp_insns));
}
if f.fp_insns > 0 {
ev.push(format!("{} coprocessor (floating-point) instructions", f.fp_insns));
}
if f.hw_divides > 0 {
ev.push(format!("{} udiv/sdiv instructions", f.hw_divides));
}
r.arch = Some(arch);
if let Some(decl) = r.attribute("Tag_CPU_arch").map(str::to_string) {
let thumb1_only = decl.starts_with("v6") && decl.ends_with("-M");
if thumb1_only && arch != "ARMv6-M" {
r.contradictions.push(format!(
"build attributes declare {decl} (Thumb-1 only), but the code uses instructions that need {arch}"
));
}
if decl == "v8-M.baseline" && is_thumb2(f) {
r.contradictions.push(format!(
"build attributes declare {decl}, but the code uses Thumb-2 instructions that need a Mainline core"
));
}
}
}
fn softmax(s: &[f32; 7], levels: &[usize]) -> Vec<(OptLevel, f32)> {
let max = levels.iter().map(|&l| s[l]).fold(f32::MIN, f32::max);
let exp: Vec<f32> = levels.iter().map(|&l| (s[l] - max).exp()).collect();
let total: f32 = exp.iter().sum();
let mut c: Vec<(OptLevel, f32)> = levels
.iter()
.zip(&exp)
.map(|(&l, &e)| (OptLevel::ALL[l], e / total))
.collect();
c.sort_by(|a, b| b.1.total_cmp(&a.1));
c
}
fn guess_level(f: &Features, thumb1_helpers: u32, r: &mut FlagReport) {
let clang = r.family == Some(Compiler::Clang);
let thumb2 = is_thumb2(f);
let mut s = [0.0f32; 7];
let ev = &mut r.evidence;
if r.family.is_none() {
ev.push("compiler not identified: using the rules for GCC".into());
}
let frame = f.frame_accesses as f32 / f.insns as f32;
let what = format!(
"{} of {} functions store their arguments to the stack on entry and {:.0}% of instructions access the frame",
f.arg_spills,
f.funcs,
frame * 100.0
);
if looks_unoptimised(f) {
s[O0] += 10.0;
ev.push(format!("{what}: unoptimised code"));
} else {
s[O0] -= 10.0;
ev.push(format!("{what}: optimised code"));
}
let loops = f.loops_top_tested + f.loops_entry_jump + f.loops_rotated;
let (top, entry, rot) = if loops > 0 {
(
f.loops_top_tested as f32 / loops as f32,
f.loops_entry_jump as f32 / loops as f32,
f.loops_rotated as f32 / loops as f32,
)
} else {
(0.0, 0.0, 0.0)
};
let nb = f.branch_adjacent + f.branch_separated;
let na = f.starts_padded + f.starts_unpadded;
let padded = if na > 0 {
f.starts_padded as f32 / na as f32
} else {
0.0
};
let wa = na.min(3) as f32 / 3.0;
let dup = if f.windows > 0 {
f.repeated_windows as f32 / f.windows as f32
} else {
0.0
};
let wl = loops.min(8) as f32 / 8.0;
if clang {
if loops > 0 {
ev.push(format!(
"{loops} loops: {} tested at the top (-Oz does not rotate loops), {} entered by a jump to the test, {} rotated",
f.loops_top_tested, f.loops_entry_jump, f.loops_rotated
));
s[OZ] += wl * (3.5 * top - 2.5 * (rot + entry));
for l in [O1, O2, O3, OS] {
s[l] += wl * (1.5 * (rot + entry) - 3.0 * top);
}
s[O1] += wl * 0.8 * entry.min(0.3) / 0.3;
} else {
ev.push("no loops: loop-shape evidence unavailable".into());
}
if f.outlined > 0 {
ev.push(format!(
"{} outlined functions: the machine outliner runs at -Oz",
f.outlined
));
s[OZ] += 4.0;
}
if f.push_r3_pad > 0 {
ev.push(format!(
"{} prologues push extra low registers to make room on the stack instead of adjusting sp (-Oz)",
f.push_r3_pad
));
s[OZ] += 2.5;
} else if f.nonleaf_funcs >= 12 {
s[OZ] -= 0.7;
}
if thumb2 && f.movw_movt == 0 && f.literal_loads >= 3 {
ev.push(format!(
"addresses and constants come from literal pools ({} loads) rather than movw/movt pairs (-Oz)",
f.literal_loads
));
s[OZ] += 2.5;
} else if thumb2 && f.movw_movt >= 2 {
ev.push(format!("{} movw/movt pairs (every level except -Oz)", f.movw_movt));
s[OZ] -= 2.0;
}
if f.div_by_immediate + f.long_multiplies > 0 {
ev.push(format!(
"{} divisions by an immediate kept as udiv/sdiv (-Oz), {} long multiplies (reciprocal division elsewhere)",
f.div_by_immediate, f.long_multiplies
));
if f.div_by_immediate > 0 {
s[OZ] += 2.5;
for l in [O1, O2, O3, OS] {
s[l] -= 2.0;
}
} else {
s[OZ] -= 1.5;
}
}
if thumb2 && na > 0 {
ev.push(format!(
"{} of {na} function starts that needed padding for 4-byte alignment received it (clang aligns functions to 4 bytes except at -Os/-Oz)",
f.starts_padded
));
if padded >= 0.75 {
for l in [O1, O2, O3] {
s[l] += 1.5 * wa;
}
s[OS] -= 2.0 * wa;
s[OZ] -= 2.0 * wa;
} else if padded <= 0.25 {
for l in [O1, O2, O3] {
s[l] -= 2.0 * wa;
}
s[OS] += 1.5 * wa;
s[OZ] += 1.5 * wa;
}
}
if f.windows >= 150 && loops >= 2 {
ev.push(format!(
"{:.0}% of instruction windows repeat within their function (loop unrolling duplicates code at -O2/-O3)",
dup * 100.0
));
if dup >= 0.06 {
s[O2] += 2.0;
s[O3] += 2.0;
for l in [O1, OS, OZ] {
s[l] -= 1.5;
}
if dup >= 0.115 {
s[O3] += 0.5;
} else {
s[O2] += 0.3;
}
} else if dup <= 0.035 {
s[O2] -= 1.5;
s[O3] -= 1.5;
}
} else if !looks_unoptimised(f) {
ev.push("too little looping code to tell -O1/-Os from -O2/-O3".into());
}
if !thumb2 {
ev.push("on Thumb-1, clang's -O1 and -Os output differ very little: expect a tie".into());
}
r.candidates = softmax(&s, &[O0, O1, O2, O3, OS, OZ]);
return;
}
if loops > 0 {
ev.push(format!(
"{loops} loops: {} test at the top (-Os), {} jump to a bottom test (-Og/-O0), {} guarded bottom-tested (-O1 and up)",
f.loops_top_tested, f.loops_entry_jump, f.loops_rotated
));
s[OS] += wl * (3.0 * top - 0.8 * rot - 2.0 * entry);
if loops >= 4 && f.loops_entry_jump == 0 && top >= 0.2 {
s[OS] += 1.5;
}
if entry >= 0.15 {
s[OS] -= 1.5 * wl;
}
s[OG] += wl * (3.0 * entry + if entry > 0.0 { 1.5 * top } else { -0.5 * top } - 2.5 * rot);
s[O1] += wl * (1.2 * rot - 2.5 * top - 0.8 * entry);
for l in [O2, O3] {
s[l] += wl * (1.2 * rot - 2.5 * (top + entry));
}
} else {
ev.push("no loops: loop-shape evidence unavailable".into());
}
if f.div_by_immediate + f.long_multiplies > 0 {
ev.push(format!(
"{} divisions by an immediate kept as udiv/sdiv (-Os), {} long multiplies (reciprocal division at speed levels)",
f.div_by_immediate, f.long_multiplies
));
if f.div_by_immediate > 0 && f.long_multiplies <= f.div_by_immediate {
s[OS] += 2.5;
for l in [O1, O2, O3, OG] {
s[l] -= 2.0;
}
} else if f.div_by_immediate == 0 {
s[OS] -= 1.5;
}
}
if nb >= 4 {
let sep = ratio(f.branch_separated, f.branch_adjacent);
ev.push(format!(
"{} of {nb} conditional branches are separated from their compare (instruction scheduling: -O2/-O3/-Os)",
f.branch_separated
));
if sep >= 0.25 {
s[O2] += 1.5;
s[O3] += 1.5;
s[OS] += 0.5;
s[O1] -= 1.5;
s[OG] -= 1.5;
} else if sep <= 0.10 && nb >= 8 && thumb2 {
s[O1] += 1.0;
s[OG] += 1.0;
s[O2] -= 1.0;
s[O3] -= 1.0;
}
}
if na > 0 {
ev.push(format!(
"{} of {na} function starts that needed padding for 4-byte alignment received it (-O2/-O3 align functions)",
f.starts_padded
));
if padded >= 0.75 {
s[O2] += 1.5 * wa;
s[O3] += 1.5 * wa;
for l in [O1, OS, OG] {
s[l] -= 1.5 * wa;
}
} else if padded <= 0.34 {
s[O2] -= 2.0 * wa;
s[O3] -= 2.0 * wa;
for l in [O1, OS, OG] {
s[l] += 0.5 * wa;
}
}
}
if thumb2 {
if f.it_blocks == 0 && nb >= 6 {
ev.push("no IT blocks despite conditional code: little if-conversion (-Og/-O0)".into());
s[OG] += 0.5;
} else if f.it_blocks > 0 {
ev.push(format!("{} IT blocks (if-conversion: -O1 and up, -Os)", f.it_blocks));
s[OG] -= 0.5;
}
if f.tail_calls > 0 {
ev.push(format!(
"{} tail calls (sibling-call optimisation: -O2, -O3, -Os)",
f.tail_calls
));
s[O1] -= 1.5;
s[OG] -= 1.5;
}
}
if !thumb2 && f.push_r3_pad > 0 {
ev.push(format!(
"{} prologues push extra low registers to make room on the stack instead of adjusting sp (a size optimisation)",
f.push_r3_pad
));
s[OS] += 1.5;
}
if thumb1_helpers > 0 {
ev.push(
"switches dispatch through __gnu_thumb1_case_* helpers, which GCC only uses when optimising for size"
.into(),
);
s[OS] += 2.5;
for l in [O1, O2, O3, OG] {
s[l] -= 1.0;
}
}
let mut o3 = 0.0;
if f.clones > 0 {
ev.push(format!(
"{} function clone symbols (.constprop/.isra/.part): interprocedural cloning",
f.clones
));
o3 += 0.6;
}
if f.windows >= 40 {
ev.push(format!(
"{:.0}% of instruction windows repeat within their function (unrolling, peeling and loop versioning duplicate code at -O3)",
dup * 100.0
));
if dup >= 0.045 {
o3 += 0.65;
} else if dup <= 0.025 && loops >= 2 {
o3 -= 1.0;
}
}
if f.loops_rotated > 0 && f.loops_with_remainder > 0 {
ev.push(format!(
"{} of {} bottom-tested loops are followed by remainder handling{}",
f.loops_with_remainder,
f.loops_rotated,
if f.dual_accesses > 0 {
format!("; {} paired memory accesses", f.dual_accesses)
} else {
String::new()
}
));
if f.loops_with_remainder * 4 >= f.loops_rotated {
o3 += 0.6;
}
}
s[O3] += o3;
if o3 == 0.0 {
ev.push("nothing distinguishes -O2 from -O3 in this code".into());
}
if !thumb2 && f.loops_entry_jump == 0 && s[O1] > s[OS] {
ev.push("on Thumb-1, GCC's -O1 and -Os output differ very little: reported as a tie".into());
s[OS] = s[O1] - 0.2;
}
s[OZ] = s[OS] - 0.1;
ev.push("GCC's -Oz output is (nearly) identical to -Os: the two are reported together".into());
r.candidates = softmax(&s, &[O0, O1, O2, O3, OS, OZ, OG]);
}
fn negation(flag: &str) -> Option<String> {
let (p, rest) = flag.split_at(2);
if p != "-f" && p != "-m" {
return None;
}
Some(match rest.strip_prefix("no-") {
Some(x) => format!("{p}{x}"),
None => format!("{p}no-{rest}"),
})
}
fn flag_findings(f: &Features, image: &Image, r: &mut FlagReport) {
let meta = &image.meta;
let unopt = looks_unoptimised(f);
let thumb2 = is_thumb2(f);
let tokens: Vec<String> = r
.declared
.as_deref()
.unwrap_or("")
.split_whitespace()
.filter(|t| t.starts_with('-'))
.map(str::to_string)
.collect();
let merges_loads = !unopt
&& r.candidates
.first()
.is_some_and(|c| !matches!(c.0, OptLevel::O0 | OptLevel::O1 | OptLevel::Og) && c.1 >= 0.5);
let mut out: Vec<Finding> = Vec::new();
let sec = |pred: &dyn Fn(&str) -> bool| meta.sections.iter().filter(|s| s.3 > 0 && pred(&s.0)).count();
let reloc = |pred: &dyn Fn(&crate::image::RelocInfo) -> bool| meta.relocs.iter().filter(|x| pred(x)).count();
let mut x = Finding::new("-fomit-frame-pointer");
let fp = f.fp_leaf + f.fp_nonleaf;
if f.nonleaf_funcs >= 2 && f.fp_nonleaf * 10 >= f.nonleaf_funcs * 8 {
x.set(
false,
0.9,
format!(
"{} of {} non-leaf functions set up a frame pointer in r7",
f.fp_nonleaf, f.nonleaf_funcs
),
);
} else if fp == 0 && f.nonleaf_funcs >= 3 {
x.set(
true,
(0.6 + 0.02 * f.nonleaf_funcs as f32).min(0.9),
format!("none of {} functions sets up a frame pointer", f.funcs),
);
x.note("frame pointers are omitted by default by GCC at -O1 and above, and by clang for bare-metal ARM: the flag itself may not have been given");
} else {
x.note(format!(
"{fp} of {} functions set up a frame pointer: too few to tell",
f.funcs
));
}
out.push(x);
let mut x = Finding::new("-momit-leaf-frame-pointer");
if f.fp_nonleaf >= 2 {
if f.fp_leaf == 0 && f.leaf_funcs >= 2 {
x.set(
true,
0.8,
format!(
"{} non-leaf functions keep a frame pointer, none of {} leaf functions does",
f.fp_nonleaf, f.leaf_funcs
),
);
} else if f.fp_leaf >= 2 {
x.set(
false,
0.8,
format!("{} leaf functions set up a frame pointer", f.fp_leaf),
);
}
} else {
x.note("no frame pointers are kept, so there is nothing to omit in leaf functions");
}
out.push(x);
let mut x = Finding::new("-fropi");
let rel_ro = reloc(&|q| {
q.in_code
&& matches!(q.rtype, 3 | 49 | 50)
&& matches!(
q.target,
crate::image::RelocTarget::ReadOnlyData | crate::image::RelocTarget::Code
)
});
let abs_ro = reloc(&|q| {
q.in_code
&& matches!(q.rtype, 2 | 47 | 48)
&& matches!(
q.target,
crate::image::RelocTarget::ReadOnlyData | crate::image::RelocTarget::Code
)
});
if meta.relocatable && rel_ro + abs_ro >= 1 {
x.note(format!(
"code relocations against read-only data and functions: {rel_ro} PC-relative, {abs_ro} absolute"
));
if rel_ro >= 1 && abs_ro == 0 {
x.set(
true,
if rel_ro >= 3 { 0.95 } else { 0.8 },
"all such references are PC-relative".into(),
);
} else if abs_ro >= 1 && rel_ro == 0 {
x.set(
false,
if abs_ro >= 3 { 0.95 } else { 0.8 },
"all such references are absolute".into(),
);
}
} else if f.add_pc >= 2 && f.abs_ro_refs * 4 <= f.add_pc {
x.set(
true,
if f.add_pc >= 4 { 0.85 } else { 0.6 },
format!(
"{} addresses are formed relative to pc (`add rX, pc`) against {} literals that look like absolute addresses of read-only memory",
f.add_pc, f.abs_ro_refs
),
);
} else if f.abs_ro_refs >= 2 && f.add_pc * 4 <= f.abs_ro_refs {
x.set(
false,
if f.abs_ro_refs >= 4 { 0.85 } else { 0.65 },
format!(
"{} absolute addresses of read-only memory are formed in code ({} PC-relative)",
f.abs_ro_refs, f.add_pc
),
);
} else {
x.note("the code takes no (or too few) addresses of constants or functions");
}
out.push(x);
let mut x = Finding::new("-frwpi");
let sb = reloc(&|q| matches!(q.rtype, 9 | 87..=89));
let abs_rw =
reloc(&|q| q.in_code && matches!(q.rtype, 2 | 47 | 48) && q.target == crate::image::RelocTarget::WritableData);
if sb > 0 {
x.set(true, 0.99, format!("{sb} static-base-relative relocations"));
} else if f.r9_reads >= 2 && f.r9_writes == 0 {
x.set(
true,
0.8,
format!(
"r9 is read {} times and never written: it holds the static base",
f.r9_reads
),
);
} else if (abs_rw >= 2 || f.abs_rw_refs >= 2) && (f.r9_reads == 0 || f.r9_writes > 0) {
x.set(
false,
0.9,
format!(
"writable data is addressed absolutely ({} references) and r9 is {}",
abs_rw.max(f.abs_rw_refs as usize),
if f.r9_writes > 0 {
"used as a scratch register"
} else {
"never used as a base"
}
),
);
} else {
x.note("the code does not address writable data (or the image does not contain its data segments)");
}
out.push(x);
let mut x = Finding::new("-fno-jump-tables");
let helpers = thumb1_case_helpers(image);
let tables = f.table_branches + f.computed_jumps + helpers;
if tables > 0 {
x.set(
false,
0.95,
format!(
"{} table branches, {} computed jumps, {} switch helper routines: jump tables are in use",
f.table_branches, f.computed_jumps, helpers
),
);
} else if f.dense_compare_chains > 0 {
let why = format!(
"{} functions compare one register against five or more closely spaced constants (longest: {}) and no jump table exists anywhere",
f.dense_compare_chains, f.longest_compare_chain
);
if unopt && r.family != Some(Compiler::Clang) {
x.note(why);
x.note("unoptimised GCC code often lowers such switches to compare chains anyway: not conclusive");
} else {
x.set(true, (0.55 + 0.1 * f.dense_compare_chains as f32).min(0.8), why);
}
} else {
x.note("no switch large and dense enough for a jump table to be worthwhile");
}
out.push(x);
let mut x = Finding::new("-mno-unaligned-access");
if !thumb2 && f.hw_divides == 0 && f.wide_baseline == 0 {
x.note("ARMv6-M has no unaligned access at all: the flag changes nothing on this target");
} else if f.assembled_words >= 2 && merges_loads {
x.set(
true,
(0.55 + 0.05 * f.assembled_words as f32).min(0.7),
format!(
"{} words are assembled from single bytes in optimised code, where one unaligned load would do",
f.assembled_words
),
);
} else if f.odd_word_access > 0 {
x.note(format!(
"{} word or halfword accesses at odd offsets, which occur with and without the flag: not conclusive",
f.odd_word_access
));
} else {
x.note("the code contains no access that would have to be unaligned");
}
out.push(x);
let mut x = Finding::new("-fshort-enums");
x.note("the size of enumeration types is not visible in machine code without knowing the source");
out.push(x);
let mut x = Finding::new("-ffunction-sections");
let generic = |n: &str| {
[
".text.unlikely",
".text.startup",
".text.hot",
".text.exit",
".text.cold",
]
.iter()
.any(|p| n.starts_with(p))
};
let per_fn = sec(&|n| n.starts_with(".text.") && !generic(n));
if meta.relocatable {
if per_fn > 0 {
x.set(true, 0.95, format!("{per_fn} sections named .text.<function>"));
} else if f.funcs >= 2 {
x.set(false, 0.9, format!("{} functions share one .text section", f.funcs));
}
} else {
x.note("section names do not survive linking");
}
out.push(x);
let mut x = Finding::new("-fdata-sections");
let merged = |n: &str| n.starts_with(".rodata.str") || n.starts_with(".rodata.cst") || n.starts_with(".data.rel");
let per_obj =
sec(&|n| (n.starts_with(".data.") || n.starts_with(".bss.") || n.starts_with(".rodata.")) && !merged(n));
let shared = sec(&|n| n == ".data" || n == ".bss" || n == ".rodata");
if meta.relocatable {
if per_obj > 0 {
x.set(
true,
0.95,
format!("{per_obj} sections named .data.<object>, .bss.<object> or .rodata.<object>"),
);
} else if shared > 0 && image.symbols.iter().filter(|s| s.kind == SymKind::Object).count() >= 2 {
x.set(false, 0.85, "several objects share .data/.bss/.rodata".into());
}
} else {
x.note("section names do not survive linking");
}
out.push(x);
let mut x = Finding::new("-fstack-protector");
let has = |n: &str| {
meta.undefined.iter().any(|s| s == n)
|| image.symbols.iter().any(|s| s.name == n)
|| image.externals.values().any(|s| s == n)
};
if has("__stack_chk_fail") || has("__stack_chk_guard") {
x.set(true, 0.95, "references __stack_chk_fail / __stack_chk_guard".into());
} else if f.funcs >= 5 {
x.set(
false,
0.6,
"no reference to __stack_chk_fail or __stack_chk_guard".into(),
);
x.note(
"plain -fstack-protector only instruments functions with character arrays, so it can be on without a trace",
);
}
out.push(x);
let mut x = Finding::new("-g");
if sec(&|n| n == ".debug_info") > 0 {
x.set(true, 1.0, "the file contains DWARF debug information".into());
} else if meta.present {
x.set(
false,
0.7,
"no debug sections (they may also have been stripped)".into(),
);
}
out.push(x);
let mut x = Finding::new("-fpic");
let got = reloc(&|q| matches!(q.rtype, 24..=26 | 95..=97));
if got > 0 {
x.set(true, 0.95, format!("{got} GOT-relative relocations"));
} else if sec(&|n| n == ".got") > 0 {
x.set(true, 0.7, "the image has a global offset table".into());
} else if meta.relocatable && reloc(&|q| q.in_code && q.target != crate::image::RelocTarget::Code) >= 2 {
x.set(false, 0.85, "data is referenced without a global offset table".into());
}
out.push(x);
let mut x = Finding::new("-mlong-calls");
if f.literal_calls >= 2 && f.direct_extern_calls == 0 && (meta.relocatable || f.literal_calls >= f.direct_calls) {
x.set(
true,
0.75,
format!(
"{} calls go through an address loaded from the literal pool and none is a direct bl to another object",
f.literal_calls
),
);
} else if f.direct_extern_calls >= 2 {
x.set(
false,
0.9,
format!(
"{} direct bl calls to functions defined elsewhere",
f.direct_extern_calls
),
);
}
out.push(x);
let mut x = Finding::new("-mfloat-abi=soft");
if f.fp_insns > 0 {
x.set(false, 0.9, format!("{} floating-point instructions", f.fp_insns));
} else if f.soft_float_calls > 0 {
x.set(
true,
0.85,
format!("{} calls to software floating-point routines", f.soft_float_calls),
);
} else {
x.note("the code performs no floating-point arithmetic");
}
out.push(x);
let mut x = Finding::new("-flto");
let lto = sec(&|n| n.starts_with(".gnu.lto_") || n == ".llvmbc" || n == ".llvm.lto");
if lto > 0 {
x.set(true, 0.95, format!("{lto} LTO sections"));
} else if meta.relocatable {
x.set(false, 0.9, "a relocatable object without LTO sections".into());
} else {
x.note("link-time optimisation leaves no reliable trace in a linked image");
}
out.push(x);
let mut x = Finding::new("-fno-inline");
if !unopt && f.local_tiny_single_caller >= 3 {
x.set(
true,
0.5,
format!(
"{} tiny static functions with a single caller were not inlined in optimised code",
f.local_tiny_single_caller
),
);
x.note("`noinline` attributes in the source have the same effect");
}
out.push(x);
let attr = |tag: &str| r.attribute(tag).map(str::to_string);
let has_attrs = !r.attributes.is_empty();
for x in &mut out {
let from_attr: Option<(bool, String)> = match x.flag {
"-fropi" => attr("Tag_ABI_PCS_RO_data")
.map(|v| (v == "PC-relative", format!("Tag_ABI_PCS_RO_data: {v}")))
.or_else(|| has_attrs.then(|| (false, "no Tag_ABI_PCS_RO_data: absolute addressing".to_string()))),
"-frwpi" => attr("Tag_ABI_PCS_R9_use")
.map(|v| (v == "SB", format!("Tag_ABI_PCS_R9_use: {v}")))
.or_else(|| {
attr("Tag_ABI_PCS_RW_data").map(|v| (v == "SB-relative", format!("Tag_ABI_PCS_RW_data: {v}")))
})
.or_else(|| {
has_attrs.then(|| (false, "no Tag_ABI_PCS_R9_use: r9 is an ordinary register".to_string()))
}),
"-mno-unaligned-access" => {
attr("Tag_CPU_unaligned_access").map(|v| (v == "none", format!("Tag_CPU_unaligned_access: {v}")))
}
"-fshort-enums" => attr("Tag_ABI_enum_size").map(|v| (v == "small", format!("Tag_ABI_enum_size: {v}"))),
"-mfloat-abi=soft" => attr("Tag_ABI_VFP_args").map(|v| (v == "soft", format!("Tag_ABI_VFP_args: {v}"))),
"-fpic" => attr("Tag_ABI_PCS_GOT_use")
.filter(|v| v == "GOT-indirect")
.map(|v| (true, format!("Tag_ABI_PCS_GOT_use: {v}"))),
_ => None,
};
let neg = negation(x.flag);
let from_cmd = tokens.iter().rev().find_map(|t| {
let t = t.split('=').next().unwrap_or(t);
let base = x.flag.split('=').next().unwrap_or(x.flag);
if x.flag.contains('=') {
tokens
.iter()
.any(|t| t == x.flag)
.then(|| (true, format!("recorded command line: {}", x.flag)))
} else if t == base {
Some((true, format!("recorded command line: {t}")))
} else if Some(t) == neg.as_deref() {
Some((false, format!("recorded command line: {t}")))
} else {
None
}
});
x.declared = from_cmd.or(from_attr);
}
for x in &out {
if let Some((d, src)) = &x.declared
&& x.verdict != Verdict::Unknown
&& x.confidence >= 0.75
&& *d != (x.verdict == Verdict::Yes)
&& x.flag != "-fomit-frame-pointer"
&& x.flag != "-g"
{
r.contradictions.push(format!(
"{} is declared {} ({src}), but the code says {}: {}",
x.flag,
if *d { "on" } else { "off" },
x.verdict.label(),
x.evidence.last().cloned().unwrap_or_default()
));
}
}
r.findings = out;
r.undecidable = vec![
(
"-fshort-enums",
"enumeration sizes are only visible through build attributes or the source",
),
(
"-ffast-math",
"only affects floating-point code generation; nothing to observe without it, and little with it",
),
(
"-fno-builtin / -ffreestanding",
"calls to memcpy/memset may come from the source or from the compiler; their absence proves nothing",
),
(
"-fno-strict-aliasing / -fwrapv",
"they only remove optimisations that would have needed specific source patterns",
),
(
"-mtune",
"tuning for a CPU changes instruction selection too subtly to separate from version differences",
),
(
"-mcpu within one architecture",
"cores sharing an instruction set (e.g. Cortex-M0, M0+ and M1) produce the same code",
),
(
"-W..., -std=..., -D..., -I...",
"diagnostics, language dialect, macros and include paths leave no trace in machine code",
),
];
}
fn reconstruct(f: &Features, r: &FlagReport) -> String {
let mut parts: Vec<String> = Vec::new();
let clang = r.family == Some(Compiler::Clang);
parts.push(match r.family {
Some(Compiler::Clang) => "clang".into(),
Some(Compiler::Gcc) => "arm-none-eabi-gcc".into(),
None => "cc".into(),
});
let cpu = r.attribute("Tag_CPU_name").filter(|c| c.starts_with("cortex"));
let (triple, march, default_cpu) = match r.arch {
Some("ARMv6-M") => ("armv6m-none-eabi", "armv6s-m", None),
Some("ARMv8-M Baseline") => ("armv8m.base-none-eabi", "armv8-m.base", None),
Some(a) if a.contains("DSP") => ("armv7em-none-eabi", "armv7e-m", Some("cortex-m4")),
Some(_) => ("armv7m-none-eabi", "armv7-m", None),
None => ("arm-none-eabi", "", None),
};
let decl_arch = r.attribute("Tag_CPU_arch").unwrap_or("");
let triple = if decl_arch == "v8-M.mainline" && r.arch.is_some_and(|a| a.contains("Mainline")) {
"armv8m.main-none-eabi"
} else {
triple
};
if clang {
parts.push(format!("--target={triple}"));
}
match cpu.or(default_cpu) {
Some(c) => parts.push(format!("-mcpu={c}")),
None if !clang && !march.is_empty() => parts.push(format!(
"-march={}",
if decl_arch == "v8-M.mainline" {
"armv8-m.main"
} else {
march
}
)),
None => {}
}
parts.push("-mthumb".into());
let tied = r.tied();
let narrowed: Vec<OptLevel> = tied.iter().copied().filter(|l| r.declared_levels.contains(l)).collect();
let quoted = if narrowed.is_empty() { tied } else { narrowed };
if !quoted.is_empty() {
let q: Vec<String> = quoted.iter().map(|l| l.to_string()).collect();
parts.push(q.join("|"));
}
let level = r.level();
for x in &r.findings {
let decl_on = x.declared.as_ref().is_some_and(|d| d.0);
let yes = x.verdict == Verdict::Yes && x.confidence >= 0.6;
let no = x.verdict == Verdict::No && x.confidence >= 0.75;
match x.flag {
"-fomit-frame-pointer" => {
if no && (clang || level != Some(OptLevel::O0)) {
parts.push("-fno-omit-frame-pointer".into());
} else if yes && level == Some(OptLevel::O0) && !clang {
parts.push(x.flag.into());
}
}
"-fshort-enums" => {
if let Some((d, _)) = &x.declared {
if *d && clang {
parts.push("-fshort-enums".into());
} else if !*d && !clang {
parts.push("-fno-short-enums".into());
}
}
}
"-mno-unaligned-access" => {
if (yes || (decl_on && x.verdict == Verdict::Unknown)) && is_thumb2(f) {
parts.push(x.flag.into());
}
}
"-fno-inline"
| "-fstack-protector"
| "-fpic"
| "-mlong-calls"
| "-flto"
| "-g"
| "-ffunction-sections"
| "-fdata-sections"
| "-fno-jump-tables"
| "-fropi"
| "-frwpi"
| "-momit-leaf-frame-pointer"
| "-mfloat-abi=soft" => {
if x.flag == "-fno-inline" {
continue;
}
if yes || (decl_on && x.verdict == Verdict::Unknown) {
parts.push(x.flag.into());
}
}
_ => {}
}
}
parts.join(" ")
}
pub fn detect(image: &Image) -> FlagReport {
let f = features(image);
let mut report = FlagReport {
compiler: image.comment.clone(),
attributes: build_attributes(&image.meta.attributes),
..Default::default()
};
let mut producers: Vec<&String> = image
.meta
.producers
.iter()
.filter(|p| !p.starts_with("GCC: "))
.collect();
producers.extend(image.producer.as_ref());
producers.sort_by_key(|p| std::cmp::Reverse(p.len()));
report.declared = image
.meta
.command_line
.clone()
.or_else(|| producers.first().filter(|p| p.contains(" -")).map(|p| p.to_string()));
identify_compiler(&f, image, &mut report);
if let Some(goal) = report.attribute("Tag_ABI_optimization_goals")
&& let Some(levels) = goal_levels(report.family, goal)
{
report.declared_levels = levels;
}
let declared_flag = report.declared.as_deref().and_then(declared_level);
if let Some(p) = &report.declared {
match declared_flag {
Some(l) => report.evidence.push(format!(
"the recorded command line declares {l} (a claim by the binary, not used for the guess)"
)),
None if p.contains(" -") => report
.evidence
.push("the recorded command line has no -O flag (GCC omits it at -O0)".into()),
None => {}
}
}
if f.funcs == 0 || f.insns == 0 {
report
.evidence
.push("no decodable functions: nothing to base a guess on".into());
flag_findings(&f, image, &mut report);
return report;
}
identify_target(&f, &mut report);
guess_level(&f, thumb1_case_helpers(image), &mut report);
flag_findings(&f, image, &mut report);
let conf = |l: OptLevel| report.candidates.iter().find(|c| c.0 == l).map_or(0.0, |c| c.1);
if let Some(best) = report.candidates.first().copied() {
if let Some(decl) = declared_flag {
let alias = match (decl, report.family) {
(OptLevel::Og, Some(Compiler::Clang)) => OptLevel::O1,
(d, _) => d,
};
if (alias == OptLevel::O0) != (best.0 == OptLevel::O0) {
report.contradictions.push(format!(
"the recorded command line declares {decl}, but the code is {}",
if best.0 == OptLevel::O0 {
"unoptimised"
} else {
"optimised"
}
));
} else if conf(alias) < best.1 * 0.2 {
report.evidence.push(format!(
"the code looks more like {} than the declared {decl} ({:.0}% against {:.0}%); optimised levels are hard to separate, so this is not counted as a contradiction",
best.0,
best.1 * 100.0,
conf(alias) * 100.0
));
}
}
if !report.declared_levels.is_empty() {
let unopt_decl = report.declared_levels == [OptLevel::O0];
if unopt_decl != (best.0 == OptLevel::O0) {
let d: Vec<String> = report.declared_levels.iter().map(|l| l.to_string()).collect();
report.contradictions.push(format!(
"build attributes record the optimisation goal of {}, but the code is {}",
d.join("/"),
if best.0 == OptLevel::O0 {
"unoptimised"
} else {
"optimised"
}
));
}
}
}
report.command_line = reconstruct(&f, &report);
report
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn declared_flag_parsing() {
assert_eq!(
declared_level("GNU C17 16.2.1 -mthumb -mcpu=cortex-m3 -g -O2"),
Some(OptLevel::O2)
);
assert_eq!(declared_level("GNU C17 -Os -O3"), Some(OptLevel::O3));
assert_eq!(declared_level("GNU C17 13.2.1 -mthumb -g"), None);
assert_eq!(OptLevel::Og.to_string(), "-Og");
}
#[test]
fn empty_image_has_no_candidates() {
let r = detect(&Image::default());
assert!(r.candidates.is_empty());
assert_eq!(r.best(), None);
}
}