cverif 0.0.2

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
//! Shared symbolic-execution context: path condition, branching through the
//! prover, deterministic path replay and the memory model used by both the C
//! and the machine-code executors.

use crate::bv::{Prover, Verdict};
use crate::term::{Env, T, Terms};
use std::collections::{HashMap, HashSet};

/// Why a path stopped before producing a comparable result.
#[derive(Debug, Clone)]
pub enum Stop {
    /// Exploration limit reached; the path (and its subtree) is not verified.
    Truncated(String),
    /// A construct the tool does not model.
    Unsupported(String),
    /// The two sides provably differ; the environment is a concrete witness.
    Mismatch(String, Option<Box<Env>>),
    /// The prover could not decide an equality.
    Inconclusive(String),
    /// The C program has undefined behaviour on every input of this path.
    Undefined,
    /// The C program stopped by calling a function that does not return.
    Halt,
}

pub type R<V> = Result<V, Stop>;

#[derive(Clone, Debug)]
pub struct Write {
    pub addr: T,
    /// Size in bytes.
    pub size: u8,
    pub val: T,
    /// For a store through a pointer of unknown target recorded in a private log: the exposed
    /// object (base, size) it lands in, if it lands in private memory at all.
    pub guard: Option<(T, u32)>,
}

/// A private object whose address is known to the outside world (it was passed to an external
/// function): pointers obtained after `since` may point into it.
#[derive(Clone, Debug)]
pub struct Exposed {
    pub base: T,
    pub size: u32,
    /// First world-memory snapshot in which the address may be found.
    pub since: u32,
}

/// Memory of one side: a write log for "world" memory (anything reachable by the
/// caller) and one per private object (stack frame, C locals).
#[derive(Clone, Debug, Default)]
pub struct Mem {
    pub world: Vec<Write>,
    pub private: HashMap<T, Vec<Write>>,
    /// Snapshot id of world memory; bumped by every external call.
    pub epoch: u32,
    /// Private objects that pointers of unknown origin may point into.
    pub exposed: Vec<Exposed>,
}

/// Snapshot id used for never-written private memory (uninitialised locals, stack).
pub const UNINIT_EPOCH: u32 = 0x8000_0000;

#[derive(Clone, Copy, Debug)]
pub struct Limits {
    /// Maximum number of undetermined branches on one path.
    pub max_depth: usize,
    /// Maximum number of paths per function.
    pub max_paths: usize,
    /// Maximum number of executed C blocks / instructions per path.
    pub max_steps: u64,
    pub max_call_depth: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            max_depth: 40,
            max_paths: 2000,
            max_steps: 20_000,
            max_call_depth: 48,
        }
    }
}

pub struct Ctx {
    pub tm: Terms,
    pub prover: Prover,
    /// Path condition: preconditions and branch decisions.
    pub pc: Vec<T>,
    /// Conditions under which the C program has defined behaviour on this path.
    pub ub: Vec<T>,
    pub decisions: Vec<bool>,
    pub pos: usize,
    pub steps: u64,
    pub limits: Limits,
    /// Base addresses of private objects.
    pub private_bases: HashSet<T>,
    /// Wall-clock deadline for the current function.
    pub deadline: Option<std::time::Instant>,
    /// Budget in deterministic work units (see `work`), so that results do not depend on
    /// the speed of the machine.
    pub work_limit: u64,
    /// Cap on the number of terms, as a memory guard.
    pub max_terms: usize,
    /// Symbols standing for values the C standard leaves unspecified beyond a constraint (the
    /// magnitude of a `strcmp` result): a proof may rely on the constraint but a refutation that
    /// depends on the symbol is not a real difference.
    pub unspecified: HashSet<T>,
    /// Tag of the proof segment being executed (0: a path from the function entry).  Symbols
    /// that stand for run-time events are named after it, so that the events of an arbitrary
    /// loop iteration are distinct from those that happened before the loop.
    pub seg: u32,
    /// Private objects of the source whose place in the binary's frame is known (see
    /// `verify::match_value`); a counterexample may then mention their addresses.
    pub bound: HashSet<T>,
    /// Symbols that come into existence during execution (results of calls, contents of memory
    /// a callee may have written): the world-memory snapshot from which they exist.
    births: HashMap<T, u32>,
    named: HashMap<String, T>,
}

