cverif 0.0.6

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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
//! Binary images: ELF32 ARM files (relocatable objects and linked executables)
//! and raw binaries accompanied by a symbol table.

use std::collections::HashMap;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SymKind {
    Func,
    Object,
    Other,
}

#[derive(Clone, Debug)]
pub struct Symbol {
    pub name: String,
    /// Address with the Thumb bit cleared.
    pub addr: u32,
    pub size: u32,
    pub kind: SymKind,
    pub global: bool,
    /// The object or source file the symbol comes from, when the image says (ELF `FILE`
    /// symbols, linker map contributions).
    pub file: Option<String>,
}

#[derive(Clone, Debug)]
pub struct Segment {
    pub name: String,
    pub addr: u32,
    pub data: Vec<u8>,
    pub writable: bool,
    pub exec: bool,
    /// Where the bytes are stored in the load image when that differs from `addr`
    /// (initialised data kept in flash and copied to RAM by startup code).
    pub load_addr: Option<u32>,
}

#[derive(Clone, Default, Debug)]
pub struct Image {
    pub segments: Vec<Segment>,
    pub symbols: Vec<Symbol>,
    /// Fake addresses assigned to undefined symbols (calls to them are external calls).
    pub externals: HashMap<u32, String>,
    /// Data-in-code ranges inside executable segments (literal pools), from `$d` mapping symbols.
    pub data_ranges: Vec<(u32, u32)>,
    /// Contents of `.comment` (compiler identification).
    pub comment: Option<String>,
    /// DW_AT_producer string if debug info is present (records the command-line flags).
    pub producer: Option<String>,
    /// `Tag_ABI_enum_size` of the ARM build attributes: true when enumerated types take the
    /// smallest type that fits, false when they are at least `int`.
    pub short_enums: Option<bool>,
    /// Value of the static base register (r9) for code built with read-write position
    /// independence (`-frwpi`): the address its data offsets are relative to.
    pub static_base: Option<u32>,
    /// The image declares (in its build attributes) that data is addressed relative to r9.
    pub rwpi: bool,
    /// A linked image (not a relocatable object, whose static base cverif chooses itself).
    pub needs_static_base: bool,
    /// Start addresses of the contributions of each object file, sorted: the bytes from one
    /// entry up to the next belong to the named file.
    pub owners: Vec<(u32, String)>,
    /// ELF metadata that does not affect verification (build attributes, section names,
    /// relocation statistics); used to identify how the binary was built.
    pub meta: ElfMeta,
    /// Built for the hard-float variant of the procedure call standard: floating-point
    /// arguments and results travel in VFP registers.
    pub hard_float: bool,
    /// Nothing authoritative says where code ends and data begins (a raw, HEX or S-record
    /// image described by a symbol listing only, or by discovery): loaded bytes outside the
    /// code are then data only where something accounts for them.
    pub soft_bounds: bool,
    /// Address ranges taken to be data without proof, with who says so: (start, end, why).
    pub set_aside: Vec<(u32, u32, String)>,
}

/// Static base used when laying out a relocatable object that has SB-relative relocations.
pub const OBJECT_STATIC_BASE: u32 = 0x2000_0000;

fn u16le(b: &[u8], o: usize) -> u32 {
    u16::from_le_bytes([b[o], b[o + 1]]) as u32
}

fn u32le(b: &[u8], o: usize) -> u32 {
    u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
}

fn cstr(b: &[u8], o: usize) -> String {
    let end = b[o.min(b.len())..]
        .iter()
        .position(|&c| c == 0)
        .map_or(b.len(), |p| o + p);
    String::from_utf8_lossy(&b[o.min(b.len())..end]).into_owned()
}

