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
//! Firmware images that are not ELF files: raw binaries, Intel HEX and Motorola S-record
//! files, described by a symbol table (`nm` output in any of its formats) and/or a GNU ld
//! link map.

use crate::image::{Image, Segment, SymKind, Symbol};
use std::collections::BTreeMap;

/// What a file given as the binary looks like.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
    Elf,
    IntelHex,
    Srec,
    Raw,
}

pub fn sniff(bytes: &[u8]) -> Format {
    if Image::is_elf(bytes) {
        return Format::Elf;
    }
    let text = |ok: fn(&[u8]) -> bool| {
        let mut lines = bytes
            .split(|&c| c == b'\n')
            .map(|l| l.trim_ascii())
            .filter(|l| !l.is_empty());
        let mut n = 0;
        lines.all(|l| {
            n += 1;
            ok(l)
        }) && n > 0
    };
    if text(|l| l[0] == b':' && l.len() >= 11 && l[1..].iter().all(u8::is_ascii_hexdigit)) {
        Format::IntelHex
    } else if text(|l| l[0] == b'S' && l.len() >= 10 && l[1..].iter().all(u8::is_ascii_hexdigit)) {
        Format::Srec
    } else {
        Format::Raw
    }
}

fn hex_bytes(s: &str) -> Option<Vec<u8>> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    (0..s.len() / 2)
        .map(|i| u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok())
        .collect()
}

/// Collects bytes at arbitrary addresses into maximal contiguous regions.
#[derive(Default)]
struct Regions(BTreeMap<u32, u8>);

impl Regions {
    /// A file that gives one address two different values describes no definite image (which
    /// one ends up in memory depends on the programming tool): refuse it.
    fn put(&mut self, addr: u32, data: &[u8]) -> Result<(), String> {
        for (i, &b) in data.iter().enumerate() {
            let a = addr.wrapping_add(i as u32);
            if self.0.insert(a, b).is_some_and(|old| old != b) {
                return Err(format!("address {a:#x} is given two different values"));
            }
        }
        Ok(())
    }

    fn finish(self) -> Vec<(u32, Vec<u8>)> {
        let mut out: Vec<(u32, Vec<u8>)> = Vec::new();
        for (a, b) in self.0 {
            match out.last_mut() {
                Some((start, d)) if start.wrapping_add(d.len() as u32) == a => d.push(b),
                _ => out.push((a, vec![b])),
            }
        }
        out
    }
}

/// Intel HEX: data records with extended segment / linear address records.
pub fn parse_ihex(text: &str) -> Result<Vec<(u32, Vec<u8>)>, String> {
    let mut regions = Regions::default();
    let mut upper = 0u32;
    for (ln, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let bad = |why: &str| format!("Intel HEX line {}: {why}", ln + 1);
        let rec = line
            .strip_prefix(':')
            .and_then(hex_bytes)
            .ok_or_else(|| bad("not a record"))?;
        if rec.len() < 5 || rec.len() != rec[0] as usize + 5 {
            return Err(bad("wrong length"));
        }
        if rec.iter().fold(0u8, |a, b| a.wrapping_add(*b)) != 0 {
            return Err(bad("bad checksum"));
        }
        let off = (rec[1] as u32) << 8 | rec[2] as u32;
        let data = &rec[4..rec.len() - 1];
        match rec[3] {
            0 => regions.put(upper.wrapping_add(off), data).map_err(|e| bad(&e))?,
            1 => break,
            2 if data.len() == 2 => upper = ((data[0] as u32) << 8 | data[1] as u32) << 4,
            4 if data.len() == 2 => upper = ((data[0] as u32) << 8 | data[1] as u32) << 16,
            3 | 5 => {} // start addresses
            _ => return Err(bad("unknown record type")),
        }
    }
    Ok(regions.finish())
}