impl Ctx {
    pub fn new(limits: Limits) -> Ctx {
        Ctx {
            tm: Terms::new(),
            prover: Prover::new(),
            pc: Vec::new(),
            ub: Vec::new(),
            decisions: Vec::new(),
            pos: 0,
            steps: 0,
            limits,
            private_bases: HashSet::new(),
            deadline: None,
            work_limit: u64::MAX,
            max_terms: usize::MAX,
            unspecified: HashSet::new(),
            seg: 0,
            bound: HashSet::new(),
            births: HashMap::new(),
            named: HashMap::new(),
        }
    }

    /// A symbol identified by name: the same name gives the same symbol on every path.
    /// Names of the named symbols created so far.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.named.keys().map(|k| k.as_str())
    }

    pub fn named_sym(&mut self, name: &str, w: u8) -> T {
        if let Some(&t) = self.named.get(name) {
            debug_assert_eq!(self.tm.width(t), w);
            return t;
        }
        let t = self.tm.sym(name, w);
        self.named.insert(name.to_string(), t);
        if let Some(b) = Self::birth_of(name) {
            self.births.insert(t, b);
        }
        t
    }

    /// Symbols created while a path runs are named after the event that produces them:
    /// `ret{k}:…` and `esc{k}:…` exist from snapshot `k + 1`; register garbage after a call
    /// (`clob…`) and values read from volatile objects (`vol…`) are treated as always new.
    fn birth_of(name: &str) -> Option<u32> {
        for prefix in ["ret", "esc"] {
            if let Some(rest) = name.strip_prefix(prefix) {
                let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
                if !digits.is_empty() && rest[digits.len()..].starts_with(':') {
                    return Some(digits.parse::<u32>().unwrap_or(0).saturating_add(1));
                }
            }
        }
        if name.starts_with("clob") || name.starts_with("vol") {
            return Some(0);
        }
        None
    }

    /// Could the value `t` have been computed from something that only became available in
    /// world snapshot `since` or later (so that it may be the address of an object exposed then)?
    pub fn young(&self, t: T, since: u32) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            match self.tm.node(x) {
                crate::term::Node::Load(m, _) if *m >= since => return true,
                _ => {}
            }
            if let Some(&b) = self.births.get(&x)
                && (b == 0 || b >= since)
            {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// May a world address (one that is not syntactically inside a private object) point into
    /// the exposed object `e`?
    pub fn may_point_into(&self, addr: T, e: &Exposed) -> bool {
        self.young(addr, e.since) || self.mentions_private(addr)
    }

    /// `addr` lies inside the exposed object.
    pub fn inside(&mut self, addr: T, e: &Exposed) -> T {
        let off = self.tm.sub(addr, e.base);
        let n = self.tm.konst(32, e.size as u64);
        self.tm.ult(off, n)
    }

    /// A symbol for a run-time event (a value read or returned), distinct per proof segment.
    pub fn event_sym(&mut self, name: &str, w: u8) -> T {
        if self.seg == 0 {
            self.named_sym(name, w)
        } else {
            let n = format!("{name}~{}", self.seg);
            self.named_sym(&n, w)
        }
    }

    pub fn private_base(&mut self, name: &str) -> T {
        let t = self.named_sym(name, 32);
        self.private_bases.insert(t);
        t
    }

    /// Start replaying from the beginning with the current decision vector.
    pub fn restart(&mut self, pre: &[T]) {
        self.pc.clear();
        self.pc.extend_from_slice(pre);
        self.ub.clear();
        self.bound.clear();
        self.pos = 0;
        self.steps = 0;
    }

    /// Advance the decision vector to the next unexplored path.  False when done.
    pub fn next_path(&mut self) -> bool {
        while let Some(last) = self.decisions.pop() {
            if last {
                self.decisions.push(false);
                return true;
            }
        }
        false
    }

    pub fn step(&mut self) -> R<()> {
        self.steps += 1;
        if self.steps > self.limits.max_steps {
            return Err(Stop::Truncated("step limit".into()));
        }
        self.check_deadline()
    }

    /// Work done so far: one unit per term created and per thousand solver propagations.
    /// Deterministic for a given input, unlike elapsed time.
    pub fn work(&self) -> u64 {
        self.prover.counters().3 / 1000 + self.tm.len() as u64
    }

    /// Set the effort limits for the current function.
    pub fn set_budget(&mut self, work_limit: u64, max_terms: usize, deadline: Option<std::time::Instant>) {
        self.work_limit = work_limit;
        self.max_terms = max_terms;
        self.deadline = deadline;
        // The solver stops by itself when the whole budget has gone into propagation.
        self.prover.set_limits(work_limit.saturating_mul(1000), deadline);
    }

    pub fn check_deadline(&self) -> R<()> {
        if self.tm.len() > self.max_terms {
            return Err(Stop::Truncated("term limit".into()));
        }
        if self.work_limit != u64::MAX && self.work() > self.work_limit {
            return Err(Stop::Truncated("work limit".into()));
        }
        match self.deadline {
            Some(d) if std::time::Instant::now() > d => Err(Stop::Truncated("time limit".into())),
            _ => Ok(()),
        }
    }

    /// Does the path condition (with the no-undefined-behaviour assumptions if needed) imply `goal`?
    pub fn implied(&mut self, goal: T) -> bool {
        self.check(goal).is_ok()
    }

    /// Prove `goal` on this path.  On failure returns a counterexample if one exists (None = solver gave up).
    pub fn check(&mut self, goal: T) -> Result<(), Option<Box<Env>>> {
        if self.tm.is_true(goal) {
            return Ok(());
        }
        match self.prover.prove(&mut self.tm, &self.pc, goal) {
            Verdict::Proved => return Ok(()),
            Verdict::Refuted(env) if self.ub.is_empty() => return Err(Some(env)),
            Verdict::Unknown if self.ub.is_empty() => return Err(None),
            _ => {}
        }
        let mut all = self.pc.clone();
        all.extend_from_slice(&self.ub);
        match self.prover.prove(&mut self.tm, &all, goal) {
            Verdict::Proved => Ok(()),
            Verdict::Refuted(env) => Err(Some(env)),
            Verdict::Unknown => Err(None),
        }
    }

    /// Decide a branch condition, forking the path if it is not determined.
    pub fn branch(&mut self, cond: T) -> R<bool> {
        if let Some(c) = self.tm.as_const(cond) {
            return Ok(c == 1);
        }
        self.check_deadline()?;
        let n = self.tm.not(cond);
        if self.pc.contains(&cond) {
            return Ok(true);
        }
        if self.pc.contains(&n) {
            return Ok(false);
        }
        if self.implied(cond) {
            return Ok(true);
        }
        if self.implied(n) {
            return Ok(false);
        }
        let d = if self.pos < self.decisions.len() {
            self.decisions[self.pos]
        } else {
            if self.decisions.len() >= self.limits.max_depth {
                return Err(Stop::Truncated("branch depth limit".into()));
            }
            self.decisions.push(true);
            true
        };
        self.pos += 1;
        self.pc.push(if d { cond } else { n });
        Ok(d)
    }

    /// Record that the C program is only defined when `cond` holds.
    pub fn assume(&mut self, cond: T) -> R<()> {
        if self.tm.is_true(cond) {
            return Ok(());
        }
        if self.tm.is_false(cond) {
            return Err(Stop::Undefined);
        }
        if !self.ub.contains(&cond) {
            self.ub.push(cond);
        }
        Ok(())
    }

    /// If the path condition pins `t` to a single value, return it.
    pub fn unique_value(&mut self, t: T) -> Option<u64> {
        if let Some(v) = self.tm.as_const(t) {
            return Some(v);
        }
        let f = self.tm.fals();
        let Err(Some(env)) = self.check(f) else { return None };
        let v = self.tm.eval(t, &env, &mut HashMap::new());
        let k = self.tm.konst(self.tm.width(t), v);
        let e = self.tm.eq(t, k);
        if self.implied(e) { Some(v) } else { None }
    }

    // ----- memory -------------------------------------------------------------

    /// The private object an address belongs to, if any.
    pub fn region(&self, addr: T) -> Option<T> {
        if self.private_bases.contains(&addr) {
            return Some(addr);
        }
        let (ts, _) = self.tm.linear(addr);
        ts.iter().map(|x| x.0).find(|t| self.private_bases.contains(t))
    }

    pub fn mem_write(&mut self, mem: &mut Mem, addr: T, size: u8, val: T) {
        debug_assert_eq!(self.tm.width(val), size * 8);
        let region = self.region(addr);
        if region.is_none() {
            // A store through a pointer of unknown target may land in an exposed private object.
            for i in 0..mem.exposed.len() {
                let e = mem.exposed[i].clone();
                if !self.may_point_into(addr, &e) {
                    continue;
                }
                if let Some(r) = self.region(e.base) {
                    mem.private.entry(r).or_default().push(Write {
                        addr,
                        size,
                        val,
                        guard: Some((e.base, e.size)),
                    });
                }
            }
        }
        let log = match region {
            Some(r) => mem.private.entry(r).or_default(),
            None => &mut mem.world,
        };
        // Drop older writes that this one fully covers.
        let tm = &mut self.tm;
        log.retain(|e| match tm.const_diff(e.addr, addr) {
            Some(d) => {
                let d = d as u32 as i32 as i64;
                !(d >= 0 && d + e.size as i64 <= size as i64)
            }
            None => true,
        });
        log.push(Write {
            addr,
            size,
            val,
            guard: None,
        });
    }

    /// Read `size` bytes at `addr`.  `init` supplies the value of never-written memory.
    pub fn mem_read(&mut self, mem: &Mem, addr: T, size: u8, init: &mut dyn FnMut(&mut Ctx, T, u8) -> T) -> T {
        static EMPTY: Vec<Write> = Vec::new();
        let Some(r) = self.region(addr) else {
            let mut v = self.read_log(&mem.world, mem.world.len(), addr, size, init);
            // A load through a pointer of unknown target may read an exposed private object.
            for e in &mem.exposed {
                if !self.may_point_into(addr, e) {
                    continue;
                }
                let Some(r) = self.region(e.base) else { continue };
                let log = mem.private.get(&r).unwrap_or(&EMPTY);
                let inner = self.read_log(log, log.len(), addr, size, init);
                let inside = self.inside(addr, e);
                v = self.tm.ite(inside, inner, v);
            }
            return v;
        };
        let log = mem.private.get(&r).unwrap_or(&EMPTY);
        self.read_log(log, log.len(), addr, size, init)
    }

    /// Read from an explicit write log (newest entry last).
    pub fn read_world(&mut self, log: &[Write], addr: T, size: u8, init: &mut dyn FnMut(&mut Ctx, T, u8) -> T) -> T {
        self.read_log(log, log.len(), addr, size, init)
    }

    fn read_log(
        &mut self,
        log: &[Write],
        n: usize,
        addr: T,
        size: u8,
        init: &mut dyn FnMut(&mut Ctx, T, u8) -> T,
    ) -> T {
        let mut slow_at = None;
        for i in (0..n).rev() {
            let e = &log[i];
            // A store that can only have landed in another object.
            if let Some((gbase, gsize)) = e.guard
                && let Some(d) = self.tm.const_diff(addr, gbase)
            {
                let d = d as u32 as i32 as i64;
                if d >= gsize as i64 || d + size as i64 <= 0 {
                    continue;
                }
            }
            match self.tm.const_diff(addr, e.addr) {
                Some(d) => {
                    let d = d as u32 as i32 as i64;
                    if d >= e.size as i64 || d + size as i64 <= 0 {
                        continue;
                    }
                    if d >= 0 && d + size as i64 <= e.size as i64 {
                        return self.tm.extract(e.val, d as u8 * 8, size * 8);
                    }
                    slow_at = Some(i);
                    break;
                }
                None => {
                    if e.size == size {
                        let same = self.tm.eq(addr, e.addr);
                        if self.implied(same) {
                            return e.val;
                        }
                    }
                    let dis = self.disjoint(addr, size, e);
                    if self.implied(dis) {
                        continue;
                    }
                    slow_at = Some(i);
                    break;
                }
            }
        }
        let Some(i) = slow_at else {
            return init(self, addr, size);
        };
        if size > 1 {
            // Assemble from single bytes.
            let mut acc: Option<T> = None;
            for k in 0..size {
                let a = self.tm.add_const(addr, k as u64);
                let b = self.read_log(log, i + 1, a, 1, init);
                acc = Some(match acc {
                    None => b,
                    Some(lo) => self.tm.concat(b, lo),
                });
            }
            return acc.unwrap();
        }
        // One byte against an entry whose relation is unknown.
        let e = &log[i];
        let w = self.tm.width(addr);
        let d = self.tm.sub(addr, e.addr);
        let sz = self.tm.konst(w, e.size as u64);
        let inside = self.tm.ult(d, sz);
        let sel = if e.size == 1 {
            e.val
        } else {
            let vw = self.tm.width(e.val);
            let d8 = self.tm.scale(d, 8);
            let amt = self.tm.resize(d8, vw, false);
            let sh = self.tm.lshr(e.val, amt);
            self.tm.trunc(sh, 8)
        };
        if self.implied(inside) {
            return sel;
        }
        let rest = self.read_log(log, i, addr, 1, init);
        self.tm.ite(inside, sel, rest)
    }

    fn disjoint(&mut self, addr: T, size: u8, e: &Write) -> T {
        let w = self.tm.width(addr);
        let d1 = self.tm.sub(addr, e.addr);
        let d2 = self.tm.sub(e.addr, addr);
        let s1 = self.tm.konst(w, e.size as u64);
        let s2 = self.tm.konst(w, size as u64);
        let a = self.tm.ule(s1, d1);
        let b = self.tm.ule(s2, d2);
        self.tm.and(a, b)
    }

    /// Split a pointer into a private object's base and the offset from it.  None if `t` is not
    /// exactly one private base plus a term free of private addresses.
    pub fn private_split(&mut self, t: T) -> Option<(T, T)> {
        let base = if self.private_bases.contains(&t) {
            t
        } else {
            let (ts, _) = self.tm.linear(t);
            let mut it = ts.iter().filter(|x| self.private_bases.contains(&x.0));
            match (it.next(), it.next()) {
                (Some(&(b, 1)), None) => b,
                _ => return None,
            }
        };
        let off = self.tm.sub(t, base);
        if self.mentions_private(off) {
            None
        } else {
            Some((base, off))
        }
    }

    /// Does `t` depend on the contents of never-written private memory (an indeterminate value)?
    pub fn mentions_uninit(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if let crate::term::Node::Load(m, _) = self.tm.node(x)
                && *m >= UNINIT_EPOCH
            {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// Does `t` depend on a value the C standard leaves unspecified?
    pub fn mentions_unspecified(&self, t: T) -> bool {
        if self.unspecified.is_empty() {
            return false;
        }
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.unspecified.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// Is `x` a subterm of `t`?
    pub fn mentions(&self, t: T, x: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(y) = stack.pop() {
            if y == x {
                return true;
            }
            if !seen.insert(y) {
                continue;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(y)));
        }
        false
    }

    /// Is `t` computed only from the function's inputs: no value read from memory, returned by
    /// a call or otherwise created while the path ran?
    pub fn pristine(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(y) = stack.pop() {
            if !seen.insert(y) {
                continue;
            }
            if matches!(self.tm.node(y), crate::term::Node::Load(..)) || self.births.contains_key(&y) {
                return false;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(y)));
        }
        true
    }

    /// Does `t` mention the address of a private object whose place in the binary is unknown?
    pub fn mentions_unbound_private(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.private_bases.contains(&x) && !self.bound.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }

    /// Does `t` mention the address of a private object?
    pub fn mentions_private(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.private_bases.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }
}

/// 64-bit product in the shape 32-bit code computes it: from the halves of the operands.  Both
/// executors build products through this function so that they arrive at the same term.
pub fn mul64(tm: &mut Terms, a: T, b: T) -> T {
    use crate::term::Node;
    let widened = |tm: &Terms, t: T| matches!(tm.node(t), Node::ZExt(_) | Node::SExt(_) | Node::Const(_));
    if tm.width(a) != 64 || (widened(tm, a) && widened(tm, b)) {
        return tm.mul(a, b);
    }
    let (al, ah) = (tm.extract(a, 0, 32), tm.extract(a, 32, 32));
    let (bl, bh) = (tm.extract(b, 0, 32), tm.extract(b, 32, 32));
    let (za, zb) = (tm.zext(al, 64), tm.zext(bl, 64));
    let full = tm.mul(za, zb);
    let lo = tm.extract(full, 0, 32);
    let carry = tm.extract(full, 32, 32);
    let x1 = tm.mul(ah, bl);
    let x2 = tm.mul(al, bh);
    let hi = tm.add(x1, x2);
    let hi = tm.add(hi, carry);
    tm.concat(hi, lo)
}

/// Where the AAPCS places an argument.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArgLoc {
    Reg(u8),
    /// 64-bit value in registers n (low) and n + 1 (high).
    RegPair(u8),
    /// Offset from the stack pointer at the call.
    Stack(u32),
    Stack64(u32),
}

