Skip to main content

foundry_evm_symbolic/runtime/expr/
cx.rs

1use super::{hashcons::HashCons, *};
2use alloy_primitives::map::DefaultHashBuilder;
3use inturn::unsync::Interner;
4use std::collections::BTreeMap;
5
6pub(crate) struct SymCx {
7    words: HashCons<SymExprKind>,
8    bools: HashCons<SymBoolExprKind>,
9    bytes: HashCons<SymBytesKind>,
10    symbols: Interner<Symbol, DefaultHashBuilder>,
11    replayable_inputs: SymbolicVars,
12    /// Ordered so that the closest hash below a constant is a range lookup.
13    concrete_keccak_preimages: BTreeMap<U256, Arc<[SymExpr]>>,
14    cache: SymCxCache,
15    /// Solver normalization results for `ite`-containing words, keyed by the input word.
16    ///
17    /// Keys are strong hash-consed handles, so the map is bounded like the SAT cache.
18    solver_normalized_words: HashMap<SymExpr, SymExpr>,
19}
20
21struct SymCxCache {
22    zero: SymExpr,
23    one: SymExpr,
24    bool_true: SymBoolExpr,
25    bool_false: SymBoolExpr,
26    bytes_empty: SymBytes,
27}
28
29impl SymCx {
30    pub(crate) fn new() -> Self {
31        let mut words = HashCons::new();
32        let zero = SymExpr { kind: words.make(SymExprKind::Const(U256::ZERO)) };
33        let one = SymExpr { kind: words.make(SymExprKind::Const(U256::ONE)) };
34
35        let mut bools = HashCons::new();
36        let bool_true = SymBoolExpr { kind: bools.make(SymBoolExprKind::Const(true)) };
37        let bool_false = SymBoolExpr { kind: bools.make(SymBoolExprKind::Const(false)) };
38
39        let mut bytes = HashCons::new();
40        let bytes_empty = SymBytes { kind: bytes.make(SymBytesKind::Concrete(Vec::new())) };
41
42        Self {
43            words,
44            bools,
45            bytes,
46            symbols: Interner::with_hasher(DefaultHashBuilder::default()),
47            replayable_inputs: SymbolicVars::default(),
48            concrete_keccak_preimages: BTreeMap::new(),
49            cache: SymCxCache { zero, one, bool_true, bool_false, bytes_empty },
50            solver_normalized_words: HashMap::default(),
51        }
52    }
53
54    pub(in crate::runtime) fn mk_expr_kind(&mut self, expr: SymExprKind) -> SymExpr {
55        SymExpr { kind: self.words.make(expr) }
56    }
57
58    pub(in crate::runtime) fn mk_bool_kind(&mut self, expr: SymBoolExprKind) -> SymBoolExpr {
59        SymBoolExpr { kind: self.bools.make(expr) }
60    }
61
62    pub(in crate::runtime) fn mk_bytes_kind(&mut self, bytes: SymBytesKind) -> SymBytes {
63        if matches!(&bytes, SymBytesKind::Concrete(bytes) if bytes.is_empty()) {
64            return self.cache.bytes_empty.clone();
65        }
66        SymBytes { kind: self.bytes.make(bytes) }
67    }
68
69    pub(in crate::runtime::expr) fn cached_zero(&self) -> SymExpr {
70        self.cache.zero.clone()
71    }
72
73    pub(in crate::runtime::expr) fn cached_one(&self) -> SymExpr {
74        self.cache.one.clone()
75    }
76
77    pub(in crate::runtime::expr) fn cached_bool(&self, value: bool) -> SymBoolExpr {
78        if value { self.cache.bool_true.clone() } else { self.cache.bool_false.clone() }
79    }
80
81    pub(crate) fn intern(&mut self, name: &str) -> Symbol {
82        self.symbols.intern_mut(name)
83    }
84
85    pub(crate) fn symbol_name(&self, symbol: Symbol) -> &str {
86        self.symbols.resolve(symbol)
87    }
88
89    pub(crate) fn mark_replayable_input(&mut self, symbol: Symbol) {
90        self.replayable_inputs.insert(symbol);
91    }
92
93    pub(crate) fn is_replayable_input(&self, symbol: Symbol) -> bool {
94        self.replayable_inputs.contains(&symbol)
95    }
96
97    pub(in crate::runtime) fn record_concrete_keccak_preimage(
98        &mut self,
99        hash: U256,
100        bytes: Arc<[SymExpr]>,
101    ) {
102        self.concrete_keccak_preimages.entry(hash).or_insert(bytes);
103    }
104
105    pub(in crate::runtime::expr) fn concrete_keccak_preimage(
106        &self,
107        hash: U256,
108    ) -> Option<Arc<[SymExpr]>> {
109        self.concrete_keccak_preimages.get(&hash).cloned()
110    }
111
112    /// Returns the closest recorded concrete hash below `value` that `value` is a storage layout
113    /// offset from, so a folded `keccak(..) + offset` constant keeps its hash base.
114    pub(in crate::runtime) fn concrete_keccak_base(
115        &self,
116        value: U256,
117        offset_bits: usize,
118    ) -> Option<U256> {
119        let (&hash, _) = self.concrete_keccak_preimages.range(..=value).next_back()?;
120        (value - hash < U256::ONE << offset_bits).then_some(hash)
121    }
122
123    /// Returns the memoized solver normalization of `expr`.
124    pub(in crate::runtime) fn solver_normalized_word(&self, expr: &SymExpr) -> Option<SymExpr> {
125        self.solver_normalized_words.get(expr).cloned()
126    }
127
128    /// Memoizes the solver normalization of `expr`.
129    ///
130    /// A full map is cleared rather than frozen: a miss on a nested `ite` chain re-traverses it
131    /// once per nesting level, so later words must stay cacheable.
132    pub(in crate::runtime) fn record_solver_normalized_word(
133        &mut self,
134        expr: SymExpr,
135        normalized: SymExpr,
136    ) {
137        if self.solver_normalized_words.len() >= SYMBOLIC_SOLVER_SAT_CACHE_MAX_ENTRIES {
138            self.solver_normalized_words.clear();
139        }
140        self.solver_normalized_words.insert(expr, normalized);
141    }
142}
143
144impl fmt::Debug for SymCx {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.debug_struct("SymCx").finish_non_exhaustive()
147    }
148}
149
150impl Default for SymCx {
151    fn default() -> Self {
152        Self::new()
153    }
154}