Skip to main content

foundry_evm_symbolic/executor/
invariant.rs

1use super::*;
2
3fn record_candidate_limitation(
4    limitation: &mut Option<SymbolicInvariantSearchLimitation>,
5    error: SymbolicError,
6) -> bool {
7    let search_exhausted = matches!(
8        error,
9        SymbolicError::Timeout(_) | SymbolicError::Solver(_) | SymbolicError::SolverQueryLimit(_)
10    );
11    if search_exhausted {
12        *limitation = Some(error.into());
13    } else {
14        limitation.get_or_insert_with(|| error.into());
15    }
16    search_exhausted
17}
18
19impl SymbolicExecutor {
20    pub(super) fn execute_invariant_check(
21        &mut self,
22        executor: &ExecutorView<'_>,
23        state: &PathState,
24        invariant_address: Address,
25        invariant: &Function,
26        after_invariant: Option<&Function>,
27        completed_paths: &mut usize,
28    ) -> Result<Vec<InvariantCheckOutcome>, SymbolicError> {
29        let mut call =
30            self.prepare_invariant_call(executor, state.clone(), invariant_address, invariant)?;
31
32        let mut checked = Vec::new();
33        while let Some(mut outcome) =
34            self.execute_sequence_call_next(executor, &mut call, completed_paths)?
35        {
36            if !matches!(outcome.status, CallStatus::Success) {
37                return Ok(vec![InvariantCheckOutcome { failed: true, state: outcome.state }]);
38            }
39
40            let Some(after_invariant) = after_invariant else {
41                checked.push(InvariantCheckOutcome { failed: false, state: outcome.state });
42                continue;
43            };
44
45            // Concrete invariant checks do not commit predicate state before invoking
46            // `afterInvariant`. Retain the predicate's path state while restoring the unchanged
47            // post-handler world.
48            let mut after_state = state.clone();
49            after_state.take_noncommitting_check_state(&mut outcome.state);
50            let mut after_call = self.prepare_invariant_call(
51                executor,
52                after_state,
53                invariant_address,
54                after_invariant,
55            )?;
56            while let Some(after_outcome) =
57                self.execute_sequence_call_next(executor, &mut after_call, completed_paths)?
58            {
59                let failed = !matches!(after_outcome.status, CallStatus::Success);
60                let checked_outcome = InvariantCheckOutcome { failed, state: after_outcome.state };
61                if failed {
62                    return Ok(vec![checked_outcome]);
63                }
64                checked.push(checked_outcome);
65            }
66        }
67        Ok(checked)
68    }
69
70    fn prepare_invariant_call(
71        &mut self,
72        executor: &ExecutorView<'_>,
73        mut state: PathState,
74        invariant_address: Address,
75        invariant: &Function,
76    ) -> Result<SequenceCall, SymbolicError> {
77        state.invariant_predicate = true;
78        let calldata = SymbolicCalldata::selector_only(&mut self.cx, invariant)?;
79        let call_data = calldata.call_data(&mut self.cx);
80        let constraints = calldata.into_constraints();
81        // Forge calls invariant predicates and `afterInvariant` from `CALLER`, whatever sender
82        // the test configures.
83        self.prepare_sequence_call(
84            executor,
85            state,
86            invariant_address,
87            CALLER,
88            call_data,
89            constraints,
90        )
91    }
92
93    pub(super) fn search_invariant_candidates_inner(
94        &mut self,
95        input: &SymbolicInvariantCandidateInput<'_>,
96        candidates: &mut Vec<SymbolicInvariantCandidate>,
97        limitation: &mut Option<SymbolicInvariantSearchLimitation>,
98    ) -> Result<(), SymbolicError> {
99        if input.invariants.is_empty() {
100            return Err(SymbolicError::Unsupported("symbolic invariant has no predicates"));
101        }
102        let mut completed_paths = 0;
103
104        let mut initial_state = PathState::empty(
105            &mut self.cx,
106            input.invariant_address,
107            input.handler_sender,
108            input.ffi_enabled,
109        );
110        initial_state.apply_executor_env(&mut self.cx, &input.executor)?;
111        initial_state.world.set_storage_layout(self.config.storage_layout);
112        self.folded_slots = FoldedSlots::register(&mut self.cx, &input.executor, self.deadline);
113
114        let calldatas = SymbolicCalldata::variants_with_prefix(
115            &input.target.function,
116            &self.config,
117            &mut self.cx,
118            "frontier_handler",
119        )?;
120        'variants: for calldata in calldatas {
121            self.check_timeout()?;
122            let step = SequenceStepTemplate {
123                sender: input.handler_sender,
124                address: input.target.address,
125                contract_name: input.target.contract_name.clone(),
126                function: input.target.function.clone(),
127                calldata,
128            };
129            let call_data = step.calldata.call_data(&mut self.cx);
130            let constraints = step.calldata.constraints().to_vec();
131            let mut handler = match self.prepare_sequence_call(
132                &input.executor,
133                initial_state.clone(),
134                input.target.address,
135                input.handler_sender,
136                call_data,
137                constraints,
138            ) {
139                Ok(call) => call,
140                Err(error) => {
141                    if record_candidate_limitation(limitation, error) {
142                        break;
143                    }
144                    continue;
145                }
146            };
147            let mut stop_after_handler = false;
148            loop {
149                let outcome = match self.execute_sequence_call_next(
150                    &input.executor,
151                    &mut handler,
152                    &mut completed_paths,
153                ) {
154                    Ok(Some(outcome)) => outcome,
155                    Ok(None) => break,
156                    Err(error) => {
157                        stop_after_handler = record_candidate_limitation(limitation, error);
158                        break;
159                    }
160                };
161                if !matches!(outcome.status, CallStatus::Success) {
162                    continue;
163                }
164                let handler_state = outcome.state;
165                for (invariant_idx, invariant) in input.invariants.iter().enumerate() {
166                    self.check_timeout()?;
167                    let mut predicate = match self.prepare_invariant_call(
168                        &input.executor,
169                        handler_state.clone(),
170                        input.invariant_address,
171                        invariant,
172                    ) {
173                        Ok(call) => call,
174                        Err(error) => {
175                            if record_candidate_limitation(limitation, error) {
176                                break 'variants;
177                            }
178                            continue;
179                        }
180                    };
181                    let mut stop_after_predicate = false;
182                    let mut candidate_states = Vec::new();
183                    loop {
184                        let mut predicate_outcome = match self.execute_sequence_call_next(
185                            &input.executor,
186                            &mut predicate,
187                            &mut completed_paths,
188                        ) {
189                            Ok(Some(outcome)) => outcome,
190                            Ok(None) => break,
191                            Err(error) => {
192                                stop_after_predicate =
193                                    record_candidate_limitation(limitation, error);
194                                break;
195                            }
196                        };
197                        if !matches!(predicate_outcome.status, CallStatus::Success) {
198                            candidate_states.push(predicate_outcome.state);
199                            continue;
200                        }
201                        let Some(after_invariant) = input.after_invariant else {
202                            continue;
203                        };
204
205                        // Concrete invariant checks do not commit predicate state before invoking
206                        // `afterInvariant`. Retain the predicate's path state while restoring the
207                        // unchanged post-handler world.
208                        let mut after_state = handler_state.clone();
209                        after_state.take_noncommitting_check_state(&mut predicate_outcome.state);
210                        let mut after = match self.prepare_invariant_call(
211                            &input.executor,
212                            after_state,
213                            input.invariant_address,
214                            after_invariant,
215                        ) {
216                            Ok(call) => call,
217                            Err(error) => {
218                                if record_candidate_limitation(limitation, error) {
219                                    stop_after_predicate = true;
220                                    break;
221                                }
222                                continue;
223                            }
224                        };
225                        loop {
226                            match self.execute_sequence_call_next(
227                                &input.executor,
228                                &mut after,
229                                &mut completed_paths,
230                            ) {
231                                Ok(Some(outcome)) => {
232                                    if !matches!(outcome.status, CallStatus::Success) {
233                                        candidate_states.push(outcome.state);
234                                    }
235                                }
236                                Ok(None) => break,
237                                Err(error) => {
238                                    if record_candidate_limitation(limitation, error) {
239                                        stop_after_predicate = true;
240                                    }
241                                    break;
242                                }
243                            }
244                        }
245                        if stop_after_predicate {
246                            break;
247                        }
248                    }
249
250                    for state in candidate_states {
251                        match self.materialize_sequence(std::slice::from_ref(&step), &state) {
252                            Ok((mut sequence, storage)) => {
253                                let step =
254                                    sequence.pop().expect("one handler template produces one step");
255                                candidates.push(SymbolicInvariantCandidate {
256                                    invariant_idx,
257                                    step,
258                                    storage,
259                                });
260                            }
261                            Err(error) => {
262                                if record_candidate_limitation(limitation, error) {
263                                    break 'variants;
264                                }
265                            }
266                        }
267                    }
268                    if stop_after_predicate {
269                        break 'variants;
270                    }
271                }
272            }
273            if stop_after_handler {
274                break;
275            }
276        }
277
278        Ok(())
279    }
280
281    pub(super) fn prepare_sequence_call(
282        &mut self,
283        executor: &ExecutorView<'_>,
284        mut state: PathState,
285        target: Address,
286        sender: Address,
287        calldata: SymCalldata,
288        constraints: Vec<SymBoolExpr>,
289    ) -> Result<SequenceCall, SymbolicError> {
290        state.world.clear_transaction_scoped_state(&mut self.cx);
291        state.mapping_hook_keccak_preimages.clear();
292        let code = state.world.extcode(&mut self.cx, executor, target)?;
293        state.call_depth = 0;
294        state.call_depth_base = 0;
295        state.assertion_failed = false;
296        // Like Forge, expectations end with the root call; only a met count 0 one can remain.
297        state.expected_emit = None;
298        // Each sequence call runs with a fresh block hash overlay.
299        state.block.block_hashes.clear();
300        state.origin = sender;
301        state.origin_word = SymExpr::constant(&mut self.cx, address_word(sender));
302        // Like Forge, a prank applies only to calls from the contract that set it.
303        let prank = std::mem::take(&mut state.prank);
304        if prank.has_active() {
305            state.root_pranks.insert(state.address, prank);
306        }
307        state.prank = state.root_pranks.remove(&target).unwrap_or_default();
308        let callvalue = SymExpr::zero(&mut self.cx);
309        state.frame =
310            CallFrame::new(&mut self.cx, target, target, sender, callvalue, false, calldata);
311        state.constraints.extend(constraints);
312        Ok(SequenceCall {
313            code,
314            worklist: VecDeque::from([state]),
315            deferred_worklist: VecDeque::new(),
316        })
317    }
318
319    pub(super) fn execute_sequence_call_next(
320        &mut self,
321        executor: &ExecutorView<'_>,
322        call: &mut SequenceCall,
323        completed_paths: &mut usize,
324    ) -> Result<Option<CallOutcome>, SymbolicError> {
325        if call.worklist.is_empty() && call.deferred_worklist.is_empty() {
326            return Ok(None);
327        }
328        let mut outcomes = self.execute_call_path_batch(
329            executor,
330            &call.code,
331            &mut call.worklist,
332            &mut call.deferred_worklist,
333            completed_paths,
334            CallPathKind::Sequence,
335        )?;
336        debug_assert!(outcomes.len() <= 1);
337        Ok(outcomes.pop())
338    }
339
340    pub(super) fn materialize_sequence(
341        &mut self,
342        steps: &[SequenceStepTemplate],
343        state: &PathState,
344    ) -> Result<(Vec<SymbolicInvariantStep>, Vec<SymbolicStorageAssignment>), SymbolicError> {
345        // Invariant replay does not answer `svm.*` calls, so it cannot reproduce such a sequence.
346        if !state.svm_returns.is_empty() {
347            return Err(SymbolicError::Unsupported("symbolic invariant replay of svm values"));
348        }
349        let model = self.witness_model(state)?;
350        let sequence = steps
351            .iter()
352            .map(|step| {
353                let args = step.calldata.model_to_args(&mut self.cx, &model)?;
354                let calldata = Bytes::from(step.function.abi_encode_input(&args)?);
355                Ok(SymbolicInvariantStep {
356                    sender: step.sender,
357                    address: step.address,
358                    contract_name: step.contract_name.clone(),
359                    function_name: step.function.name.clone(),
360                    signature: step.function.signature(),
361                    args,
362                    calldata,
363                })
364            })
365            .collect::<Result<Vec<_>, SymbolicError>>()?;
366        let storage = state.world.replay_storage_assignments(&model, false)?;
367        Ok((sequence, storage))
368    }
369}