/// Assign AAPCS32 locations to integer arguments of the given bit widths (<= 32 or 64).
pub fn arg_locs(widths: &[u8]) -> Vec<ArgLoc> {
    let mut ncrn = 0u8;
    let mut nsaa = 0u32;
    widths
        .iter()
        .map(|&w| {
            if w <= 32 {
                if ncrn < 4 {
                    ncrn += 1;
                    ArgLoc::Reg(ncrn - 1)
                } else {
                    nsaa += 4;
                    ArgLoc::Stack(nsaa - 4)
                }
            } else {
                ncrn = ncrn.next_multiple_of(2);
                if ncrn <= 2 {
                    ncrn += 2;
                    ArgLoc::RegPair(ncrn - 2)
                } else {
                    ncrn = 4;
                    nsaa = nsaa.next_multiple_of(8) + 8;
                    ArgLoc::Stack64(nsaa - 8)
                }
            }
        })
        .collect()
}

/// A local object of the C program whose address has been handed to an external function.
/// From then on every external call may read and modify it.
#[derive(Clone, Debug)]
pub struct Escaped {
    /// The object's private base address on the C side.
    pub base: T,
    pub size: u32,
    pub name: String,
    /// Contents at the call: (offset, size in bytes, value).  The value is None where the C
    /// program left the bytes indeterminate (never written, padding): the binary may hold anything there.
    pub pre: Vec<(u32, u8, Option<T>)>,
    /// Contents after the call: fresh symbols shared by both sides.  Empty if the call does not return.
    pub post: Vec<(u32, u8, T)>,
}

