cverif 0.0.3

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Machine code on its own: disassembly listings and symbolic path summaries of a function or
//! an address range, without any source to compare with.

use super::report::{self, FuncDetail};
use super::{Names, Style};
use crate::image::Image;
use crate::sym::{Ctx, Limits, Stop};
use crate::thumb::decode::{Op, decode};
use crate::thumb::exec::{Callee, Exit, Machine};
use std::fmt::Write as _;
use std::time::{Duration, Instant};

/// One line of a listing.
#[derive(Clone, Debug)]
pub struct Line {
    pub addr: u32,
    pub bytes: Vec<u8>,
    /// Mnemonic and operands, or `.word`/`.byte` for data in code.
    pub text: String,
}

/// Disassemble `[start, end)`.  Literal pools (as the image's mapping symbols mark them) are
/// listed as data.
pub fn disassemble(image: &Image, start: u32, end: u32) -> Vec<Line> {
    let mut out = Vec::new();
    let mut pc = start & !1;
    // Instructions left in the current IT block.
    let mut it_left = 0u8;
    while pc < end {
        if image.is_data_in_code(pc) {
            let n = if pc.is_multiple_of(4) && pc + 4 <= end && image.is_data_in_code(pc + 3) {
                4
            } else {
                1
            };
            let Some(b) = image.read(pc, n) else { break };
            let text = if n == 4 {
                format!(".word {:#010x}", u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
            } else {
                format!(".byte {:#04x}", b[0])
            };
            out.push(Line {
                addr: pc,
                bytes: b.to_vec(),
                text,
            });
            pc += n;
            it_left = 0;
            continue;
        }
        let avail = (end - pc).min(4);
        let bytes = image.read(pc, avail).or_else(|| image.read(pc, 2));
        let Some(insn) = bytes.and_then(|b| decode(b, pc, it_left > 0)) else {
            break;
        };
        if insn.len as u32 > end - pc {
            break;
        }
        let Some(b) = image.read(pc, insn.len as u32) else {
            break;
        };
        it_left = it_left.saturating_sub(1);
        if let Op::It { mask, .. } = insn.op {
            // The lowest set bit of the mask marks the end of the block.
            it_left = match mask & 0xf {
                0 => 0,
                m => 4 - m.trailing_zeros() as u8,
            };
        }
        out.push(Line {
            addr: pc,
            bytes: b.to_vec(),
            text: insn.to_string(),
        });
        pc += insn.len as u32;
    }
    out
}

/// A listing as text: one instruction per line, labels at symbols, branch targets named.
pub fn listing(image: &Image, names: &Names, start: u32, end: u32) -> String {
    let mut o = String::new();
    for l in disassemble(image, start, end) {
        if let Some(s) = image.func_at(l.addr).filter(|s| s.addr == l.addr) {
            let _ = writeln!(o, "  <{}>:", s.name);
        }
        let hex: String = if l.bytes.len() == 4 && !l.text.starts_with('.') {
            format!(
                "{:04x} {:04x}",
                u16::from_le_bytes([l.bytes[0], l.bytes[1]]),
                u16::from_le_bytes([l.bytes[2], l.bytes[3]])
            )
        } else if l.bytes.len() == 2 {
            format!("{:04x}", u16::from_le_bytes([l.bytes[0], l.bytes[1]]))
        } else {
            l.bytes.iter().rev().map(|b| format!("{b:02x}")).collect()
        };
        let mut line = format!("  {:8x}:  {hex:<9}  {}", l.addr, l.text);
        // Name the address an instruction refers to.
        if let Some(i) = l.text.rfind("0x")
            && !l.text.starts_with('.')
            && !l.text[..i].ends_with('#')
        {
            let digits: String = l.text[i + 2..].chars().take_while(|c| c.is_ascii_hexdigit()).collect();
            if let Some(n) = u32::from_str_radix(&digits, 16).ok().and_then(|a| {
                image
                    .externals
                    .get(&a)
                    .or_else(|| image.externals.get(&(a | 1)))
                    .cloned()
                    .or_else(|| names.locate(a))
            }) {
                let _ = write!(line, "  ; <{n}>");
            }
        }
        o.push_str(&line);
        o.push('\n');
    }
    o
}

/// The code `spec` designates: a function's name, an address inside a function, or an
/// explicit range `start-end` (hexadecimal).  Returns (label, start, end).
pub fn resolve(image: &Image, spec: &str) -> Result<(String, u32, u32), String> {
    let hex = |s: &str| u32::from_str_radix(s.trim_start_matches("0x"), 16).ok();
    if let Some(s) = image.func(spec) {
        return Ok((s.name.clone(), s.addr, s.addr + s.size.max(2)));
    }
    if let Some((a, b)) = spec.split_once('-')
        && let (Some(a), Some(b)) = (hex(a), hex(b))
    {
        if a >= b {
            return Err(format!("{spec}: empty address range"));
        }
        return Ok((format!("{:#x}-{b:#x}", a & !1), a & !1, b));
    }
    if let Some(a) = hex(spec) {
        let a = a & !1;
        return match image.func_at(a) {
            Some(s) if s.addr == a => Ok((s.name.clone(), a, a + s.size.max(2))),
            // Inside a function, or code without a symbol: from there to the end of what is known.
            Some(s) => Ok((format!("{}+{:#x}", s.name, a - s.addr), a, s.addr + s.size.max(2))),
            None => {
                let end = image
                    .segment_at(a)
                    .map(|seg| seg.addr + seg.data.len() as u32)
                    .ok_or_else(|| format!("{spec}: address outside the image"))?;
                let next = image
                    .symbols
                    .iter()
                    .filter(|s| s.addr > a && s.kind == crate::image::SymKind::Func)
                    .map(|s| s.addr)
                    .min()
                    .unwrap_or(end);
                Ok((format!("{a:#x}"), a, next.min(end)))
            }
        };
    }
    Err(format!("{spec}: no such function symbol, and not an address"))
}

/// Limits of a stand-alone symbolic execution.
#[derive(Clone, Copy, Debug)]
pub struct Budget {
    pub max_paths: usize,
    pub limits: Limits,
    pub work_limit: u64,
    pub time_limit: Duration,
}

impl Default for Budget {
    fn default() -> Budget {
        Budget {
            max_paths: 64,
            limits: Limits {
                max_depth: 16,
                ..Limits::default()
            },
            work_limit: 200_000,
            time_limit: Duration::from_secs(30),
        }
    }
}

/// Symbolically execute the machine code from `start` with every register and all of memory
/// unknown, and summarise each path: its condition, the value returned in r0, the stores to
/// memory and the calls made.  Calls and jumps that leave `[start, end)` are events (their
/// results are fresh unknowns); `true` in the result says that not every path was explored.
pub fn summarize(image: &Image, start: u32, end: u32, budget: &Budget) -> (FuncDetail, bool) {
    let mut ctx = Ctx::new(budget.limits);
    ctx.set_budget(budget.work_limit, 20_000_000, Some(Instant::now() + budget.time_limit));
    ctx.prover.rom = image
        .segments
        .iter()
        .filter(|s| !s.writable)
        .map(|s| (s.addr, s.data.clone()))
        .collect();
    let mut regs = [0; 16];
    for (i, r) in regs.iter_mut().enumerate().take(13) {
        *r = ctx.named_sym(&format!("r{i}"), 32);
    }
    if let Some(sb) = image.static_base {
        regs[9] = ctx.tm.konst(32, sb as u64);
    }
    regs[13] = ctx.private_base("SP0");
    regs[14] = ctx.named_sym("LR0", 32);
    regs[15] = ctx.tm.konst(32, 0);
    let lr0 = regs[14];
    let low = ctx.tm.extract(regs[13], 0, 3);
    let z3 = ctx.tm.konst(3, 0);
    let pre = vec![ctx.tm.eq(low, z3)];
    let classify = |addr: u32| -> Callee {
        if let Some(name) = image.externals.get(&addr) {
            return Callee::External(name.clone());
        }
        let a = addr & !1;
        if a >= start && a < end {
            return Callee::Internal;
        }
        match image.func_at(a) {
            Some(s) if s.addr == a => Callee::External(s.name.clone()),
            Some(s) => Callee::External(format!("{}+{:#x}", s.name, a - s.addr)),
            None => Callee::External(format!("{a:#x}")),
        }
    };
    report::begin_function(budget.max_paths);
    let mut explored = 0usize;
    let mut partial = false;
    loop {
        ctx.restart(&pre);
        report::begin_path(pre.len());
        explored += 1;
        let mut m = Machine::new(&mut ctx, start, regs);
        // Nothing says which addresses are peripherals: every access is a plain one.
        m.mmio = Vec::new();
        let mut k = 0usize;
        let outcome = loop {
            match m.run(&mut ctx, image, lr0, &classify) {
                Ok(Exit::Call { name }) => {
                    report::note_call(&m, &name, None);
                    m.mem.world.clear();
                    m.mem.epoch += 1;
                    let ret = ctx.named_sym(&format!("ret{k}:{name}"), 32);
                    m.finish_call(&mut ctx, k, Some(ret), None);
                    k += 1;
                    if k > 64 {
                        break "not explored to the end: more than 64 calls".to_string();
                    }
                }
                Ok(Exit::Asm { name, out, .. }) => {
                    report::note_call(&m, &format!("`{name}`"), Some(0));
                    if let Some(rd) = out {
                        m.regs[rd as usize] = ctx.named_sym(&format!("ret{k}:asm:{name}"), 32);
                    }
                    k += 1;
                    if k > 64 {
                        break "not explored to the end: more than 64 calls".to_string();
                    }
                }
                Ok(Exit::Return) => {
                    report::note_return(&m, Some(32));
                    break "returns".to_string();
                }
                Ok(Exit::Trap) => break "traps (udf)".to_string(),
                Ok(Exit::Cut(_)) => break "stopped at a cut point".to_string(),
                Err(Stop::Truncated(why)) => {
                    partial = true;
                    break format!("not explored to the end: {why}");
                }
                Err(Stop::Unsupported(why)) => break format!("not modelled: {why}"),
                Err(Stop::Mismatch(why, _)) | Err(Stop::Inconclusive(why)) => break why,
                Err(Stop::Undefined) => break "unreachable".to_string(),
                Err(Stop::Halt) => break "does not return".to_string(),
            }
        };
        report::end_path_as(&ctx, None, 0, outcome);
        if ctx.check_deadline().is_err() {
            partial = true;
            break;
        }
        if explored >= budget.max_paths {
            // Is there anything left?
            partial |= ctx.next_path();
            break;
        }
        if !ctx.next_path() {
            break;
        }
    }
    let (paths, skipped) = report::take_paths();
    report::begin_function(0);
    (
        FuncDetail {
            explanation: None,
            paths,
            skipped_paths: skipped,
        },
        partial,
    )
}

/// `cverif --dump-binary`: the listing of the code `spec` designates and its path summaries.
pub fn dump_binary(image: &Image, spec: &str, style: Style, budget: &Budget) -> Result<String, String> {
    let (label, start, end) = resolve(image, spec)?;
    if !image.segment_at(start).is_some_and(|s| s.exec) {
        return Err(format!("{spec}: {start:#x} is not in an executable part of the image"));
    }
    let names = Names::new(image, None);
    let mut o = String::new();
    let _ = writeln!(o, "{label}: {start:#x}-{end:#x} ({} bytes)", end - start);
    o.push_str(&listing(image, &names, start, end));
    o.push_str(&summary_text(image, &names, start, end, style, budget));
    Ok(o)
}

/// The symbolic summary of `[start, end)` as text.
pub fn summary_text(image: &Image, names: &Names, start: u32, end: u32, style: Style, budget: &Budget) -> String {
    let mut o = String::new();
    let (detail, partial) = summarize(image, start, end, budget);
    let _ = writeln!(
        o,
        "  symbolic summary: {} path{}{} (inputs: r0-r12, sp0, lr0 and memory at entry)",
        detail.paths.len(),
        if detail.paths.len() == 1 { "" } else { "s" },
        if partial { ", NOT ALL PATHS EXPLORED" } else { "" }
    );
    o.push_str(&detail.dump_text(names, style));
    o
}