/// A linked file is loaded through its program headers, while everything here reads it through
/// its section headers.  The two views must describe the same bytes, or the verifier would
/// examine code that is not what runs: refuse a file in which a section's contents are not the
/// bytes its load segment puts at that address, or in which sections or load segments overlap,
/// and expose executable bytes that a load segment brings in without any section describing
/// them as code that nothing vouches for.
fn load_view(bytes: &[u8], secs: &[Section], img: &mut Image) -> Result<(), String> {
    let (phoff, phentsize, phnum) = (
        u32le(bytes, 28) as usize,
        u16le(bytes, 42) as usize,
        u16le(bytes, 44) as usize,
    );
    if phoff == 0 || phnum == 0 {
        return Ok(());
    }
    if phentsize < 32 || phoff + phnum * phentsize > bytes.len() {
        return Err("ELF program headers extend past the end of the file".into());
    }
    // (file offset, address, bytes in the file, executable)
    let mut loads: Vec<(u64, u64, u64, bool)> = Vec::new();
    for i in 0..phnum {
        let o = phoff + i * phentsize;
        if u32le(bytes, o) != 1 {
            continue;
        }
        let (off, vaddr, filesz) = (
            u32le(bytes, o + 4) as u64,
            u32le(bytes, o + 8) as u64,
            u32le(bytes, o + 16) as u64,
        );
        if filesz == 0 {
            continue;
        }
        if off + filesz > bytes.len() as u64 {
            return Err("ELF load segment extends past the end of the file".into());
        }
        if loads.iter().any(|l| vaddr < l.1 + l.2 && l.1 < vaddr + filesz) {
            return Err("ELF load segments overlap".into());
        }
        loads.push((off, vaddr, filesz, u32le(bytes, o + 24) & 1 != 0));
    }
    if loads.is_empty() {
        return Ok(());
    }
    let mut described: Vec<(u64, u64)> = Vec::new();
    for s in secs {
        if s.flags & SHF_ALLOC == 0 || s.size == 0 || s.flags & 0x400 != 0 {
            continue;
        }
        let (a, e) = (s.addr as u64, s.addr as u64 + s.size as u64);
        if described.iter().any(|d| a < d.1 && d.0 < e) {
            return Err(format!("section {} overlaps another section", s.name));
        }
        described.push((a, e));
        if s.ty == SHT_NOBITS {
            continue;
        }
        let same = loads
            .iter()
            .any(|l| a >= l.1 && e <= l.1 + l.2 && l.0 + (a - l.1) == s.offset as u64);
        if !same {
            return Err(format!(
                "section {} does not hold the bytes the program headers load at {:#x}",
                s.name, s.addr
            ));
        }
    }
    described.sort_unstable();
    for (n, &(off, vaddr, filesz, exec)) in loads.iter().enumerate() {
        if !exec {
            continue;
        }
        let mut at = vaddr;
        let end = vaddr + filesz;
        let mut gaps = Vec::new();
        for &(a, e) in &described {
            if e <= at || a >= end {
                continue;
            }
            if a > at {
                gaps.push((at, a));
            }
            at = at.max(e);
        }
        if at < end {
            gaps.push((at, end));
        }
        for (a, e) in gaps {
            let o = (off + (a - vaddr)) as usize;
            img.segments.push(Segment {
                name: format!("<load segment {n}, no section>"),
                addr: a as u32,
                data: bytes[o..o + (e - a) as usize].to_vec(),
                writable: false,
                exec: true,
                load_addr: None,
            });
        }
    }
    Ok(())
}

struct Section {
    name: String,
    ty: u32,
    flags: u32,
    addr: u32,
    offset: usize,
    size: usize,
    link: u32,
    info: u32,
    align: u32,
}

const SHT_PROGBITS: u32 = 1;
const SHT_SYMTAB: u32 = 2;
const SHT_NOBITS: u32 = 8;
const SHT_REL: u32 = 9;
const SHT_INIT_ARRAY: u32 = 14;
const SHF_WRITE: u32 = 1;
const SHF_ALLOC: u32 = 2;
const SHF_EXEC: u32 = 4;

impl Image {
    pub fn is_elf(bytes: &[u8]) -> bool {
        bytes.starts_with(b"\x7fELF")
    }