/// Where one 32-bit word of an argument is passed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WordLoc {
    Reg(u8),
    /// Offset from the stack pointer at the call.
    Stack(u32),
}

/// AAPCS32 locations of the words of each argument, given (size in bytes, needs 8-byte
/// alignment) per argument.  Covers integers and composites passed by value, which may be
/// split between registers and the stack.  `first_reg` is 1 when r0 holds the address of the
/// result (functions returning a composite larger than four bytes).
pub fn arg_words(args: &[(u32, bool)], first_reg: u8) -> Vec<Vec<WordLoc>> {
    let mut ncrn = first_reg as u32;
    let mut nsaa = 0u32;
    args.iter()
        .map(|&(size, align8)| {
            let words = size.div_ceil(4).max(1);
            if align8 {
                ncrn = ncrn.next_multiple_of(2);
            }
            let mut locs = Vec::with_capacity(words as usize);
            if ncrn < 4 && (ncrn + words <= 4 || nsaa == 0) {
                for _ in 0..words {
                    if ncrn < 4 {
                        locs.push(WordLoc::Reg(ncrn as u8));
                        ncrn += 1;
                    } else {
                        locs.push(WordLoc::Stack(nsaa));
                        nsaa += 4;
                    }
                }
            } else {
                ncrn = 4;
                if align8 {
                    nsaa = nsaa.next_multiple_of(8);
                }
                for _ in 0..words {
                    locs.push(WordLoc::Stack(nsaa));
                    nsaa += 4;
                }
            }
            locs
        })
        .collect()
}

/// An externally observable call made by the C side, to be matched by the binary.
#[derive(Clone, Debug)]
pub struct Event {
    pub name: String,
    /// Argument values and whether each is signed (for extension to register width).
    pub args: Vec<(T, bool)>,
    /// Arguments of which only some bits carry a value (words of a structure with padding):
    /// (argument index, mask of the value bits).
    pub arg_masks: Vec<(usize, u64)>,
    /// World memory at the time of the call.
    pub writes: Vec<Write>,
    pub epoch: u32,
    /// Symbol standing for the returned value, and its signedness.
    pub ret: Option<(T, bool)>,
    pub noreturn: bool,
    /// Local objects reachable by the callee, in discovery order.
    pub escaped: Vec<Escaped>,
    /// The source's exposed objects once the call has been made.
    pub exposed: Vec<Exposed>,
}