/// Motorola S-records: S1/S2/S3 data records.
pub fn parse_srec(text: &str) -> Result<Vec<(u32, Vec<u8>)>, String> {
    let mut regions = Regions::default();
    for (ln, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let bad = |why: &str| format!("S-record line {}: {why}", ln + 1);
        let kind = line.as_bytes().get(1).copied().ok_or_else(|| bad("not a record"))?;
        let rec = line.get(2..).and_then(hex_bytes).ok_or_else(|| bad("not a record"))?;
        if !line.starts_with('S') || rec.is_empty() || rec.len() != rec[0] as usize + 1 {
            return Err(bad("wrong length"));
        }
        if rec.iter().fold(0u8, |a, b| a.wrapping_add(*b)) != 0xff {
            return Err(bad("bad checksum"));
        }
        let alen = match kind {
            b'1' => 2,
            b'2' => 3,
            b'3' => 4,
            _ => continue, // header, counts, start addresses
        };
        if rec.len() < alen + 2 {
            return Err(bad("wrong length"));
        }
        let addr = rec[1..1 + alen].iter().fold(0u32, |a, b| a << 8 | *b as u32);
        regions.put(addr, &rec[1 + alen..rec.len() - 1])?;
    }
    Ok(regions.finish())
}

/// The memory regions a non-ELF input file provides; a raw binary is placed at `base`.
pub fn regions_of(bytes: &[u8], base: u32) -> Result<Vec<(u32, Vec<u8>)>, String> {
    match sniff(bytes) {
        Format::IntelHex => parse_ihex(&String::from_utf8_lossy(bytes)),
        Format::Srec => parse_srec(&String::from_utf8_lossy(bytes)),
        _ => Ok(vec![(base, bytes.to_vec())]),
    }
}

/// How the bytes of an input section are used.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Class {
    Code,
    Rodata,
    Data,
    Bss,
}

/// One input section placed by the linker (a line of the link map).
#[derive(Clone, Debug)]
pub struct Contribution {
    pub addr: u32,
    pub size: u32,
    pub class: Class,
    /// Object file, `archive(member)` for library members; empty for linker fill.
    pub object: String,
    /// Output section it was placed in.
    pub section: String,
    /// Name of the input section.
    pub input: String,
}

/// Everything known about the layout of an image from text files.
#[derive(Default, Debug)]
pub struct SymInfo {
    pub symbols: Vec<Symbol>,
    /// From a link map: memory regions (name, origin, length, attributes).
    pub memory: Vec<(String, u32, u32, String)>,
    /// From a link map: output sections (name, address, size, load address).
    pub sections: Vec<(String, u32, u32, Option<u32>)>,
    pub contributions: Vec<Contribution>,
}

impl SymInfo {
    pub fn merge(&mut self, other: SymInfo) {
        for s in other.symbols {
            match self.symbols.iter_mut().find(|t| {
                t.name == s.name && t.addr == s.addr && (t.kind == SymKind::Func) == (s.kind == SymKind::Func)
            }) {
                Some(t) => {
                    if t.size == 0 {
                        t.size = s.size;
                    }
                    if t.file.is_none() {
                        t.file = s.file;
                    }
                }
                None => self.symbols.push(s),
            }
        }
        self.memory.extend(other.memory);
        self.sections.extend(other.sections);
        self.contributions.extend(other.contributions);
    }
}

fn hex(s: &str) -> Option<u32> {
    let s = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")).unwrap_or(s);
    if s.is_empty() || s.len() > 16 {
        return None;
    }
    u64::from_str_radix(s, 16).ok().map(|v| v as u32)
}

fn nm_kind(c: char) -> Option<SymKind> {
    Some(match c.to_ascii_lowercase() {
        't' | 'w' | 'i' => SymKind::Func,
        'd' | 'b' | 'r' | 'c' | 'g' | 's' | 'v' => SymKind::Object,
        'u' => return None,
        _ => SymKind::Other,
    })
}