    pub fn from_elf(bytes: &[u8]) -> Result<Image, String> {
        if bytes.len() < 52 || !Self::is_elf(bytes) {
            return Err("not an ELF file".into());
        }
        if bytes[4] != 1 || bytes[5] != 1 {
            return Err("only 32-bit little-endian ELF files are supported".into());
        }
        let etype = u16le(bytes, 16);
        if u16le(bytes, 18) != 40 {
            return Err("not an ARM ELF file".into());
        }
        let shoff = u32le(bytes, 32) as usize;
        let shentsize = u16le(bytes, 46) as usize;
        let shnum = u16le(bytes, 48) as usize;
        let shstrndx = u16le(bytes, 50) as usize;
        if shoff == 0 || shnum == 0 || shoff + shnum * shentsize > bytes.len() || shentsize < 40 {
            return Err("ELF file has no usable section headers".into());
        }
        let mut secs: Vec<Section> = (0..shnum)
            .map(|i| {
                let o = shoff + i * shentsize;
                Section {
                    name: String::new(),
                    ty: u32le(bytes, o + 4),
                    flags: u32le(bytes, o + 8),
                    addr: u32le(bytes, o + 12),
                    offset: u32le(bytes, o + 16) as usize,
                    size: u32le(bytes, o + 20) as usize,
                    link: u32le(bytes, o + 24),
                    info: u32le(bytes, o + 28),
                    align: u32le(bytes, o + 32),
                }
            })
            .collect();
        let name_offs: Vec<usize> = (0..shnum)
            .map(|i| u32le(bytes, shoff + i * shentsize) as usize)
            .collect();
        if shstrndx < shnum {
            let stroff = secs[shstrndx].offset;
            for (s, no) in secs.iter_mut().zip(&name_offs) {
                s.name = cstr(bytes, stroff + no);
            }
        }
        for s in &secs {
            if s.ty != SHT_NOBITS && s.offset + s.size > bytes.len() {
                return Err(format!("section {} extends past the end of the file", s.name));
            }
        }
        let relocatable = etype == 1;
        if relocatable {
            // Lay the allocated sections out one after another.
            let mut addr = 0x0001_0000u32;
            for s in secs.iter_mut() {
                if s.flags & SHF_ALLOC != 0 {
                    addr = addr.next_multiple_of(s.align.max(1));
                    s.addr = addr;
                    addr += s.size as u32;
                    // Keep sections apart so that an out-of-bounds access cannot silently hit a neighbour.
                    addr += 16;
                }
            }
        }
        // Load addresses come from the program headers.
        let phoff = u32le(bytes, 28) as usize;
        let phentsize = u16le(bytes, 42) as usize;
        let phnum = u16le(bytes, 44) as usize;
        let mut loads: Vec<(u32, u32, u32, u32)> = Vec::new(); // (offset, vaddr, paddr, filesz)
        if !relocatable && phoff != 0 && phentsize >= 32 && phoff + phnum * phentsize <= bytes.len() {
            for i in 0..phnum {
                let o = phoff + i * phentsize;
                if u32le(bytes, o) == 1 {
                    loads.push((
                        u32le(bytes, o + 4),
                        u32le(bytes, o + 8),
                        u32le(bytes, o + 12),
                        u32le(bytes, o + 16),
                    ));
                }
            }
        }
        let load_addr = |s: &Section| -> Option<u32> {
            if s.ty == SHT_NOBITS {
                return None;
            }
            loads
                .iter()
                .find(|l| s.offset as u32 >= l.0 && (s.offset as u32) < l.0 + l.3)
                .map(|l| l.2 + (s.offset as u32 - l.0))
        };
        let mut img = Image::default();
        let mut seg_of_sec: HashMap<usize, usize> = HashMap::new();
        for (i, s) in secs.iter().enumerate() {
            if s.flags & SHF_ALLOC != 0
                && s.size > 0
                && matches!(s.ty, SHT_PROGBITS | SHT_NOBITS | SHT_INIT_ARRAY | 15 | 16)
            {
                let data = if s.ty == SHT_NOBITS {
                    vec![0; s.size]
                } else {
                    bytes[s.offset..s.offset + s.size].to_vec()
                };
                seg_of_sec.insert(i, img.segments.len());
                img.segments.push(Segment {
                    name: s.name.clone(),
                    addr: s.addr,
                    data,
                    writable: s.flags & SHF_WRITE != 0,
                    exec: s.flags & SHF_EXEC != 0,
                    load_addr: load_addr(s).filter(|&l| l != s.addr),
                });
            }
            let raw = || &bytes[s.offset..s.offset + s.size];
            if s.ty == 0x7000_0003 && s.offset + s.size <= bytes.len() {
                // SHT_ARM_ATTRIBUTES: Tag_ABI_PCS_RW_data = 2 means SB-relative data.
                img.rwpi = aeabi_attribute(raw(), 15) == Some(2);
                img.hard_float |= crate::fp::vfp_args(raw());
                img.short_enums = match aeabi_attribute(raw(), 26) {
                    Some(1) => Some(true),
                    Some(2) => Some(false),
                    _ => img.short_enums,
                };
            }
            if s.name == ".comment" && s.ty == SHT_PROGBITS {
                let text: Vec<String> = raw()
                    .split(|&c| c == 0)
                    .filter(|p| !p.is_empty())
                    .map(|p| String::from_utf8_lossy(p).into_owned())
                    .collect();
                img.comment = Some(text.join("; "));
            }
            if (s.name == ".debug_str" || s.name == ".debug_info" || s.name == ".debug_line_str")
                && img.producer.is_none()
            {
                let d = raw();
                if let Some(p) = d.windows(5).position(|w| w == b"GNU C") {
                    img.producer = Some(cstr(d, p));
                }
            }
        }
        if !relocatable {
            load_view(bytes, &secs, &mut img)?;
        }
        // Symbols.
        struct RawSym {
            name: String,
            value: u32,
            shndx: usize,
            info: u8,
        }
        let mut raw_syms: Vec<RawSym> = Vec::new();
        let mut ext_next = img
            .segments
            .iter()
            .map(|s| s.addr + s.data.len() as u32)
            .max()
            .unwrap_or(0x10000)
            .next_multiple_of(16)
            + 0x100;
        let mut ext_by_name: HashMap<String, u32> = HashMap::new();
        let mut sym_addr: Vec<u32> = Vec::new();
        if let Some(st) = secs.iter().find(|s| s.ty == SHT_SYMTAB) {
            let stroff = secs.get(st.link as usize).map_or(0, |s| s.offset);
            let mut code_marks: Vec<(u32, bool)> = Vec::new();
            let mut cur_file: Option<String> = None;
            for i in 0..st.size / 16 {
                let o = st.offset + i * 16;
                let name = cstr(bytes, stroff + u32le(bytes, o) as usize);
                let value = u32le(bytes, o + 4);
                let size = u32le(bytes, o + 8);
                let info = bytes[o + 12];
                let shndx = u16le(bytes, o + 14) as usize;
                let ty = info & 0xf;
                if ty == 4 {
                    cur_file = Some(name.clone());
                }
                let local = info >> 4 == 0;
                let base = if relocatable && shndx != 0 && shndx < shnum {
                    secs[shndx].addr
                } else {
                    0
                };
                let mut addr = base.wrapping_add(value);
                if shndx == 0 && i != 0 && ty != 3 {
                    // Undefined symbol: give it a fake address.
                    addr = *ext_by_name.entry(name.clone()).or_insert_with(|| {
                        let a = ext_next;
                        ext_next += 16;
                        a
                    });
                    img.externals.insert(addr, name.clone());
                    if ty == 2 || ty == 0 {
                        addr |= 1;
                    }
                } else if shndx == 0xfff1 && !relocatable && ty == 0 && !name.is_empty() {
                    // An absolute symbol of a linked image: defined by the linker script.
                    img.symbols.push(Symbol {
                        name: name.clone(),
                        addr,
                        size: 0,
                        kind: SymKind::Other,
                        global: !local,
                        file: None,
                    });
                } else if shndx != 0 && shndx < shnum {
                    if local
                        && secs[shndx].flags & SHF_ALLOC != 0
                        && ty != 3
                        && let Some(f) = &cur_file
                    {
                        img.owners.push((addr & !1, f.clone()));
                    }
                    if name == "$t" || name == "$a" || name.starts_with("$t.") {
                        code_marks.push((addr, true));
                    } else if name == "$d" || name.starts_with("$d.") {
                        if secs[shndx].flags & SHF_EXEC != 0 {
                            code_marks.push((addr, false));
                        }
                    } else if !name.is_empty() && matches!(ty, 0..=2) && secs[shndx].flags & SHF_ALLOC != 0 {
                        let kind = match ty {
                            2 => SymKind::Func,
                            1 => SymKind::Object,
                            _ => SymKind::Other,
                        };
                        img.symbols.push(Symbol {
                            name: name.clone(),
                            addr: addr & !((kind == SymKind::Func) as u32),
                            size,
                            kind,
                            global: info >> 4 != 0,
                            file: if local { cur_file.clone() } else { None },
                        });
                    }
                }
                sym_addr.push(addr);
                raw_syms.push(RawSym {
                    name,
                    value,
                    shndx,
                    info,
                });
            }
            // Turn mapping symbols into data ranges.
            code_marks.sort();
            for (i, &(a, is_code)) in code_marks.iter().enumerate() {
                if is_code {
                    continue;
                }
                let seg_end = img
                    .segments
                    .iter()
                    .find(|s| a >= s.addr && a < s.addr + s.data.len() as u32)
                    .map(|s| s.addr + s.data.len() as u32);
                let Some(seg_end) = seg_end else { continue };
                let end = code_marks[i + 1..]
                    .iter()
                    .find(|m| m.1)
                    .map_or(seg_end, |m| m.0.min(seg_end));
                img.data_ranges.push((a, end));
            }
        }
        let _ = &raw_syms;
        if relocatable {
            for s in &secs {
                if s.ty != SHT_REL {
                    continue;
                }
                let Some(&seg) = seg_of_sec.get(&(s.info as usize)) else {
                    continue;
                };
                let target = &secs[s.info as usize];
                for i in 0..s.size / 8 {
                    let o = s.offset + i * 8;
                    let off = u32le(bytes, o);
                    let info = u32le(bytes, o + 4);
                    let (symi, rty) = ((info >> 8) as usize, info & 0xff);
                    let Some(&sv) = sym_addr.get(symi) else {
                        return Err("relocation refers to a bad symbol".into());
                    };
                    let rs = &raw_syms[symi];
                    let is_func = rs.info & 0xf == 2 || (rs.shndx == 0 && rs.info & 0xf == 0);
                    let _ = rs.value;
                    let t = if is_func { sv & 1 } else { 0 };
                    let s_addr = sv & !t;
                    let p = target.addr + off;
                    let o = off as usize;
                    let data = &img.segments[seg].data;
                    // R_ARM_THM_JUMP11 and R_ARM_THM_JUMP8 patch a 16-bit instruction.
                    let width = if matches!(rty, 102 | 103) { 2 } else { 4 };
                    if o + width > data.len() {
                        return Err("relocation outside its section".into());
                    }
                    // SB-relative relocations: the symbol's offset from the static base.
                    let (rty, s_addr, t) = match rty {
                        9 | 87..=89 => {
                            img.static_base = Some(OBJECT_STATIC_BASE);
                            let rel = s_addr.wrapping_sub(OBJECT_STATIC_BASE);
                            (
                                if rty == 9 {
                                    2
                                } else if rty == 88 {
                                    48
                                } else {
                                    47
                                },
                                rel,
                                0,
                            )
                        }
                        _ => (rty, s_addr, t),
                    };
                    let data = &mut img.segments[seg].data;
                    apply_reloc(data, o, rty, s_addr, t, p).map_err(|e| format!("{e} (symbol {})", rs.name))?;
                }
            }
        }
        img.needs_static_base = !relocatable;
        if !relocatable {
            // A linked image keeps its relocations with `--emit-relocs`: SB-relative ones give
            // away the static base (value in place = S + A - SB; A is zero more often than not).
            let mut votes: HashMap<u32, u32> = HashMap::new();
            for s in secs.iter().filter(|s| s.ty == SHT_REL) {
                for i in 0..s.size / 8 {
                    let o = s.offset + i * 8;
                    let (off, info) = (u32le(bytes, o), u32le(bytes, o + 4));
                    let (symi, rty) = ((info >> 8) as usize, info & 0xff);
                    let Some(&sv) = sym_addr.get(symi) else { continue };
                    let value = match rty {
                        9 => img.read(off, 4).map(|d| u32le(d, 0)),
                        87 | 89 => img.read(off, 8).and_then(|d| {
                            let imm = |o: usize| {
                                let (hw1, hw2) = (u16le(d, o), u16le(d, o + 2));
                                (hw1 & 0xf) << 12 | (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | (hw2 & 0xff)
                            };
                            // movw immediately followed by the matching movt
                            (u16le(d, 4) & 0xfbf0 == 0xf2c0).then(|| imm(4) << 16 | imm(0))
                        }),
                        _ => None,
                    };
                    if let Some(v) = value {
                        *votes.entry((sv & !1).wrapping_sub(v)).or_default() += 1;
                    }
                }
            }
            let total: u32 = votes.values().sum();
            if let Some((&sb, &n)) = votes.iter().max_by_key(|(sb, n)| (**n, std::cmp::Reverse(**sb)))
                && n * 2 > total
            {
                img.static_base = Some(sb);
            }
        }
        img.meta = ElfMeta::parse(bytes);
        img.finish();
        Ok(img)
    }

    /// A raw binary loaded at `base`, with symbols given in `nm` format:
    /// `address [size] type name` per line (hex address and size).
    pub fn from_raw(bytes: &[u8], base: u32, symtab: &str) -> Result<Image, String> {
        let info = crate::inputs::parse_symbols(symtab)?;
        crate::inputs::build_image(vec![(base, bytes.to_vec())], &info)
    }

    pub(crate) fn finish(&mut self) {
        self.symbols
            .sort_by_key(|s| (s.addr, s.kind != SymKind::Func, s.name.clone()));
        // Infer missing function sizes from the next symbol or the end of the segment.
        let addrs: Vec<u32> = self.symbols.iter().map(|s| s.addr).collect();
        for i in 0..self.symbols.len() {
            if self.symbols[i].size != 0 || self.symbols[i].kind == SymKind::Other {
                continue;
            }
            let a = self.symbols[i].addr;
            let seg_end = self
                .segments
                .iter()
                .find(|s| a >= s.addr && a < s.addr + s.data.len() as u32)
                .map(|s| s.addr + s.data.len() as u32);
            let next = addrs.iter().copied().filter(|&x| x > a).min();
            if let Some(end) = match (seg_end, next) {
                (Some(e), Some(n)) => Some(e.min(n)),
                (Some(e), None) => Some(e),
                _ => None,
            } {
                self.symbols[i].size = end - a;
            }
        }
        self.data_ranges.sort();
        self.owners.sort();
        self.owners.dedup();
        for i in 0..self.symbols.len() {
            if self.symbols[i].file.is_none() && self.symbols[i].kind != SymKind::Other {
                self.symbols[i].file = self.owner(self.symbols[i].addr).map(str::to_string);
            }
        }
    }

    /// The object file that contributed the byte at `addr`, if the image records it.
    pub fn owner(&self, addr: u32) -> Option<&str> {
        let seg = self.segment_at(addr)?;
        let i = self.owners.partition_point(|o| o.0 <= addr);
        let (start, name) = self.owners.get(i.checked_sub(1)?)?;
        (*start >= seg.addr).then_some(name.as_str())
    }

    /// All symbols with this name that are functions (or not), locals included.
    pub fn named(&self, name: &str, func: bool) -> impl Iterator<Item = &Symbol> {
        self.symbols
            .iter()
            .filter(move |s| (s.kind == SymKind::Func) == func && s.name == name)
    }

    pub fn segment_at(&self, addr: u32) -> Option<&Segment> {
        self.segments
            .iter()
            .find(|s| addr >= s.addr && addr - s.addr < s.data.len() as u32)
    }

    /// Bytes at `addr`, if they lie in a loaded segment.
    pub fn read(&self, addr: u32, n: u32) -> Option<&[u8]> {
        let s = self.segment_at(addr)?;
        let o = (addr - s.addr) as usize;
        s.data.get(o..o + n as usize)
    }

    /// Bytes at `addr` if they lie in a read-only segment (their value can be relied upon).
    pub fn read_const(&self, addr: u32, n: u32) -> Option<&[u8]> {
        let s = self.segment_at(addr)?;
        if s.writable {
            return None;
        }
        let o = (addr - s.addr) as usize;
        s.data.get(o..o + n as usize)
    }

    pub fn func(&self, name: &str) -> Option<&Symbol> {
        self.symbols.iter().find(|s| s.kind == SymKind::Func && s.name == name)
    }

    /// The function symbol at `addr`.  Code may have several names; of a run-time routine
    /// that serves as both `__aeabi_uidiv` and `__aeabi_uidivmod` (one routine that leaves
    /// the quotient and the remainder), the name that promises more is the one to go by:
    /// a caller may be using either result.
    pub fn func_at(&self, addr: u32) -> Option<&Symbol> {
        let mut at = (self.symbols.iter()).filter(|s| s.kind == SymKind::Func && s.addr == addr);
        let first = at.next()?;
        if first.name.ends_with("divmod") {
            return Some(first);
        }
        Some(
            at.find(|s| s.name.starts_with("__aeabi_") && s.name.ends_with("divmod"))
                .unwrap_or(first),
        )
    }

    /// Built for a processor with the 16-bit Thumb instruction set only (ARMv6-M), by the
    /// build attributes.
    pub fn thumb1_only(&self) -> bool {
        matches!(aeabi_attribute(&self.meta.attributes, 6), Some(11 | 12))
    }

    pub fn object(&self, name: &str) -> Option<&Symbol> {
        self.symbols.iter().find(|s| s.kind != SymKind::Func && s.name == name)
    }

    pub fn is_data_in_code(&self, addr: u32) -> bool {
        self.data_ranges.iter().any(|&(a, b)| addr >= a && addr < b)
    }
}

/// Value of an integer-valued tag in the file scope of the "aeabi" build attributes.
fn aeabi_attribute(d: &[u8], want: u32) -> Option<u32> {
    fn uleb(d: &[u8], p: &mut usize) -> Option<u32> {
        let (mut v, mut shift) = (0u32, 0);
        loop {
            let b = *d.get(*p)?;
            *p += 1;
            v |= ((b & 0x7f) as u32).checked_shl(shift).unwrap_or(0);
            shift += 7;
            if b & 0x80 == 0 {
                return Some(v);
            }
        }
    }
    fn ntbs(d: &[u8], p: &mut usize) -> Option<()> {
        *p += d.get(*p..)?.iter().position(|&c| c == 0)? + 1;
        Some(())
    }
    if d.first() != Some(&b'A') {
        return None;
    }
    let mut p = 1;
    while p + 4 <= d.len() {
        let len = u32le(d, p) as usize;
        let end = (p + len).min(d.len());
        let mut q = p + 4;
        let vendor_end = q + d.get(q..end)?.iter().position(|&c| c == 0)?;
        let is_aeabi = &d[q..vendor_end] == b"aeabi";
        q = vendor_end + 1;
        while is_aeabi && q + 5 <= end {
            let tag = d[q];
            let sub_end = (q + u32le(d, q + 1) as usize).min(end);
            let mut r = q + 5;
            while tag == 1 && r < sub_end {
                let t = uleb(d, &mut r)?;
                match t {
                    4 | 5 | 65 | 67 => ntbs(d, &mut r)?,
                    32 => {
                        uleb(d, &mut r)?;
                        ntbs(d, &mut r)?;
                    }
                    t if t > 32 && t % 2 == 1 => ntbs(d, &mut r)?,
                    _ => {
                        let v = uleb(d, &mut r)?;
                        if t == want {
                            return Some(v);
                        }
                    }
                }
            }
            if sub_end <= q {
                break;
            }
            q = sub_end;
        }
        if len == 0 {
            break;
        }
        p = end;
    }
    None
}

fn sign_extend(v: u32, bits: u32) -> i32 {
    ((v << (32 - bits)) as i32) >> (32 - bits)
}

fn apply_reloc(d: &mut [u8], o: usize, rty: u32, s: u32, t: u32, p: u32) -> Result<(), String> {
    let rd16 = |d: &[u8], o: usize| u16::from_le_bytes([d[o], d[o + 1]]) as u32;
    let wr16 = |d: &mut [u8], o: usize, v: u32| d[o..o + 2].copy_from_slice(&(v as u16).to_le_bytes());
    let rd32 = |d: &[u8], o: usize| u32::from_le_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]);
    match rty {
        0 | 40 => {} // R_ARM_NONE, R_ARM_V4BX
        2 | 38 => {
            // R_ARM_ABS32, R_ARM_TARGET1
            let v = rd32(d, o).wrapping_add(s) | t;
            d[o..o + 4].copy_from_slice(&v.to_le_bytes());
        }
        3 => {
            // R_ARM_REL32
            let v = (rd32(d, o).wrapping_add(s) | t).wrapping_sub(p);
            d[o..o + 4].copy_from_slice(&v.to_le_bytes());
        }
        42 => {
            // R_ARM_PREL31
            let a = sign_extend(rd32(d, o) & 0x7fff_ffff, 31) as u32;
            let v = (a.wrapping_add(s) | t).wrapping_sub(p);
            let w = (rd32(d, o) & 0x8000_0000) | (v & 0x7fff_ffff);
            d[o..o + 4].copy_from_slice(&w.to_le_bytes());
        }
        10 | 30 => {
            // R_ARM_THM_CALL, R_ARM_THM_JUMP24
            let (hw1, hw2) = (rd16(d, o), rd16(d, o + 2));
            let sgn = hw1 >> 10 & 1;
            let (j1, j2) = (hw2 >> 13 & 1, hw2 >> 11 & 1);
            let (i1, i2) = (!(j1 ^ sgn) & 1, !(j2 ^ sgn) & 1);
            let imm = sgn << 24 | i1 << 23 | i2 << 22 | (hw1 & 0x3ff) << 12 | (hw2 & 0x7ff) << 1;
            let a = sign_extend(imm, 25) as u32;
            let v = a.wrapping_add(s).wrapping_sub(p);
            let sv = v as i32;
            if !(-(1 << 24)..(1 << 24)).contains(&sv) {
                return Err("branch relocation out of range".into());
            }
            let sgn = v >> 24 & 1;
            let (i1, i2) = (v >> 23 & 1, v >> 22 & 1);
            let (j1, j2) = (!(i1 ^ sgn) & 1, !(i2 ^ sgn) & 1);
            wr16(d, o, (hw1 & 0xf800) | sgn << 10 | (v >> 12 & 0x3ff));
            wr16(d, o + 2, (hw2 & 0xd000) | j1 << 13 | j2 << 11 | (v >> 1 & 0x7ff));
        }
        102 | 103 => {
            // R_ARM_THM_JUMP11, R_ARM_THM_JUMP8: the 16-bit branches.
            let bits = if rty == 102 { 11 } else { 8 };
            let hw = rd16(d, o);
            let mask = (1u32 << bits) - 1;
            let a = sign_extend((hw & mask) << 1, bits + 1) as u32;
            let v = a.wrapping_add(s).wrapping_sub(p);
            if !(-(1 << bits)..(1 << bits)).contains(&(v as i32)) {
                return Err("short branch relocation out of range".into());
            }
            wr16(d, o, (hw & !mask) | (v >> 1 & mask));
        }
        51 => {
            // R_ARM_THM_JUMP19
            let (hw1, hw2) = (rd16(d, o), rd16(d, o + 2));
            let sgn = hw1 >> 10 & 1;
            let (j1, j2) = (hw2 >> 13 & 1, hw2 >> 11 & 1);
            let imm = sgn << 20 | j2 << 19 | j1 << 18 | (hw1 & 0x3f) << 12 | (hw2 & 0x7ff) << 1;
            let a = sign_extend(imm, 21) as u32;
            let v = a.wrapping_add(s).wrapping_sub(p);
            if !(-(1 << 20)..(1 << 20)).contains(&(v as i32)) {
                return Err("conditional branch relocation out of range".into());
            }
            wr16(d, o, (hw1 & 0xfbc0) | (v >> 20 & 1) << 10 | (v >> 12 & 0x3f));
            wr16(
                d,
                o + 2,
                (hw2 & 0xd000) | (v >> 18 & 1) << 13 | (v >> 19 & 1) << 11 | (v >> 1 & 0x7ff),
            );
        }
        47 | 48 => {
            // R_ARM_THM_MOVW_ABS_NC, R_ARM_THM_MOVT_ABS
            let (hw1, hw2) = (rd16(d, o), rd16(d, o + 2));
            let imm = (hw1 & 0xf) << 12 | (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | (hw2 & 0xff);
            let a = sign_extend(imm, 16) as u32;
            let x = a.wrapping_add(s) | t;
            let v = if rty == 47 { x & 0xffff } else { x >> 16 };
            wr16(d, o, (hw1 & 0xfbf0) | (v >> 11 & 1) << 10 | (v >> 12 & 0xf));
            wr16(d, o + 2, (hw2 & 0x8f00) | (v >> 8 & 7) << 12 | (v & 0xff));
        }
        other => return Err(format!("unsupported relocation type {other}")),
    }
    Ok(())
}

