Skip to main content

foundry_evm_symbolic/runtime/
evm.rs

1use super::*;
2use alloy_sol_types::{
3    Panic, PanicKind, Revert, SolError,
4    abi::{AbiDecoderConfig, decode_with_config, token::PackedSeqToken},
5};
6use foundry_evm::core::decode::ASSERTION_FAILED_PREFIX;
7
8pub(crate) fn exp_expr_for_concrete_exponent(
9    cx: &mut SymCx,
10    base: SymExpr,
11    exponent: usize,
12) -> SymExpr {
13    if exponent == 0 {
14        return SymExpr::one(cx);
15    }
16    if let Some(base) = base.as_const() {
17        return SymExpr::constant(cx, base.wrapping_pow(U256::from(exponent)));
18    }
19
20    let mut expr = base.clone();
21    for _ in 1..exponent {
22        expr = SymExpr::binop(cx, SymBinOp::Mul, expr, base.clone());
23    }
24    expr
25}
26
27pub(crate) fn signextend(byte_index: U256, value: U256) -> U256 {
28    if byte_index >= U256::from(32) {
29        return value;
30    }
31    let bit_index = usize::try_from(byte_index).expect("checked byte index") * 8 + 7;
32    let sign_bit = U256::ONE << bit_index;
33    let mask = sign_bit - U256::ONE;
34    if (value & sign_bit).is_zero() { value & mask } else { value | !mask }
35}
36
37pub(crate) fn signextend_word(cx: &mut SymCx, byte_index: U256, value: SymExpr) -> SymExpr {
38    if byte_index >= U256::from(32) {
39        return value;
40    }
41    if let Some(value) = value.as_const() {
42        return SymExpr::constant(cx, signextend(byte_index, value));
43    }
44    let bit_index = usize::try_from(byte_index).expect("checked byte index") * 8 + 7;
45    let sign_bit = U256::ONE << bit_index;
46    let mask_value = sign_bit - U256::ONE;
47    let sign_bit = SymExpr::constant(cx, sign_bit);
48    let masked_sign = SymExpr::binop(cx, SymBinOp::And, value.clone(), sign_bit);
49    let zero = SymExpr::zero(cx);
50    let condition = SymBoolExpr::eq(cx, masked_sign, zero);
51    let inverse_mask = SymExpr::constant(cx, !mask_value);
52    let mask = SymExpr::constant(cx, mask_value);
53    let masked = SymExpr::binop(cx, SymBinOp::And, value.clone(), mask);
54    let extended = SymExpr::binop(cx, SymBinOp::Or, value, inverse_mask);
55    SymExpr::ite(cx, condition, masked, extended)
56}
57
58pub(crate) fn signextend_word_dynamic(
59    cx: &mut SymCx,
60    byte_index: SymExpr,
61    value: SymExpr,
62) -> SymExpr {
63    if let Some(byte_index) = byte_index.as_const() {
64        return signextend_word(cx, byte_index, value);
65    }
66
67    let mut result = value.clone();
68    for idx in (0..31).rev() {
69        let idx_expr = SymExpr::constant(cx, U256::from(idx));
70        let condition = SymBoolExpr::eq(cx, byte_index.clone(), idx_expr);
71        let value = signextend_word(cx, U256::from(idx), value.clone());
72        result = SymExpr::ite(cx, condition, value, result);
73    }
74    result
75}
76
77pub(crate) fn byte_word(cx: &mut SymCx, index: U256, word: SymExpr) -> SymExpr {
78    if index >= U256::from(32) {
79        return SymExpr::zero(cx);
80    }
81    let index = usize::try_from(index).expect("checked byte index");
82    if let Some(word) = word.as_const() {
83        SymExpr::constant(cx, U256::from(word.to_be_bytes::<32>()[index]))
84    } else {
85        byte_expr(cx, index, &word)
86    }
87}
88
89pub(crate) fn byte_word_dynamic(cx: &mut SymCx, index: SymExpr, word: SymExpr) -> SymExpr {
90    if let Some(index) = index.as_const() {
91        return byte_word(cx, index, word);
92    }
93
94    let mut result = SymExpr::zero(cx);
95    if let Some(word) = word.as_const() {
96        let bytes = word.to_be_bytes::<32>();
97        for idx in (0..32).rev() {
98            let idx_expr = SymExpr::constant(cx, U256::from(idx));
99            let condition = SymBoolExpr::eq(cx, index.clone(), idx_expr);
100            let byte = SymExpr::constant(cx, U256::from(bytes[idx]));
101            result = SymExpr::ite(cx, condition, byte, result);
102        }
103    } else {
104        for idx in (0..32).rev() {
105            let idx_expr = SymExpr::constant(cx, U256::from(idx));
106            let condition = SymBoolExpr::eq(cx, index.clone(), idx_expr);
107            let byte = byte_expr(cx, idx, &word);
108            result = SymExpr::ite(cx, condition, byte, result);
109        }
110    }
111    result
112}
113
114/// Returns the number of leading zero bits in `value`, or 256 when it is zero.
115pub(crate) fn clz_word(cx: &mut SymCx, value: SymExpr) -> SymExpr {
116    if let Some(value) = value.as_const() {
117        return SymExpr::constant(cx, U256::from(value.leading_zeros()));
118    }
119
120    // Binary search: shift out high zero halves and add their widths.
121    let mut count = SymExpr::zero(cx);
122    let mut word = value.clone();
123    for bits in [128, 64, 32, 16, 8, 4, 2, 1] {
124        let high_zero =
125            SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &word, U256::ONE << (256 - bits));
126        let added = SymExpr::constant(cx, U256::from(bits));
127        let added_count = SymExpr::binop(cx, SymBinOp::Add, count.clone(), added);
128        count = SymExpr::ite(cx, high_zero.clone(), added_count, count);
129        let shifted = shift_left(cx, word.clone(), bits);
130        word = SymExpr::ite(cx, high_zero, shifted, word);
131    }
132    let is_zero = SymBoolExpr::eq_word_const(cx, &value, U256::ZERO);
133    let full = SymExpr::constant(cx, U256::from(256));
134    SymExpr::ite(cx, is_zero, full, count)
135}
136
137/// Returns the byte extraction expression for a symbolic word.
138pub(crate) fn byte_expr(cx: &mut SymCx, index: usize, expr: &SymExpr) -> SymExpr {
139    debug_assert!(index < 32);
140    if let Some(byte) = expr.known_byte(index) {
141        return SymExpr::constant(cx, U256::from(byte));
142    }
143    expr.extracted_byte(cx, index)
144}
145
146pub(crate) fn shift_left(cx: &mut SymCx, value: SymExpr, bits: usize) -> SymExpr {
147    if let Some(value) = value.as_const() {
148        SymExpr::constant(cx, value << bits)
149    } else {
150        let bits = SymExpr::constant(cx, U256::from(bits));
151        SymExpr::binop(cx, SymBinOp::Shl, value, bits)
152    }
153}
154
155pub(crate) fn is_assertion_revert(data: &[u8]) -> bool {
156    Panic::abi_decode(data).is_ok_and(|panic| panic.kind() == Some(PanicKind::Assert))
157        || is_revert_assertion_failure(data)
158}
159
160pub(crate) fn cheatcode_error_revert_condition(
161    cx: &mut SymCx,
162    data: &SymReturnData,
163) -> Option<SymBoolExpr> {
164    let selector = SymBytes::concrete(cx, Vm::CheatcodeError::SELECTOR.to_vec());
165    let prefix = data.bytes.prefix_condition(cx, &selector)?;
166    let selector_len = SymExpr::constant(cx, U256::from(selector.len()));
167    let has_selector = SymBoolExpr::cmp_word_expr(cx, SymCmpOp::Uge, &data.len_word, selector_len);
168    Some(SymBoolExpr::and(cx, vec![has_selector, prefix]))
169}
170
171/// Returns the condition under which symbolic revert data is an assertion failure: a
172/// `Panic(0x01)` or an `Error(string)` whose message contains the assertion prefix.
173pub(crate) fn assertion_revert_condition(
174    cx: &mut SymCx,
175    data: &SymReturnData,
176) -> Option<SymBoolExpr> {
177    let mut encodings = Vec::new();
178    let panic = SymBytes::concrete(cx, Panic::from(PanicKind::Assert).abi_encode());
179    if let Some(prefix) = data.bytes.prefix_condition(cx, &panic) {
180        let len = SymExpr::constant(cx, U256::from(panic.len()));
181        let has_len = SymBoolExpr::cmp_word_expr(cx, SymCmpOp::Uge, &data.len_word, len);
182        encodings.push(SymBoolExpr::and(cx, vec![has_len, prefix]));
183    }
184    encodings.extend(assertion_message_condition(cx, data));
185    (!encodings.is_empty()).then(|| SymBoolExpr::or(cx, encodings))
186}
187
188/// Returns the condition under which symbolic revert data is an `Error(string)` whose message
189/// contains the assertion prefix, validated like `is_revert_assertion_failure`: the encoded length
190/// must be concrete and within the data, the concrete bytes must decode as UTF-8 and contain the
191/// prefix on their own, and every symbolic byte must be ASCII so the message stays valid UTF-8.
192fn assertion_message_condition(cx: &mut SymCx, data: &SymReturnData) -> Option<SymBoolExpr> {
193    let mut header = Revert::SELECTOR.to_vec();
194    header.extend(U256::from(32).to_be_bytes::<32>());
195    let header = SymBytes::concrete(cx, header);
196    let header = data.bytes.prefix_condition(cx, &header)?;
197    let message_len = usize::try_from(data.bytes.word_at(cx, 36).as_const()?).ok()?;
198    let end = ERROR_DATA_MIN_LEN.checked_add(message_len).filter(|end| *end <= data.len())?;
199    let mut conditions = vec![header];
200    let mut concrete = Vec::with_capacity(message_len);
201    for offset in ERROR_DATA_MIN_LEN..end {
202        let byte = data.bytes.byte(cx, offset);
203        match byte.as_const() {
204            Some(value) => concrete.push(u8::try_from(value).ok()?),
205            None => {
206                // The placeholder is outside the prefix, so symbolic bytes never complete it.
207                concrete.push(b'_');
208                let ascii = SymExpr::constant(cx, U256::from(0x80));
209                conditions.push(SymBoolExpr::cmp_word_expr(cx, SymCmpOp::Ult, &byte, ascii));
210            }
211        }
212    }
213    if !std::str::from_utf8(&concrete).ok()?.contains(ASSERTION_FAILED_PREFIX) {
214        return None;
215    }
216    let len = SymExpr::constant(cx, U256::from(end));
217    conditions.push(SymBoolExpr::cmp_word_expr(cx, SymCmpOp::Uge, &data.len_word, len));
218    Some(SymBoolExpr::and(cx, conditions))
219}
220
221pub(crate) fn is_revert_assertion_failure(data: &[u8]) -> bool {
222    if data.len() < ERROR_DATA_MIN_LEN {
223        return false;
224    }
225    let Some(data) = data.strip_prefix(&Revert::SELECTOR) else { return false };
226    // Decode a borrowed token to preserve strict UTF-8 checks without allocating a String.
227    let config = AbiDecoderConfig::new().memory_limit(data.len());
228    decode_with_config::<PackedSeqToken<'_>>(data, config)
229        .ok()
230        .and_then(|message| std::str::from_utf8(message.0).ok())
231        .is_some_and(|message| message.contains(ASSERTION_FAILED_PREFIX))
232}