/// A symbol table as text: `nm` output (BSD, POSIX `-P` or System V `-f sysv` format, with or
/// without sizes, with or without `-A`/`-l` decorations) or a GNU ld link map.
pub fn parse_symbols(text: &str) -> Result<SymInfo, String> {
    if text.contains("Linker script and memory map") || text.contains("Memory Configuration") {
        return Ok(parse_map(text));
    }
    let mut info = SymInfo::default();
    for (ln, raw) in text.lines().enumerate() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let bad = || format!("symbol table line {}: expected 'address [size] type name'", ln + 1);
        let (name, class, addr, size);
        if line.contains('|') {
            // System V: Name |Value |Class |Type |Size |Line |Section
            let f: Vec<&str> = line.split('|').map(str::trim).collect();
            if f.len() < 5 || f[0] == "Name" {
                continue;
            }
            let Some(a) = hex(f[1]) else { continue }; // undefined
            (name, class, addr) = (f[0], f[2].chars().next().unwrap_or('?'), a);
            size = hex(f[4]).unwrap_or(0);
        } else {
            let f: Vec<&str> = line.split_whitespace().collect();
            if f.len() < 2
                || line.ends_with(':')
                || line.starts_with("Symbols from")
                || (f[0] == "Name" && f[1] == "Value")
            {
                continue; // headings of multi-file listings
            }
            let one = |s: &str| s.len() == 1 && s.chars().all(|c| c.is_ascii_alphabetic() || c == '?' || c == '-');
            if one(f[0]) {
                continue; // BSD line of an undefined symbol: "U name"
            }
            if hex(f[0]).is_some() && f.len() >= 3 && (one(f[1]) || (hex(f[1]).is_some() && f.len() >= 4 && one(f[2])))
            {
                // BSD: address [size] type name
                let sized = !one(f[1]);
                addr = hex(f[0]).unwrap();
                size = if sized { hex(f[1]).unwrap() } else { 0 };
                class = f[1 + sized as usize].chars().next().unwrap();
                name = f[2 + sized as usize];
            } else if one(f[1]) {
                // POSIX: name type [value [size]]
                let Some(a) = f.get(2).and_then(|v| hex(v)) else {
                    continue;
                };
                (name, class, addr) = (f[0], f[1].chars().next().unwrap(), a);
                size = f.get(3).and_then(|v| hex(v)).unwrap_or(0);
            } else {
                return Err(bad());
            }
        }
        // `nm -A` prefixes the file name.
        let name = name.rsplit(':').next().unwrap_or(name);
        if name.is_empty() || name.starts_with('$') {
            continue;
        }
        let Some(kind) = nm_kind(class) else { continue };
        info.symbols.push(Symbol {
            name: name.to_string(),
            addr: addr & !((kind == SymKind::Func) as u32),
            size,
            kind: if class.eq_ignore_ascii_case(&'a') {
                SymKind::Other
            } else {
                kind
            },
            global: class.is_ascii_uppercase(),
            file: None,
        });
    }
    Ok(info)
}

fn class_of(input: &str) -> Class {
    let is = |p: &str| input == p || input.starts_with(&format!("{p}."));
    if is(".text")
        || is(".init")
        || is(".fini")
        || input.starts_with(".glue")
        || input.ends_with("_veneer")
        || is(".iplt")
    {
        Class::Code
    } else if is(".bss") || input == "COMMON" || is(".noinit") || is(".sbss") {
        Class::Bss
    } else if is(".data") || is(".sdata") || is(".ramfunc") || is(".fastcode") {
        Class::Data
    } else {
        Class::Rodata
    }
}

/// The name a compiler gives the section of one function or object (`-ffunction-sections`,
/// `-fdata-sections`): `.text.name`, `.rodata.name`, `.data.name`, `.bss.name`.
fn section_symbol(input: &str) -> Option<&str> {
    for p in [".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss."] {
        if let Some(rest) = input.strip_prefix(p) {
            let rest = ["unlikely.", "startup.", "exit.", "hot.", "cold."]
                .iter()
                .find_map(|q| rest.strip_prefix(q))
                .unwrap_or(rest);
            // String and constant pools are not objects of the program.
            let pool = rest.starts_with("str") || rest.starts_with("cst") || rest.contains(".str");
            return (!rest.is_empty() && !pool).then_some(rest);
        }
    }
    None
}