/// What a relocation refers to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RelocTarget {
    Code,
    ReadOnlyData,
    WritableData,
    Undefined,
    Other,
}

/// One relocation of a relocatable object, reduced to what build identification needs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RelocInfo {
    /// ARM ELF relocation type (R_ARM_*).
    pub rtype: u32,
    /// The relocated place is in an executable section.
    pub in_code: bool,
    pub target: RelocTarget,
    /// Name of the symbol referred to (empty for section symbols).
    pub symbol: String,
}

/// ELF metadata collected independently of the loader proper.  Everything here is a
/// *claim* recorded by the toolchain or an incidental property of the file; nothing in
/// the equivalence proof depends on it.
#[derive(Clone, Debug, Default)]
pub struct ElfMeta {
    /// The file is an ELF file (false for raw binaries: all other fields are empty).
    pub present: bool,
    pub relocatable: bool,
    pub e_flags: u32,
    /// Raw contents of `.ARM.attributes`.
    pub attributes: Vec<u8>,
    /// Every section: (name, type, flags, size).
    pub sections: Vec<(String, u32, u32, u32)>,
    pub relocs: Vec<RelocInfo>,
    /// Names of undefined symbols.
    pub undefined: Vec<String>,
    /// Names of the functions a relocatable file defines weakly: the linker may put another
    /// object's definition in their place.
    pub weak_funcs: Vec<String>,
    /// Producer strings found in debug info or `.comment` (`clang version ...`, `GNU C17 ...`).
    pub producers: Vec<String>,
    /// A recorded command line (`.GCC.command.line`, from `-frecord-command-line`).
    pub command_line: Option<String>,
}

