cverif 0.0.1

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Compiler-flag identification: guesses the GCC optimisation level from the
//! shape of the generated Thumb-2 code.
//!
//! This is deliberately separate from the equivalence proof: the proof does not
//! care how the compiler chose its instructions, whereas this module looks only
//! at those choices.  Each optimisation level leaves structural fingerprints:
//!
//! * `-O0` keeps a frame pointer in `r7` and spills everything to the frame;
//! * `-Og` and `-O0` enter loops by jumping to a test placed at the bottom,
//!   while `-O1` and above copy the loop header (guard, then a bottom-tested
//!   loop), and `-Os` keeps the test at the top with an unconditional back edge;
//! * `-Os` divides by constants with `udiv`/`sdiv`, the speed levels multiply
//!   by a reciprocal;
//! * `-O2`/`-O3`/`-Os` schedule instructions, which separates compares from the
//!   conditional branch that consumes them, and `-O2`/`-O3` align functions;
//! * `-O3` peels, unrolls and versions loops and creates function clones.
//!
//! Simple code is frequently byte-identical at several levels; the report then
//! contains a tie rather than a guess.

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,
    Og,
}

impl OptLevel {
    pub const ALL: [OptLevel; 6] = [
        OptLevel::O0,
        OptLevel::O1,
        OptLevel::O2,
        OptLevel::O3,
        OptLevel::Os,
        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::Og => "-Og",
        })
    }
}

#[derive(Clone, Debug)]
pub struct FlagReport {
    /// Compiler identification from .comment, e.g. "GCC: (Gentoo 16.2.1_p20260926 p1) 16.2.1 20260926".
    pub compiler: Option<String>,
    /// Flags recorded in debug info (DW_AT_producer), when present. These are a claim by the binary, not evidence.
    pub declared: Option<String>,
    /// Candidate levels with a confidence in 0..=1, best first. Levels that cannot be told apart for this code
    /// share similar scores.
    pub candidates: Vec<(OptLevel, f32)>,
    /// Human-readable observations that drove the guess (one per line in the report).
    pub evidence: Vec<String>,
}

impl FlagReport {
    pub fn best(&self) -> Option<OptLevel> {
        self.candidates.first().map(|c| c.0)
    }
}

/// Structural measurements taken from the code of an image.
#[derive(Clone, Debug, Default)]
pub struct Features {
    /// Functions that could be decoded.
    pub funcs: u32,
    pub insns: u32,
    /// Functions that set up `r7` as a frame pointer in their prologue.
    pub frame_pointer_funcs: u32,
    /// Loads and stores relative to `sp` or the `r7` frame pointer.
    pub frame_accesses: u32,
    /// Loops whose back edge is an unconditional branch to a test at the top.
    pub loops_top_tested: u32,
    /// Bottom-tested loops entered by an unconditional jump to the test.
    pub loops_entry_jump: u32,
    /// Bottom-tested loops entered by falling in (header copied / guarded).
    pub loops_rotated: u32,
    /// Bottom-tested loops immediately followed by another compare-and-branch
    /// (remainder handling after an unrolled or widened loop).
    pub loops_with_remainder: u32,
    /// Functions containing at least one loop, and their total size in bytes.
    pub loop_funcs: u32,
    pub loop_func_bytes: u32,
    /// Conditional branches directly preceded by the flag-setting instruction.
    pub branch_adjacent: u32,
    /// Conditional branches with a non-flag-setting instruction in between.
    pub branch_separated: u32,
    pub it_blocks: u32,
    /// `udiv`/`sdiv` whose divisor was loaded as an immediate just before.
    pub div_by_immediate: u32,
    /// Long multiplies (reciprocal multiplication for division by a constant).
    pub long_multiplies: u32,
    /// Function starts where 4-byte alignment needed padding and got it / did not get it.
    pub starts_padded: u32,
    pub starts_unpadded: u32,
    /// Symbols of function clones (`.constprop`, `.isra`, `.part`).
    pub clones: u32,
    /// Paired or multi-word memory accesses typical of widened loops (`strd`/`ldrd` outside prologues).
    pub dual_accesses: u32,
    /// Windows of four consecutive instructions, and how many of them repeat an earlier
    /// window of the same function (same operations, any registers): duplicated code
    /// from unrolling, peeling and loop versioning.
    pub windows: u32,
    pub repeated_windows: 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;
    while pc < end {
        if image.is_data_in_code(pc) {
            // Literal pool: skip to the end of the data range.
            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);
        }
        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, .. })
}

/// The operation of an instruction with registers and immediates abstracted away.
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,
            ..
        }
    )
}

/// Measure the structural features of all function symbols in the image.
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;
        }
    }
    // Alignment: a function ending at an address that is 2 modulo 4 is followed either
    // directly by the next one (no alignment) or after 2 bytes of padding (4-byte alignment).
    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;
            }
        }
    }
    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 {
                            // A loop tested at the top: the head starts with a compare and a conditional
                            // branch.  (Other backward jumps merely share an epilogue or a block.)
                            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;
                            // Is the loop entered by an unconditional jump from before its head to its test?
                            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;
        }
    }
    f
}

fn ratio(a: u32, b: u32) -> f32 {
    if a + b == 0 { 0.0 } else { a as f32 / (a + b) as f32 }
}

/// Find an optimisation flag in a DW_AT_producer string.
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" | "-Oz" => OptLevel::Os,
            "-Og" => OptLevel::Og,
            _ => continue,
        };
        found = Some(l); // the last -O flag wins, as in GCC
    }
    found
}