/// A GNU ld link map (`-Map`): memory regions, output sections with their load addresses,
/// the contribution of every object file, and the global symbols.  With `-ffunction-sections`
/// and `-fdata-sections` the input section names also reveal static functions and objects.
pub fn parse_map(text: &str) -> SymInfo {
    let mut info = SymInfo::default();
    let mut lines = text.lines().peekable();
    // Memory configuration.
    for line in lines.by_ref() {
        if line.starts_with("Linker script and memory map") {
            break;
        }
        let f: Vec<&str> = line.split_whitespace().collect();
        if f.len() >= 3
            && f[1].starts_with("0x")
            && f[2].starts_with("0x")
            && f[0] != "*default*"
            && let (Some(o), Some(l)) = (hex(f[1]), hex(f[2]))
        {
            info.memory
                .push((f[0].to_string(), o, l, f.get(3).unwrap_or(&"").to_string()));
        }
    }
    let mut section = String::new();
    // The contribution the following symbol lines belong to: (index, input section name).
    let mut current: Option<(usize, String)> = None;
    let mut pending: Option<(bool, String)> = None; // a name on a line of its own: (is output section, name)
    for line in lines {
        if line.starts_with("OUTPUT(") || line.starts_with("Cross Reference Table") {
            break;
        }
        if line.trim().is_empty() {
            continue;
        }
        let indent = line.len() - line.trim_start().len();
        let f: Vec<&str> = line.split_whitespace().collect();
        // Split "name addr size rest" / "addr size rest" / "addr symbol".
        let (name, rest): (Option<&str>, &[&str]) = if f[0].starts_with("0x") {
            (None, &f[..])
        } else {
            (Some(f[0]), &f[1..])
        };
        let addr = rest.first().filter(|a| a.starts_with("0x")).and_then(|a| hex(a));
        let size = rest.get(1).filter(|a| a.starts_with("0x")).and_then(|a| hex(a));
        let (is_out, name) = match (name, pending.take()) {
            (Some(n), _) => (indent == 0, n.to_string()),
            (None, Some(p)) => p,
            (None, None) => (false, String::new()),
        };
        if (name.starts_with('*') && name != "*fill*")
            || name.contains('(')
            || name.starts_with("LOAD")
            || name.starts_with("START")
            || name.starts_with("END")
        {
            continue;
        }
        match (addr, size) {
            (None, _) => {
                if !name.is_empty() && f.len() == 1 {
                    pending = Some((indent == 0, name));
                }
            }
            (Some(a), Some(sz)) if !name.is_empty() => {
                if is_out {
                    let load = rest
                        .windows(3)
                        .find(|w| w[0] == "load" && w[1] == "address")
                        .and_then(|w| hex(w[2]));
                    section = name.clone();
                    info.sections.push((name, a, sz, load));
                    current = None;
                } else {
                    let object = rest[2..].join(" ");
                    let fill = name == "*fill*";
                    if sz > 0 {
                        info.contributions.push(Contribution {
                            addr: a,
                            size: sz,
                            class: if fill {
                                info.contributions.last().map_or(Class::Rodata, |c| c.class)
                            } else {
                                class_of(&name)
                            },
                            object: if fill { String::new() } else { object },
                            section: section.clone(),
                            input: name.clone(),
                        });
                        current = (!fill).then(|| (info.contributions.len() - 1, name));
                    } else {
                        current = None;
                    }
                }
            }
            (Some(a), _) => {
                // "address symbol" or "address symbol = expression".
                let Some(sym) = rest.get(1) else { continue };
                if sym.starts_with('.') && rest.get(2) == Some(&"=") || *sym == "." || sym.contains('(') {
                    continue;
                }
                let assigned = rest.get(2) == Some(&"=") || name == "PROVIDE";
                let (kind, file) = match &current {
                    Some((i, _)) if !assigned => {
                        let c = &info.contributions[*i];
                        (
                            if c.class == Class::Code {
                                SymKind::Func
                            } else {
                                SymKind::Object
                            },
                            Some(c.object.clone()),
                        )
                    }
                    _ => (SymKind::Other, None),
                };
                info.symbols.push(Symbol {
                    name: sym.trim_start_matches("PROVIDE(").to_string(),
                    addr: a & !((kind == SymKind::Func) as u32),
                    size: 0,
                    kind,
                    global: true,
                    file,
                });
            }
        }
    }
    // Sizes of the listed symbols: up to the next symbol of the same contribution, or its end.
    // Contributions without any listed symbol hold static functions and objects; their names
    // come from the section name when there is one section per function or object.
    let mut extra = Vec::new();
    for c in info.contributions.iter().filter(|c| !c.object.is_empty()) {
        let (start, end) = (c.addr, c.addr + c.size);
        let mut inside: Vec<usize> = (0..info.symbols.len())
            .filter(|&i| {
                let s = &info.symbols[i];
                s.kind != SymKind::Other && s.addr >= start && s.addr < end && s.file.as_deref() == Some(&c.object)
            })
            .collect();
        inside.sort_by_key(|&i| info.symbols[i].addr);
        for (k, &i) in inside.iter().enumerate() {
            let a = info.symbols[i].addr;
            let next = inside[k + 1..]
                .iter()
                .map(|&j| info.symbols[j].addr)
                .find(|&n| n > a)
                .unwrap_or(end);
            info.symbols[i].size = next - a;
        }
        if inside.is_empty()
            && let Some(name) = section_symbol(&c.input)
        {
            extra.push(Symbol {
                name: name.to_string(),
                addr: c.addr,
                size: c.size,
                kind: if c.class == Class::Code {
                    SymKind::Func
                } else {
                    SymKind::Object
                },
                global: false,
                file: Some(c.object.clone()),
            });
        }
    }
    info.symbols.extend(extra);
    info
}