impl ElfMeta {
    /// Parse the metadata of a 32-bit little-endian ELF file; never fails (returns what it could read).
    pub fn parse(b: &[u8]) -> ElfMeta {
        let mut m = ElfMeta::default();
        if b.len() < 52 || !b.starts_with(b"\x7fELF") || b[4] != 1 || b[5] != 1 {
            return m;
        }
        m.present = true;
        m.relocatable = u16le(b, 16) == 1;
        m.e_flags = u32le(b, 36);
        let (shoff, shentsize, shnum, shstrndx) = (
            u32le(b, 32) as usize,
            u16le(b, 46) as usize,
            u16le(b, 48) as usize,
            u16le(b, 50) as usize,
        );
        if shoff == 0 || shentsize < 40 || shoff.saturating_add(shnum * shentsize) > b.len() {
            return m;
        }
        // (name offset, type, flags, offset, size, link, info)
        let hdr = |i: usize| {
            let o = shoff + i * shentsize;
            (
                u32le(b, o) as usize,
                u32le(b, o + 4),
                u32le(b, o + 8),
                u32le(b, o + 16) as usize,
                u32le(b, o + 20) as usize,
                u32le(b, o + 24) as usize,
                u32le(b, o + 28) as usize,
            )
        };
        let data = |i: usize| -> &[u8] {
            let h = hdr(i);
            if h.1 == 8 || h.3.saturating_add(h.4) > b.len() {
                &[]
            } else {
                &b[h.3..h.3 + h.4]
            }
        };
        let stroff = if shstrndx < shnum { hdr(shstrndx).3 } else { 0 };
        let names: Vec<String> = (0..shnum).map(|i| cstr(b, stroff + hdr(i).0)).collect();
        for (i, name) in names.iter().enumerate() {
            let h = hdr(i);
            m.sections.push((name.clone(), h.1, h.2, h.4 as u32));
            let d = data(i);
            match names[i].as_str() {
                ".ARM.attributes" => m.attributes = d.to_vec(),
                ".GCC.command.line" => {
                    let parts: Vec<String> = d
                        .split(|&c| c == 0)
                        .filter(|p| !p.is_empty())
                        .map(|p| String::from_utf8_lossy(p).into_owned())
                        .collect();
                    m.command_line = Some(parts.join(" "));
                }
                ".debug_str" | ".debug_info" | ".debug_line_str" | ".comment" => {
                    for pat in [&b"clang version"[..], b"GNU C", b"GNU GIMPLE", b"GCC: "] {
                        let mut from = 0;
                        while let Some(p) = d[from..].windows(pat.len()).position(|w| w == pat) {
                            let at = from + p;
                            // Only at the start of a string (debug_info may embed it after a form byte).
                            if at == 0 || d[at - 1] == 0 || name == ".debug_info" {
                                let s = cstr(d, at);
                                if !m.producers.contains(&s) {
                                    m.producers.push(s);
                                }
                            }
                            from = at + pat.len();
                        }
                    }
                }
                _ => {}
            }
        }
        // Symbols and relocations.
        let Some(symtab) = (0..shnum).find(|&i| hdr(i).1 == 2) else {
            return m;
        };
        let st = data(symtab);
        let sym_str = hdr(hdr(symtab).5.min(shnum - 1)).3;
        // (name, section index, type)
        let syms: Vec<(String, usize, u8)> = (0..st.len() / 16)
            .map(|i| {
                let o = i * 16;
                (
                    cstr(b, sym_str + u32le(st, o) as usize),
                    u16le(st, o + 14) as usize,
                    st[o + 12] & 0xf,
                )
            })
            .collect();
        for (i, (name, shndx, ty)) in syms.iter().enumerate() {
            if i != 0 && *shndx == 0 && *ty != 3 && !name.is_empty() {
                m.undefined.push(name.clone());
            }
            if m.relocatable && *shndx != 0 && *ty == 2 && st[i * 16 + 12] >> 4 == 2 {
                m.weak_funcs.push(name.clone());
            }
        }
        if !m.relocatable {
            return m;
        }
        for i in 0..shnum {
            let h = hdr(i);
            if h.1 != 9 || h.6 >= shnum || hdr(h.6).2 & SHF_ALLOC == 0 {
                continue;
            }
            let in_code = hdr(h.6).2 & SHF_EXEC != 0;
            let d = data(i);
            for r in 0..d.len() / 8 {
                let info = u32le(d, r * 8 + 4);
                let Some((name, shndx, _)) = syms.get((info >> 8) as usize) else {
                    continue;
                };
                let target = if *shndx == 0 {
                    RelocTarget::Undefined
                } else if *shndx >= shnum {
                    RelocTarget::Other
                } else {
                    let f = hdr(*shndx).2;
                    if f & SHF_EXEC != 0 {
                        RelocTarget::Code
                    } else if f & SHF_WRITE != 0 {
                        RelocTarget::WritableData
                    } else if f & SHF_ALLOC != 0 {
                        RelocTarget::ReadOnlyData
                    } else {
                        RelocTarget::Other
                    }
                };
                m.relocs.push(RelocInfo {
                    rtype: info & 0xff,
                    in_code,
                    target,
                    symbol: name.clone(),
                });
            }
        }
        m
    }
}