foundry_evm_symbolic/executor/
constraints.rs1use foundry_cheatcodes_spec::Vm::{assumeCall, bound_0Call, bound_1Call, skip_0Call, skip_1Call};
2
3use super::*;
4
5impl SymbolicExecutor {
6 pub(super) fn handle_assume(
8 &mut self,
9 state: &mut PathState,
10 condition_offset: usize,
11 ) -> Result<CheatcodeOutcome, SymbolicError> {
12 let cond = state.memory.load_word(&mut self.cx, condition_offset)?;
13 let cond = cond.nonzero_bool(&mut self.cx);
14 if cond.as_const() != Some(true) {
15 let rejected = cond.not(&mut self.cx);
18 let (_, rejected_sat) = self.constraints_with_condition(state, rejected)?;
19 if rejected_sat {
20 return Err(SymbolicError::Unsupported(
21 "vm.assume may reject an invariant predicate",
22 ));
23 }
24 }
25 Ok(CheatcodeOutcome::Continue(Vec::new()))
26 }
27
28 #[expect(clippy::too_many_arguments)]
32 pub(super) fn branch_assume_cheatcode_if_needed(
33 &mut self,
34 state: &mut PathState,
35 worklist: &mut VecDeque<PathState>,
36 selector: [u8; 4],
37 input: Option<&SymMemory>,
38 in_offset: usize,
39 out_offset: SymExpr,
40 out_size: &BoundedCopySize,
41 ) -> Result<Option<StepOutcome>, SymbolicError> {
42 let skip = matches!(selector, skip_0Call::SELECTOR | skip_1Call::SELECTOR);
43 if !skip && (selector != assumeCall::SELECTOR || state.invariant_predicate) {
44 return Ok(None);
45 }
46 let memory = input.unwrap_or(&state.memory);
47 let cond = memory.load_word(&mut self.cx, in_offset + 4)?;
48 let cond = cond.nonzero_bool(&mut self.cx);
49 let accepted = if skip { cond.not(&mut self.cx) } else { cond };
50 let revert_data = if !skip {
51 SymReturnData::from_concrete_bytes(&mut self.cx, MAGIC_ASSUME.to_vec())
52 } else if state.call_depth == 0 {
53 let mut payload = MAGIC_SKIP.to_vec();
54 if selector == skip_1Call::SELECTOR {
55 let reason = read_abi_string_arg(
56 &mut self.cx,
57 memory,
58 in_offset + 4,
59 1,
60 "symbolic vm.skip reason",
61 )?;
62 payload.extend_from_slice(reason.as_bytes());
63 }
64 SymReturnData::from_concrete_bytes(&mut self.cx, payload)
65 } else {
66 error_string_return_data(&mut self.cx, "vm.skip: `skip` can only be used at test level")
67 };
68 let return_data = SymReturnData::empty(&mut self.cx);
69 match accepted.as_const() {
70 Some(true) => {
71 complete_cheatcode_call(&mut self.cx, state, out_offset, out_size, return_data)?;
72 }
73 Some(false) => {
74 revert_cheatcode_call(&mut self.cx, state, out_offset, out_size, revert_data)?;
75 }
76 None => {
77 let (accepted_seed_models, rejected_seed_models) =
78 state.split_corpus_seed_models(&accepted);
79 let mut accepted_state = state.clone();
80 accepted_state.constraints.push(accepted.clone());
81 accepted_state.set_corpus_seed_models(accepted_seed_models);
82 accepted_state.defer_feasibility_check();
83 complete_cheatcode_call(
84 &mut self.cx,
85 &mut accepted_state,
86 out_offset.clone(),
87 out_size,
88 return_data,
89 )?;
90 worklist.push_back(accepted_state);
91 state.constraints.push(accepted.not(&mut self.cx));
94 state.set_corpus_seed_models(rejected_seed_models);
95 state.defer_feasibility_check();
96 revert_cheatcode_call(&mut self.cx, state, out_offset, out_size, revert_data)?;
97 }
98 }
99 Ok(Some(StepOutcome::Continue))
100 }
101
102 pub(super) fn solver_upper_bound_usize(
103 &mut self,
104 state: &PathState,
105 expr: &SymExpr,
106 max: usize,
107 reason: &'static str,
108 ) -> Result<usize, SymbolicError> {
109 if let Some(bound) =
110 state.upper_bound_usize(&mut self.cx, expr).filter(|bound| *bound <= max)
111 {
112 return Ok(bound);
113 }
114 let mut above_max = state.constraints.clone();
115 above_max.push(SymBoolExpr::cmp_word_const(
116 &mut self.cx,
117 SymCmpOp::Ugt,
118 expr,
119 U256::from(max),
120 ));
121 if self.is_sat_with_state(state, &above_max)? {
122 return Err(SymbolicError::Unsupported(reason));
123 }
124
125 let mut low = 0usize;
126 let mut high = max;
127 while low < high {
128 let mid = low + (high - low) / 2;
129 let mut above_mid = state.constraints.clone();
130 above_mid.push(SymBoolExpr::cmp_word_const(
131 &mut self.cx,
132 SymCmpOp::Ugt,
133 expr,
134 U256::from(mid),
135 ));
136 if self.is_sat_with_state(state, &above_mid)? {
137 low = mid + 1;
138 } else {
139 high = mid;
140 }
141 }
142 Ok(low)
143 }
144
145 pub(super) fn assume_expr_at_least(
146 &mut self,
147 state: &mut PathState,
148 expr: &SymExpr,
149 min: usize,
150 ) -> Result<bool, SymbolicError> {
151 let condition =
152 SymBoolExpr::cmp_word_const(&mut self.cx, SymCmpOp::Uge, expr, U256::from(min));
153 match condition.as_const() {
154 Some(value) => Ok(value),
155 None => {
156 let mut constraints = state.constraints.clone();
157 constraints.push(condition);
158 if self.is_sat_with_state(state, &constraints)? {
159 state.constraints = constraints;
160 Ok(true)
161 } else {
162 Ok(false)
163 }
164 }
165 }
166 }
167
168 pub(super) fn proves_expr_at_least(
170 &mut self,
171 state: &PathState,
172 expr: &SymExpr,
173 min: usize,
174 ) -> Result<bool, SymbolicError> {
175 if state.lower_bound_usize(expr) >= min {
176 return Ok(true);
177 }
178
179 let mut below_min = state.constraints.clone();
180 below_min.push(SymBoolExpr::cmp_word_const(
181 &mut self.cx,
182 SymCmpOp::Ult,
183 expr,
184 U256::from(min),
185 ));
186 Ok(!self.is_sat_with_state(state, &below_min)?)
187 }
188
189 pub(super) fn constrained_word_with_solver(
191 &mut self,
192 state: &PathState,
193 expr: &SymExpr,
194 ) -> Result<Option<U256>, SymbolicError> {
195 if let Some(value) = state.constrained_word(&mut self.cx, expr) {
196 return Ok(Some(value));
197 }
198 if !self.symbolic_gas() && expr.contains_gasleft() {
199 return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
200 }
201
202 let replayable_storage = state.world.replay_storage_symbols();
203 let model = self.solver.model_with_replayable_storage(
204 &mut self.cx,
205 &state.constraints,
206 &replayable_storage,
207 )?;
208 let value = expr.eval_model(&model)?;
209 let differs = SymBoolExpr::eq_word_const(&mut self.cx, expr, value).not(&mut self.cx);
210 let mut constraints = state.constraints.clone();
211 constraints.push(differs);
212 if self.is_sat_with_state(state, &constraints)? { Ok(None) } else { Ok(Some(value)) }
213 }
214
215 pub(super) fn validate_symbolic_integer_bits(
217 bits: U256,
218 context: &'static str,
219 ) -> Result<(), SymbolicError> {
220 if bits <= U256::from(256) { Ok(()) } else { Err(SymbolicError::Unsupported(context)) }
221 }
222
223 pub(super) fn bound_cheatcode_if_needed(
228 &mut self,
229 state: &mut PathState,
230 worklist: &mut VecDeque<PathState>,
231 selector: [u8; 4],
232 in_offset: usize,
233 out_offset: SymExpr,
234 out_size: &BoundedCopySize,
235 ) -> Result<Option<StepOutcome>, SymbolicError> {
236 let signed = match selector {
237 bound_0Call::SELECTOR => false,
238 bound_1Call::SELECTOR => true,
239 _ => return Ok(None),
240 };
241 let args_offset = in_offset + 4;
242 let value = read_abi_word_arg(&mut self.cx, &state.memory, args_offset, 0)?;
243 let min = read_abi_word_arg(&mut self.cx, &state.memory, args_offset, 1)?;
244 let max = read_abi_word_arg(&mut self.cx, &state.memory, args_offset, 2)?;
245 let (Some(min_word), Some(max_word)) = (min.as_const(), max.as_const()) else {
246 return Err(SymbolicError::Unsupported("symbolic vm.bound range"));
247 };
248 let order = |a: &U256, b: &U256| {
249 if signed { I256::from_raw(*a).cmp(&I256::from_raw(*b)) } else { a.cmp(b) }
250 };
251
252 let range_conditions = |cx: &mut SymCx, word: &SymExpr, as_consts: bool| {
254 let cmp = |cx: &mut SymCx, op, bound| {
255 if as_consts {
256 SymBoolExpr::cmp_word_const(cx, op, word, bound)
257 } else {
258 let bound = SymExpr::constant(cx, bound);
259 SymBoolExpr::cmp_word_expr(cx, op, word, bound)
260 }
261 };
262 if signed {
263 let below_min = cmp(cx, SymCmpOp::Slt, min_word).not(cx);
264 let above_max = cmp(cx, SymCmpOp::Sgt, max_word).not(cx);
265 [below_min, above_max]
266 } else {
267 [cmp(cx, SymCmpOp::Uge, min_word), cmp(cx, SymCmpOp::Ule, max_word)]
268 }
269 };
270 let out_of_range = if order(&min_word, &max_word).is_lt() {
271 let in_range = range_conditions(&mut self.cx, &value, false);
272 SymBoolExpr::and(&mut self.cx, in_range.into()).not(&mut self.cx)
273 } else {
274 SymBoolExpr::constant(&mut self.cx, true)
275 };
276 if self.fork_cheatcode_revert(
277 state,
278 worklist,
279 out_of_range,
280 &out_offset,
281 out_size,
282 |this, reverted| this.bound_revert_data(reverted, &value, min_word, max_word, signed),
283 )? {
284 return Ok(Some(StepOutcome::Continue));
285 }
286
287 let bounded =
288 state.fresh_word(&mut self.cx, if signed { "vmBoundInt" } else { "vmBoundUint" });
289 state.constraints.extend(range_conditions(&mut self.cx, &bounded, true));
290 let same_value = SymBoolExpr::eq(&mut self.cx, bounded.clone(), value);
291 state.constraints.push(same_value.not(&mut self.cx));
292 let return_data = SymReturnData::from_words(&mut self.cx, vec![bounded]);
293 complete_cheatcode_call(&mut self.cx, state, out_offset, out_size, return_data)?;
294 Ok(Some(StepOutcome::Continue))
295 }
296
297 fn bound_revert_data(
298 &mut self,
299 state: &PathState,
300 value: &SymExpr,
301 min: U256,
302 max: U256,
303 signed: bool,
304 ) -> SymReturnData {
305 let Some(value) = state.constrained_word(&mut self.cx, value) else {
306 self.defer_incomplete("symbolic vm.bound revert payload");
309 return error_string_return_data(
310 &mut self.cx,
311 "vm.bound: cannot bound symbolic value in range",
312 );
313 };
314 let message = if signed {
315 format!(
316 "vm.bound: cannot bound {} in [{}, {}] range",
317 I256::from_raw(value),
318 I256::from_raw(min),
319 I256::from_raw(max)
320 )
321 } else {
322 format!("vm.bound: cannot bound {value} in [{min}, {max}] range")
323 };
324 error_string_return_data(&mut self.cx, &message)
325 }
326}