fn span_in(regions: &[(u32, Vec<u8>)], addr: u32, len: u32) -> Option<&[u8]> {
    regions.iter().find_map(|(base, d)| {
        let o = addr.checked_sub(*base)? as usize;
        d.get(o..o.checked_add(len as usize)?)
    })
}

/// Pairs of linker-script symbols that conventionally delimit initialised data: its load
/// address in flash, and its start and end in RAM.
const DATA_SYMBOLS: &[(&str, &str, &str)] = &[
    ("_sidata", "_sdata", "_edata"),
    ("__data_load_start", "__data_start", "__data_end"),
    ("__data_load__", "__data_start__", "__data_end__"),
    ("__etext", "__data_start__", "__data_end__"),
    ("_etext", "_data", "_edata"),
    ("_etext", "_sdata", "_edata"),
    ("__data_lma", "__data_start", "__data_end"),
    ("_data_loadaddr", "_data", "_edata"),
];
const BSS_SYMBOLS: &[(&str, &str)] = &[
    ("_sbss", "_ebss"),
    ("__bss_start__", "__bss_end__"),
    ("__bss_start", "__bss_end"),
    ("_bss", "_ebss"),
    ("__bss_start", "_end"),
];

/// Build an image from memory contents and the layout information of a symbol table / map.
pub fn build_image(regions: Vec<(u32, Vec<u8>)>, info: &SymInfo) -> Result<Image, String> {
    let mut img = Image::default();
    let sym = |name: &str| info.symbols.iter().find(|s| s.name == name).map(|s| s.addr);
    // Ranges of the input files that are accounted for by a segment.
    let mut used: Vec<(u32, u32)> = Vec::new();
    if !info.contributions.is_empty() {
        // A link map: one segment per run of contributions of the same kind in an output section.
        let load_of = |section: &str, addr: u32| -> Option<u32> {
            let s = info
                .sections
                .iter()
                .find(|s| s.0 == section && addr >= s.1 && addr - s.1 <= s.2)?;
            Some(s.3? + (addr - s.1))
        };
        let mut cs: Vec<&Contribution> = info.contributions.iter().collect();
        cs.sort_by_key(|c| c.addr);
        let mut run: Option<(String, u32, u32, Class)> = None; // (section, start, end, class)
        let mut runs = Vec::new();
        for c in cs {
            let name = c.section.clone();
            match &mut run {
                Some(r) if r.0 == name && r.2 == c.addr && r.3 == c.class => r.2 = c.addr + c.size,
                _ => {
                    runs.extend(run.take());
                    run = Some((name, c.addr, c.addr + c.size, c.class));
                }
            }
            if !c.object.is_empty() {
                img.owners.push((c.addr, c.object.clone()));
            }
        }
        runs.extend(run);
        for (name, start, end, class) in runs {
            let len = end - start;
            // Zero-initialised memory has no image in the files, whatever load address the map
            // prints for it: bytes found there are something else and stay unexplained.
            let load = if class == Class::Bss {
                None
            } else {
                load_of(&name, start)
            };
            let from = load.unwrap_or(start);
            let writable = matches!(class, Class::Data | Class::Bss);
            let data = match span_in(&regions, from, len).filter(|_| class != Class::Bss) {
                Some(d) => {
                    used.push((from, from + len));
                    d.to_vec()
                }
                None if class == Class::Bss => vec![0; len as usize],
                None => continue, // not part of the files given
            };
            img.segments.push(Segment {
                name,
                addr: start,
                data,
                writable,
                exec: class == Class::Code,
                load_addr: load.filter(|&l| l != start),
            });
        }
    } else {
        // Only symbols: initialised data is located through the linker-script symbols that
        // startup code uses to copy it, the rest is split by the kind of the symbols.
        for &(lma, start, end) in DATA_SYMBOLS {
            if let (Some(l), Some(s), Some(e)) = (sym(lma), sym(start), sym(end))
                && e > s
                && l != s
                && span_in(&regions, s, 1).is_none()
                && let Some(d) = span_in(&regions, l, e - s)
            {
                used.push((l, l + (e - s)));
                img.segments.push(Segment {
                    name: ".data".into(),
                    addr: s,
                    data: d.to_vec(),
                    writable: true,
                    exec: false,
                    load_addr: Some(l),
                });
                break;
            }
        }
        for &(start, end) in BSS_SYMBOLS {
            if let (Some(s), Some(e)) = (sym(start), sym(end))
                && e > s
                && e - s <= 1 << 24
                && span_in(&regions, s, 1).is_none()
                && img
                    .segments
                    .iter()
                    .all(|g| s >= g.addr + g.data.len() as u32 || e <= g.addr)
            {
                img.segments.push(Segment {
                    name: ".bss".into(),
                    addr: s,
                    data: vec![0; (e - s) as usize],
                    writable: true,
                    exec: false,
                    load_addr: None,
                });
                break;
            }
        }
    }
    // What the symbols and the map do not describe: cut the remaining bytes at symbol
    // boundaries.  Bytes of a function are code; bytes of an object are data; bytes before the
    // first symbol, and bytes nothing describes inside a map, count as unexplained code.
    used.sort();
    for (base, data) in &regions {
        let end = base + data.len() as u32;
        let mut cuts: Vec<(u32, Option<bool>, u32)> = info
            .symbols
            .iter()
            .filter(|s| s.kind != SymKind::Other && s.addr >= *base && s.addr < end)
            .map(|s| (s.addr, Some(s.kind == SymKind::Func), s.size))
            .collect();
        cuts.sort();
        let mut pieces: Vec<(u32, u32, bool)> = Vec::new(); // (start, end, exec)
        let push = |pieces: &mut Vec<(u32, u32, bool)>, a: u32, b: u32, exec: bool| {
            if a >= b {
                return;
            }
            match pieces.last_mut() {
                Some(p) if p.1 == a && p.2 == exec => p.1 = b,
                _ => pieces.push((a, b, exec)),
            }
        };
        let mut at = *base;
        for (i, &(a, is_func, size)) in cuts.iter().enumerate() {
            let a = a.max(at);
            // Before the first symbol: nothing says what it is.
            let unexplained = i == 0 || pieces.last().is_some_and(|p| p.2);
            push(&mut pieces, at, a, unexplained);
            let next = cuts.get(i + 1).map_or(end, |c| c.0).max(a);
            let body_end = if size > 0 { (a + size).min(next) } else { next };
            let exec = is_func == Some(true);
            push(&mut pieces, a, body_end, exec);
            // After a symbol of known size: a short gap is padding or a literal pool of the
            // same kind, a long one is anonymous read-only data (string literals, tables).
            push(&mut pieces, body_end, next, exec && next - body_end <= 16);
            at = next;
        }
        if cuts.is_empty() {
            push(&mut pieces, at, end, true);
        }
        for (a, b, exec) in pieces {
            // Remove what a segment already covers.
            let mut start = a;
            let mut parts = Vec::new();
            for &(u0, u1) in used.iter().filter(|u| u.1 > a && u.0 < b) {
                if u0 > start {
                    parts.push((start, u0));
                }
                start = start.max(u1);
            }
            if start < b {
                parts.push((start, b));
            }
            for (a, b) in parts {
                let d = &data[(a - base) as usize..(b - base) as usize];
                // Erased or zero fill between sections of a flash dump describes nothing.
                if !info.contributions.is_empty() && d.iter().all(|&x| x == 0xff || x == 0) {
                    continue;
                }
                if img
                    .segments
                    .iter()
                    .any(|g| a < g.addr + g.data.len() as u32 && g.addr < b)
                {
                    continue;
                }
                img.segments.push(Segment {
                    name: if info.contributions.is_empty() {
                        "raw".into()
                    } else {
                        "unmapped".into()
                    },
                    addr: a,
                    data: d.to_vec(),
                    writable: false,
                    exec: exec || !info.contributions.is_empty(),
                    load_addr: None,
                });
            }
        }
    }
    img.segments.sort_by_key(|s| s.addr);
    img.symbols = info.symbols.clone();
    img.soft_bounds = info.contributions.is_empty();
    img.finish();
    Ok(img)
}

