cverif 0.0.0

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
//! 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,
}

#[derive(Clone, Debug)]
pub struct Segment {
    pub name: String,
    pub addr: u32,
    pub data: Vec<u8>,
    pub writable: bool,
    pub exec: bool,
}

#[derive(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>,
}

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()
}

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;
                }
            }
        }
        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,
                });
            }
            let raw = || &bytes[s.offset..s.offset + s.size];
            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));
                }
            }
        }
        // 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();
            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;
                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 != 0 && shndx < shnum {
                    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,
                        });
                    }
                }
                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 data = &mut img.segments[seg].data;
                    let o = off as usize;
                    if o + 4 > data.len() {
                        return Err("relocation outside its section".into());
                    }
                    apply_reloc(data, o, rty, s_addr, t, p).map_err(|e| format!("{e} (symbol {})", rs.name))?;
                }
            }
        }
        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 mut img = Image::default();
        img.segments.push(Segment {
            name: "raw".into(),
            addr: base,
            data: bytes.to_vec(),
            writable: false,
            exec: true,
        });
        for (ln, line) in symtab.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let f: Vec<&str> = line.split_whitespace().collect();
            let bad = || format!("symbol table line {}: expected 'address [size] type name'", ln + 1);
            let (addr, size, ty, name) = match f.len() {
                3 => (f[0], None, f[1], f[2]),
                4 => (f[0], Some(f[1]), f[2], f[3]),
                _ => return Err(bad()),
            };
            let addr = u32::from_str_radix(addr.trim_start_matches("0x"), 16).map_err(|_| bad())?;
            let size = match size {
                Some(s) => u32::from_str_radix(s.trim_start_matches("0x"), 16).map_err(|_| bad())?,
                None => 0,
            };
            let c = ty.chars().next().unwrap_or('?');
            if name.starts_with('$') {
                continue;
            }
            let kind = match c.to_ascii_lowercase() {
                't' | 'w' => SymKind::Func,
                'd' | 'b' | 'r' | 'c' | 'g' | 's' => SymKind::Object,
                'u' => continue,
                _ => SymKind::Other,
            };
            img.symbols.push(Symbol {
                name: name.to_string(),
                addr: addr & !((kind == SymKind::Func) as u32),
                size,
                kind,
                global: c.is_ascii_uppercase(),
            });
        }
        img.finish();
        Ok(img)
    }

    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();
    }

    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)
    }

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

    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)
    }
}

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));
        }
        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));
        }
        102 => {
            // R_ARM_THM_JUMP11
            let hw = rd16(d, o);
            let a = sign_extend((hw & 0x7ff) << 1, 12) as u32;
            let v = a.wrapping_add(s).wrapping_sub(p);
            if !(-(1 << 11)..(1 << 11)).contains(&(v as i32)) {
                return Err("short branch relocation out of range".into());
            }
            wr16(d, o, (hw & 0xf800) | (v >> 1 & 0x7ff));
        }
        other => return Err(format!("unsupported relocation type {other}")),
    }
    Ok(())
}