cverif 0.0.4

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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
//! 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)>,
    /// Not a store but the replacement of a whole range by unknown contents (`size` and `val`
    /// are unused): the object at `addr` was handed to code that may have written all of it.
    pub havoc: Option<Havoc>,
}

/// Unknown contents of an object of `size` bytes: the byte at offset `o` is the byte at
/// `canon + o` of memory `mem`.  Both sides use the same memory and canonical base for the
/// same object, so they read the same values without knowing them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Havoc {
    pub size: T,
    pub mem: u32,
    pub canon: T,
}

/// First identifier of the memories that stand for havocked objects of dynamic size.
pub const HAVOC_BASE: u32 = 0x4000_0000;

/// Bound of a guard that stands for an object of dynamic size.
pub const DYN_GUARD: u32 = 0x7fff_ffff;

/// 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,
    /// Size in bytes of an object whose size is not a constant (`size` is then unused).
    pub dyn_size: Option<T>,
    /// 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,
    /// An access below the stack pointer is a difference, not a hazard (`--strict-stack`).
    pub strict_stack: bool,
}

/// The binary reads or stores below its stack pointer.  Without interrupts that is as good
/// as any other memory until the next call; with them, an exception taken at that point
/// pushes its frame over the bytes.  Reported next to the verdict, which it does not change.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Hazard {
    /// The instruction.
    pub pc: u32,
    pub size: u8,
    pub write: bool,
}

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

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>,
    /// Those among `ub` that hold in the compiler's model of the language rather than by the
    /// letter of the standard (type-based aliasing as GCC and clang implement it).  They are
    /// the last resort of a proof, and a proof that needed one says so.
    pub model: HashSet<T>,
    /// A proof on this function needed one of the `model` conditions.
    pub model_used: bool,
    /// Whether the conditions of the current path are satisfiable together with the model
    /// conditions: (length of `pc`, length of `ub`, a checksum of both, answer).
    model_sat: Option<(usize, usize, u64, bool)>,
    pub decisions: Vec<bool>,
    pub pos: usize,
    pub steps: u64,
    pub limits: Limits,
    /// Accesses below the stack pointer seen on any path so far.
    pub hazards: std::collections::BTreeSet<Hazard>,
    /// 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(),
            model: HashSet::new(),
            model_used: false,
            model_sat: None,
            decisions: Vec::new(),
            pos: 0,
            steps: 0,
            limits,
            hazards: Default::default(),
            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 = match e.dyn_size {
            Some(n) => n,
            None => self.tm.konst(32, e.size as u64),
        };
        self.tm.ult(off, n)
    }

    /// Replace the `size` bytes of the private object at `base` by the contents of memory `id`
    /// (unknown values, the same for whoever reads the same offset from `canon`).
    pub fn mem_havoc(&mut self, mem: &mut Mem, base: T, size: T, id: u32, canon: T) {
        let Some(r) = self.region(base) else { return };
        mem.private.entry(r).or_default().push(Write {
            addr: base,
            size: 0,
            val: size,
            guard: None,
            havoc: Some(Havoc { size, mem: id, canon }),
        });
    }

    /// How a read of `size` bytes at `addr` relates to a havocked range: (wholly inside,
    /// wholly outside).
    fn havoc_relation(&mut self, addr: T, size: u8, base: T, h: &Havoc) -> (T, T) {
        let off = self.tm.sub(addr, base);
        let n = self.tm.konst(32, size as u64);
        // inside: size <= S and off <= S - size
        let fits = self.tm.ule(n, h.size);
        let room = self.tm.sub(h.size, n);
        let low = self.tm.ule(off, room);
        let inside = self.tm.and(fits, low);
        // outside: at or after the end, or wholly before the start (base - addr >= size)
        let after = self.tm.ule(h.size, off);
        let back = self.tm.sub(base, addr);
        let before = self.tm.ule(n, back);
        let apart = self.tm.and(after, before);
        (inside, apart)
    }

    /// 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.model.clear();
        self.model_sat = None;
        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();
        let has_model = self.ub.iter().any(|u| self.model.contains(u));
        if !has_model {
            all.extend_from_slice(&self.ub);
            return match self.prover.prove(&mut self.tm, &all, goal) {
                Verdict::Proved => Ok(()),
                Verdict::Refuted(env) => Err(Some(env)),
                Verdict::Unknown => Err(None),
            };
        }
        // First what the standard itself guarantees, then the compiler's model as well.
        all.extend(self.ub.iter().filter(|u| !self.model.contains(u)));
        let strict = match self.prover.prove(&mut self.tm, &all, goal) {
            Verdict::Proved => return Ok(()),
            Verdict::Refuted(env) => Err(Some(env)),
            Verdict::Unknown => Err(None),
        };
        if !self.model_consistent() {
            return strict;
        }
        let mut all = self.pc.clone();
        all.extend_from_slice(&self.ub);
        match self.prover.prove(&mut self.tm, &all, goal) {
            Verdict::Proved => {
                self.model_used = true;
                Ok(())
            }
            Verdict::Refuted(env) => Err(Some(env)),
            Verdict::Unknown => Err(None),
        }
    }

    /// The model conditions are only used on a path they do not contradict: where the source
    /// certainly accesses one object with two types, compilers see it too, and assuming the
    /// opposite would prove anything.
    fn model_consistent(&mut self) -> bool {
        let sum =
            (self.pc.iter().chain(&self.ub)).fold(0u64, |h, &t| h.wrapping_mul(0x100_0000_01b3).wrapping_add(t as u64));
        let key = (self.pc.len(), self.ub.len(), sum);
        if let Some((a, b, c, ok)) = self.model_sat
            && (a, b, c) == key
        {
            return ok;
        }
        let mut all = self.pc.clone();
        all.extend_from_slice(&self.ub);
        let f = self.tm.fals();
        let ok = matches!(self.prover.prove(&mut self.tm, &all, f), Verdict::Refuted(_));
        self.model_sat = Some((key.0, key.1, key.2, ok));
        ok
    }

    /// Record a condition that holds in the compiler's model of the language (see `model`).
    pub fn assume_model(&mut self, cond: T) -> R<()> {
        if self.tm.is_true(cond) || self.tm.is_false(cond) {
            // Certain overlap is not undefined by this rule: it is simply not assumed away.
            return Ok(());
        }
        if !self.ub.contains(&cond) {
            self.ub.push(cond);
            self.model.insert(cond);
        }
        Ok(())
    }

    /// 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);
        } else if self.model.remove(&cond) {
            // What was so far only the compilers' reading is now also what the standard says.
            self.model_sat = None;
        }
        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, if e.dyn_size.is_some() { DYN_GUARD } else { e.size })),
                        havoc: None,
                    });
                }
            }
        }
        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| {
            e.havoc.is_some()
                || 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,
            havoc: 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 inside = self.inside(addr, e);
                // Settled by the path (or by what the language guarantees about it): the
                // access does not touch this object.
                let outside = self.tm.not(inside);
                if self.implied(outside) {
                    continue;
                }
                // Only what was stored in the object itself matters: the region may hold
                // much else (the whole stack frame, on the machine side).
                let log: Vec<Write> = (mem.private.get(&r).unwrap_or(&EMPTY).iter())
                    .filter(|w| match self.tm.const_diff(w.addr, e.base) {
                        Some(d) => {
                            let d = d as u32 as i32 as i64;
                            d < e.size as i64 + size as i64 - 1 && d + w.size as i64 > 0
                        }
                        None => true,
                    })
                    .cloned()
                    .collect();
                let inner = self.read_log(&log, log.len(), addr, size, init);
                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];
            if let Some(h) = e.havoc {
                let base = e.addr;
                if let Some(d) = self.tm.const_diff(addr, base)
                    && (d as u32 as i32 as i64) + size as i64 <= 0
                {
                    continue;
                }
                let (inside, apart) = self.havoc_relation(addr, size, base, &h);
                if self.implied(apart) {
                    continue;
                }
                let off = self.tm.sub(addr, base);
                let ca = self.tm.add(h.canon, off);
                if self.implied(inside) {
                    return self.tm.load(h.mem, ca, size);
                }
                if size > 1 {
                    // Straddles the boundary, or cannot be placed: byte by byte.
                    slow_at = Some(i);
                    break;
                }
                let fresh = self.tm.load(h.mem, ca, 1);
                let rest = self.read_log(log, i, addr, 1, init);
                return self.tm.ite(inside, fresh, rest);
            }
            // 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;
                    }
                    // Two accesses of the same size, both aligned to it, are to the same
                    // bytes or to disjoint ones: no need to assemble the value from pieces.
                    if e.size == size && size > 1 && self.aligned(addr, size) && self.aligned(e.addr, size) {
                        let same = self.tm.eq(addr, e.addr);
                        let val = e.val;
                        let rest = self.read_log(log, i, addr, size, init);
                        return self.tm.ite(same, val, rest);
                    }
                    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)
    }

    /// Is the address known to be a multiple of `size` (a power of two) on this path?
    fn aligned(&mut self, addr: T, size: u8) -> bool {
        if !size.is_power_of_two() {
            return false;
        }
        let bits = size.trailing_zeros() as u8;
        let low = self.tm.extract(addr, 0, bits);
        let zero = self.tm.konst(bits, 0);
        let ok = self.tm.eq(low, zero);
        self.tm.is_true(ok) || self.pc.contains(&ok) || self.ub.contains(&ok) || self.implied(ok)
    }

    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,
    /// The alignment the object's type requires: the callee may rely on it.
    pub align: u32,
    /// For an object whose size is not a constant (a variable-length array, an `alloca` block):
    /// its size in bytes, the source's writes to it up to the call (`pre` is unused) and the
    /// memory that stands for its contents after the call (`post` is unused).
    pub dynamic: Option<Box<DynEscaped>>,
    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)>,
}

#[derive(Clone, Debug)]
pub struct DynEscaped {
    pub size: T,
    pub log: Vec<Write>,
    /// None if the call does not return.
    pub havoc: Option<u32>,
}

/// 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>,
    /// The event is an inline assembly instruction rather than a call (the name starts with
    /// `asm:`); the flag tells whether the statement clobbers memory.  Without that, world
    /// memory is neither compared nor considered changed at the event: the compiler may move
    /// ordinary stores across the statement.
    pub asm: Option<bool>,
    /// The callee may return a second time (`setjmp`): see `verify::RtLog`.
    pub returns_twice: bool,
}