/// Guess the optimisation level an image was compiled with.
pub fn detect(image: &Image) -> FlagReport {
    let f = features(image);
    let mut report = FlagReport {
        compiler: image.comment.clone(),
        declared: image.producer.clone(),
        candidates: Vec::new(),
        evidence: Vec::new(),
    };
    if let Some(p) = &image.producer {
        match declared_level(p) {
            Some(l) => report.evidence.push(format!(
                "debug info declares {l} (a claim by the binary, not used for the guess)"
            )),
            None => report
                .evidence
                .push("debug info records no -O flag (GCC omits it at -O0)".into()),
        }
    }
    if f.funcs == 0 || f.insns == 0 {
        report
            .evidence
            .push("no decodable functions: nothing to base a guess on".into());
        return report;
    }
    // Scores are additive log-like weights; index by OptLevel::ALL order.
    let mut s = [0.0f32; 6];
    const O0: usize = 0;
    const O1: usize = 1;
    const O2: usize = 2;
    const O3: usize = 3;
    const OS: usize = 4;
    const OG: usize = 5;
    let ev = &mut report.evidence;

    // --- frame pointer and spilling: -O0 against everything else -------------------
    let fp = f.frame_pointer_funcs as f32 / f.funcs as f32;
    let frame = f.frame_accesses as f32 / f.insns as f32;
    if fp >= 0.6 && frame >= 0.2 {
        s[O0] += 10.0;
        ev.push(format!(
            "{} of {} functions keep a frame pointer in r7 and {:.0}% of instructions access the frame: unoptimised code",
            f.frame_pointer_funcs,
            f.funcs,
            frame * 100.0
        ));
    } else {
        s[O0] -= 10.0;
        ev.push(format!(
            "{} of {} functions use a frame pointer, {:.0}% of instructions access the frame: optimised code",
            f.frame_pointer_funcs,
            f.funcs,
            frame * 100.0
        ));
    }

    // --- loop shape -----------------------------------------------------------------
    let loops = f.loops_top_tested + f.loops_entry_jump + f.loops_rotated;
    if loops > 0 {
        let (top, entry, rot) = (
            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,
        );
        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] += 3.0 * top - 2.0 * (rot + entry);
        s[OG] += 3.0 * entry - 2.5 * (rot + top);
        for l in [O1, O2, O3] {
            s[l] += 2.0 * rot - 2.5 * (top + entry);
        }
    } else {
        ev.push("no loops: loop-shape evidence unavailable".into());
    }

    // --- division by constants ------------------------------------------------------
    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 == 0 {
            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;
        }
    }

    // --- instruction scheduling: compare separated from its branch --------------------
    let nb = f.branch_adjacent + f.branch_separated;
    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 {
            s[O1] += 1.0;
            s[OG] += 1.0;
            s[O2] -= 1.0;
            s[O3] -= 1.0;
        }
    }

    // --- function alignment -----------------------------------------------------------
    let na = f.starts_padded + f.starts_unpadded;
    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
        ));
        // One sample is weak evidence (in a linked image, padding also appears between objects).
        let w = na.min(3) as f32 / 3.0;
        let padded = f.starts_padded as f32 / na as f32;
        if padded >= 0.75 {
            s[O2] += 1.5 * w;
            s[O3] += 1.5 * w;
            for l in [O1, OS, OG] {
                s[l] -= 1.5 * w;
            }
        } else if padded <= 0.34 {
            s[O2] -= 2.0 * w;
            s[O3] -= 2.0 * w;
            for l in [O1, OS, OG] {
                s[l] += 0.5 * w;
            }
        }
    }

    // --- if-conversion ------------------------------------------------------------------
    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;
    }

    // --- aggressive loop transformations: -O3 against -O2 -------------------------------
    let mut o3 = 0.0;
    if f.clones > 0 {
        ev.push(format!(
            "{} function clone symbols (.constprop/.isra/.part): interprocedural cloning",
            f.clones
        ));
        o3 += 1.0;
    }
    if f.windows >= 40 {
        let dup = f.repeated_windows as f32 / f.windows as f32;
        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.08 {
            o3 += 2.5;
        } else if dup <= 0.04 && 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 += 1.0;
        }
    }
    // Duplication speaks for -O3 over -O2; its absence only speaks against -O3.
    s[O3] += o3;
    if o3 > 0.0 {
        s[O2] -= o3;
    }
    if o3 == 0.0 {
        ev.push("nothing distinguishes -O2 from -O3 in this code".into());
    }

    // Turn scores into confidences (softmax) and rank.
    let max = s.iter().cloned().fold(f32::MIN, f32::max);
    let exp: Vec<f32> = s.iter().map(|x| (x - max).exp()).collect();
    let total: f32 = exp.iter().sum();
    let mut cands: Vec<(OptLevel, f32)> = OptLevel::ALL.iter().zip(&exp).map(|(&l, &e)| (l, e / total)).collect();
    cands.sort_by(|a, b| b.1.total_cmp(&a.1));
    report.candidates = cands;

    if let Some(decl) = image.producer.as_deref().and_then(declared_level)
        && let Some(best) = report.best()
    {
        let conf = report.candidates.iter().find(|c| c.0 == decl).map_or(0.0, |c| c.1);
        if conf < report.candidates[0].1 * 0.5 {
            report.evidence.push(format!(
                "the code looks like {best}, which disagrees with the declared {decl}"
            ));
        }
    }
    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);
    }
}