/// Load the binary side from the files given on the command line.
///
/// `binary` is an ELF file, an Intel HEX or S-record file, or a raw binary placed at `base`.
/// `extra` are further memory images (`--load file@addr`; the address is ignored for formats
/// that carry their own).  `symtabs` are symbol tables and/or link maps; an ELF file needs
/// none, but a map adds the object file each byte comes from.
pub fn load(
    binary: &[u8],
    base: u32,
    extra: &[(Vec<u8>, u32)],
    symtabs: &[String],
    static_base: Option<u32>,
) -> Result<Image, String> {
    let mut info = SymInfo::default();
    for t in symtabs {
        info.merge(parse_symbols(t)?);
    }
    let mut image = if sniff(binary) == Format::Elf {
        if !extra.is_empty() {
            return Err("--load cannot be combined with an ELF file".into());
        }
        let mut image = Image::from_elf(binary)?;
        if !info.contributions.is_empty() {
            image.owners = info
                .contributions
                .iter()
                .filter(|c| !c.object.is_empty())
                .map(|c| (c.addr, c.object.clone()))
                .collect();
            image.owners.sort();
        }
        image
    } else {
        if symtabs.is_empty() {
            return Err("not an ELF file: a raw binary, HEX or S-record image needs --symbols".into());
        }
        let mut regions = regions_of(binary, base)?;
        for (bytes, addr) in extra {
            regions.extend(regions_of(bytes, *addr)?);
        }
        regions.sort_by_key(|r| r.0);
        for w in regions.windows(2) {
            if w[0].0 + w[0].1.len() as u32 > w[1].0 {
                return Err(format!("memory images overlap at {:#x}", w[1].0));
            }
        }
        build_image(regions, &info)?
    };
    if static_base.is_some() {
        image.static_base = static_base;
    }
    if image.rwpi && image.static_base.is_none() && !image.segments.is_empty() && image.needs_static_base {
        return Err(
            "this image was built with read-write position independence (-frwpi): its data is addressed \
             relative to r9, whose value is not recorded in the file; give it with --static-base <hex> \
             (or link with --emit-relocs so that it can be inferred)"
                .into(),
        );
    }
    Ok(image)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nm_formats() {
        let bsd =
            "08000018 T app_step\n08000068 0000003c T main\n         U ext\n20000000 d counter\n080003cc A _sidata\n";
        let i = parse_symbols(bsd).unwrap();
        assert_eq!(i.symbols.len(), 4);
        assert_eq!(
            (i.symbols[1].name.as_str(), i.symbols[1].addr, i.symbols[1].size),
            ("main", 0x0800_0068, 0x3c)
        );
        assert_eq!(i.symbols[3].kind, SymKind::Other);
        let posix = "app_step T 08000019 00000050\nmain T 08000068 3c\next U\ncounter d 20000000\n";
        let i = parse_symbols(posix).unwrap();
        assert_eq!(i.symbols.len(), 3);
        assert_eq!((i.symbols[0].addr, i.symbols[0].size), (0x0800_0018, 0x50));
        let sysv = "\n\nSymbols from fw.elf:\n\nName                  Value   Class        Type         Size     Line  Section\n\napp_step            |08000019|   T  |              FUNC|00000050|     |.text\next                 |        |   U  |            NOTYPE|        |     |*UND*\ncounter             |20000000|   d  |            OBJECT|00000004|     |.data\n";
        let i = parse_symbols(sysv).unwrap();
        assert_eq!(i.symbols.len(), 2);
        assert_eq!(
            (i.symbols[0].addr, i.symbols[0].size, i.symbols[0].kind),
            (0x0800_0018, 0x50, SymKind::Func)
        );
        assert!(parse_symbols("what is this\n").is_err());
    }

    #[test]
    fn hex_and_srec() {
        let ihex = ":020000040800F2\n:0400000001020304F2\n:040004000A0B0C0DCA\n:00000001FF\n";
        assert_eq!(sniff(ihex.as_bytes()), Format::IntelHex);
        assert_eq!(
            parse_ihex(ihex).unwrap(),
            vec![(0x0800_0000, vec![1, 2, 3, 4, 10, 11, 12, 13])]
        );
        assert!(parse_ihex(":0400000001020304F3\n").is_err());
        let srec = "S00600004844521B\nS3090800000001020304E4\nS70508000001F1\n";
        assert_eq!(sniff(srec.as_bytes()), Format::Srec);
        assert_eq!(parse_srec(srec).unwrap(), vec![(0x0800_0000, vec![1, 2, 3, 4])]);
        assert_eq!(sniff(&[0x00, 0x20, 0x00, 0x20, 0x21, 0x01]), Format::Raw);
    }
}