Skip to main content

foundry_evm_symbolic/executor/
mod.rs

1use super::{abi::*, runtime::*, *};
2use foundry_evm::{
3    constants::{MAGIC_ASSUME, MAGIC_SKIP},
4    inspectors::cheatcodes::{DUMMY_CALL_OUTPUT, DUMMY_CREATE_ADDRESS},
5};
6
7mod calls;
8mod cheatcodes;
9mod constraints;
10mod create;
11mod equivalence;
12mod invariant;
13mod opcodes;
14mod run;
15
16#[derive(Debug)]
17struct CallOutcome {
18    status: CallStatus,
19    state: PathState,
20}
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23enum CallStatus {
24    Success,
25    Revert,
26    ExceptionalHalt,
27    Failure,
28}
29
30enum JoinedCallOutcome {
31    ExpectedRevert(PathState),
32    /// A successful call; `unmet_expected_revert` is the reason the caller must see as a revert
33    /// instead.
34    Success {
35        parent: PathState,
36        child: PathState,
37        unmet_expected_revert: Option<&'static str>,
38    },
39    Revert {
40        parent: PathState,
41        child: PathState,
42    },
43    ExceptionalHalt(PathState),
44    Failure(PathState),
45}
46
47#[derive(Clone, Copy)]
48enum CallPathKind {
49    External,
50    Sequence,
51}
52
53enum CallPathOpcode {
54    Execute(u8),
55    Halt,
56    Discard,
57}
58
59pub(super) struct FeasiblePath {
60    state: PathState,
61    from_deferred: bool,
62}
63
64#[derive(Debug)]
65struct SequencePath {
66    state: PathState,
67    steps: Vec<SequenceStepTemplate>,
68}
69
70#[derive(Debug)]
71struct SequenceCall {
72    code: SymCode,
73    worklist: VecDeque<PathState>,
74    deferred_worklist: VecDeque<PathState>,
75}
76
77#[derive(Clone, Debug)]
78struct SequenceStepTemplate {
79    sender: Address,
80    address: Address,
81    contract_name: Option<String>,
82    function: Function,
83    calldata: SymbolicCalldata,
84}
85
86#[derive(Debug)]
87struct InvariantCheckOutcome {
88    failed: bool,
89    state: PathState,
90}
91
92impl SymbolicExecutor {
93    pub(super) fn pop_next_path(&self, paths: &mut VecDeque<PathState>) -> Option<PathState> {
94        match self.config.exploration_order {
95            SymbolicExplorationOrder::Bfs => paths.pop_front(),
96            SymbolicExplorationOrder::Dfs => paths.pop_back(),
97        }
98    }
99
100    pub(super) fn pop_next_feasible_path(
101        &mut self,
102        paths: &mut VecDeque<PathState>,
103        deferred_paths: &mut VecDeque<PathState>,
104        deferred_mode: DeferredPathMode,
105    ) -> Result<Option<FeasiblePath>, SymbolicError> {
106        loop {
107            while let Some(mut state) = self.pop_next_path(paths) {
108                if state.take_deferred_feasibility_check() {
109                    let replayable_storage = state.world.replay_storage_symbols();
110                    match self.solver.branch_feasibility_with_replayable_storage(
111                        &mut self.cx,
112                        &state.constraints,
113                        &replayable_storage,
114                    ) {
115                        Ok(BranchFeasibility::Sat) => {}
116                        Ok(BranchFeasibility::Unsat) => continue,
117                        Ok(BranchFeasibility::NeedsSolver) => {
118                            if matches!(deferred_mode, DeferredPathMode::Skip) {
119                                self.defer_hard_arithmetic();
120                                continue;
121                            }
122                            trace!("queued hard arithmetic branch for deferred SMT solving");
123                            deferred_paths.push_back(state);
124                            continue;
125                        }
126                        Err(SymbolicError::SolverUnknown) => {
127                            self.defer_solver_unknown();
128                            continue;
129                        }
130                        Err(err) => return Err(err),
131                    }
132                }
133                return Ok(Some(FeasiblePath { state, from_deferred: false }));
134            }
135
136            let Some(state) = self.pop_next_path(deferred_paths) else {
137                return Ok(None);
138            };
139            if self.deadline.is_none() {
140                self.deadline = self
141                    .config
142                    .timeout
143                    .filter(|seconds| *seconds > 0)
144                    .map(|seconds| Instant::now() + Duration::from_secs(seconds.into()));
145            }
146            self.check_timeout()?;
147            trace!("escalating deferred hard arithmetic branch to SMT solver");
148            match self.is_sat_with_state(&state, &state.constraints) {
149                Ok(true) => return Ok(Some(FeasiblePath { state, from_deferred: true })),
150                Ok(false) => {}
151                Err(SymbolicError::SolverUnknown) => self.defer_solver_unknown(),
152                Err(err) => return Err(err),
153            }
154        }
155    }
156
157    fn join_call_outcome(
158        &mut self,
159        executor: &ExecutorView<'_>,
160        state: &PathState,
161        failure_world: &SymbolicWorld,
162        mut outcome: CallOutcome,
163        failed_callee: Option<Address>,
164        assume_no_revert: Option<&AssumeNoRevert>,
165    ) -> Result<JoinedCallOutcome, SymbolicError> {
166        let mut parent = state.clone();
167        parent.first_failed_callee =
168            parent.first_failed_callee.or(outcome.state.first_failed_callee);
169        parent.first_reverted_callee =
170            parent.first_reverted_callee.or(outcome.state.first_reverted_callee);
171        parent.take_call_outcome_state(&mut outcome.state);
172        // Like Forge's `call_end`, a frame that ends with its own `vm.expectRevert` still pending
173        // reverts. If a deeper revert already matched a counted expectation, Forge's depth check
174        // passed and the reason is the unmet one. A frame that returned keeps its state, like a
175        // call that succeeds under the caller's `vm.expectRevert`; in internal expect-revert mode
176        // it returns and leaves the expectation pending for the caller.
177        if let Some(expected) = outcome.state.expected_revert.take() {
178            const DEPTH_REASON: &str =
179                "call didn't revert at a lower depth than cheatcode call depth";
180            match outcome.status {
181                // Like Forge's `create_end`, a CREATE always settles the expectation.
182                CallStatus::Success
183                    if executor.internal_expect_revert && !outcome.state.frame.is_constructor =>
184                {
185                    // The reverter history belongs to the expectation, which the child reset.
186                    parent.expected_revert = Some(expected);
187                    parent.first_failed_callee = outcome.state.first_failed_callee;
188                    return Ok(JoinedCallOutcome::Success {
189                        parent,
190                        child: outcome.state,
191                        unmet_expected_revert: None,
192                    });
193                }
194                CallStatus::Success => {
195                    let reason = if expected.matched_any()
196                        || expected.deeper_frame_ran()
197                        || executor.internal_expect_revert
198                    {
199                        "next call did not revert as expected"
200                    } else {
201                        DEPTH_REASON
202                    };
203                    return Ok(JoinedCallOutcome::Success {
204                        parent,
205                        child: outcome.state,
206                        unmet_expected_revert: Some(reason),
207                    });
208                }
209                // A frame ran deeper, so Forge's depth check passes and a matching revert is
210                // handled like a failed call below. A mismatch reverts with Forge's
211                // `CheatcodeError`, which the caller can catch. Like Forge, `vm.assumeNoRevert`
212                // handles the revert first.
213                CallStatus::Revert
214                    if expected.deeper_frame_ran() && parent.expected_revert.is_none() =>
215                {
216                    // Forge halts a constructor whose runtime is rejected, a status this arm does
217                    // not model.
218                    if outcome.state.frame.is_constructor {
219                        return Err(SymbolicError::Unsupported(
220                            "symbolic vm.expectRevert pending in a constructor",
221                        ));
222                    }
223                    let reverter = expected.reverted_by(
224                        failed_callee,
225                        outcome.state.first_failed_callee.or(failed_callee),
226                    );
227                    let constraints = parent.constraints.len();
228                    if assume_no_revert.is_some()
229                        || self.expected_revert_matches(
230                            &mut parent,
231                            &expected,
232                            reverter,
233                            &outcome.state.frame.return_data,
234                        )?
235                    {
236                        parent.expected_revert = Some(expected);
237                        parent.first_failed_callee = outcome.state.first_failed_callee;
238                    } else if parent.constraints.len() != constraints {
239                        return Err(SymbolicError::Unsupported(
240                            "ambiguous symbolic vm.expectRevert match",
241                        ));
242                    } else {
243                        const REASON: &str = "symbolic vm.expectRevert mismatch data";
244                        let return_data = &outcome.state.frame.return_data;
245                        if return_data.len_word.as_const().is_none() {
246                            return Err(SymbolicError::Unsupported(REASON));
247                        }
248                        let retdata = return_data.read_concrete(&mut self.cx, REASON)?.into();
249                        let no_contracts = None;
250                        let known_contracts = executor
251                            .cheatcodes
252                            .map_or(&no_contracts, |cheats| &cheats.config.available_artifacts);
253                        let error = expected
254                            .mismatch_error(reverter, &retdata, known_contracts)
255                            .ok_or(SymbolicError::Unsupported(REASON))?;
256                        outcome.state.frame.return_data =
257                            SymReturnData::from_concrete_bytes(&mut self.cx, error.abi_encode());
258                    }
259                }
260                CallStatus::Revert
261                    if !executor.internal_expect_revert && !expected.matched_any() =>
262                {
263                    outcome.state.frame.return_data =
264                        error_string_return_data(&mut self.cx, DEPTH_REASON);
265                }
266                // Forge's depth check also passes for a halt, which it matches like a revert.
267                CallStatus::ExceptionalHalt if expected.deeper_frame_ran() => {
268                    return Err(SymbolicError::Unsupported(
269                        "symbolic vm.expectRevert pending at an exceptional halt",
270                    ));
271                }
272                CallStatus::Revert | CallStatus::ExceptionalHalt | CallStatus::Failure => {}
273            }
274        }
275        if let Some(assumption) = &mut parent.assume_no_revert_next_call {
276            // CREATE leaves the assumption pending, but nested CALL reverts still establish its
277            // first reverter. The CREATE revert itself is not a call_end event.
278            assumption.reverted_by = assumption.reverted_by.or(outcome.state.first_reverted_callee);
279        }
280        if outcome.state.frame.is_constructor
281            && let Some(child_assumption) = outcome.state.assume_no_revert_next_call.take()
282        {
283            if parent.assume_no_revert_next_call.is_some() || assume_no_revert.is_some() {
284                return Err(SymbolicError::Unsupported("symbolic vm.assumeNoRevert overlap"));
285            }
286            parent.assume_no_revert_next_call = Some(child_assumption);
287        }
288        if !matches!(outcome.status, CallStatus::Success) {
289            parent.discard_failed_call_logs(
290                state.recorded_logs.as_ref().map_or(0, Vec::len),
291                state.recorded_logs_generation,
292            );
293            parent.world = failure_world.clone();
294            parent.world.take_snapshots_from(&mut outcome.state.world);
295            // The path keeps the failed call's constraints, so keep its replay metadata too,
296            // including the symbolic address aliases the replayed writes resolve through.
297            parent.world.merge_replay_metadata_from(&outcome.state.world);
298            parent.replay_persistent_writes(
299                &mut self.cx,
300                executor,
301                state.persistent_writes.len(),
302            )?;
303        }
304        // Forge keeps the changes a failed call makes to a count 0 `expectEmit`, such as declaring,
305        // filling, or dropping it, which the symbolic expectation does not follow, so report them
306        // as unsupported.
307        if !matches!(outcome.status, CallStatus::Success)
308            && outcome.state.expected_emit != state.expected_emit
309            && [&outcome.state.expected_emit, &state.expected_emit]
310                .into_iter()
311                .flatten()
312                .any(ExpectedEmit::is_forbidden)
313        {
314            return Err(SymbolicError::Unsupported(
315                "symbolic vm.expectEmit count 0 across a failed call",
316            ));
317        }
318
319        // Like Forge, a revert under `vm.assumeNoRevert` skips `vm.expectRevert`, and a matching
320        // revert returns `FOUNDRY::ASSUME`, which discards the run only if it reaches the top. Its
321        // filters match the first call that reverted in the call, not the callee.
322        if let Some(assumption) = assume_no_revert
323            && matches!(outcome.status, CallStatus::Revert)
324        {
325            let reverter = assumption
326                .reverted_by
327                .or(outcome.state.first_reverted_callee)
328                .unwrap_or(outcome.state.address);
329            if self.assume_no_revert_matches(
330                &parent,
331                assumption,
332                reverter,
333                &outcome.state.frame.return_data,
334            )? {
335                outcome.state.frame.return_data =
336                    SymReturnData::from_concrete_bytes(&mut self.cx, MAGIC_ASSUME.to_vec());
337            }
338            return Ok(JoinedCallOutcome::Revert { parent, child: outcome.state });
339        }
340        // Like Forge, the first failure inside the call precedes the call's own failure, which
341        // `vm.assumeNoRevert` handles before it is recorded.
342        parent.first_failed_callee = parent.first_failed_callee.or(failed_callee);
343
344        if let Some(mut expected) = parent.expected_revert.clone() {
345            // Like Forge, a call that succeeds under `vm.expectRevert` keeps its state, but the
346            // caller sees a `CheatcodeError` revert. A revert with the wrong reason fails the path.
347            if matches!(outcome.status, CallStatus::Success) && !executor.internal_expect_revert {
348                parent.expected_revert = None;
349                return Ok(JoinedCallOutcome::Success {
350                    parent,
351                    child: outcome.state,
352                    unmet_expected_revert: Some("next call did not revert as expected"),
353                });
354            }
355            match outcome.status {
356                // Like Forge's internal expect-revert mode, a call that succeeds leaves the
357                // expectation pending for a later revert.
358                CallStatus::Success => {
359                    return Ok(JoinedCallOutcome::Success {
360                        parent,
361                        child: outcome.state,
362                        unmet_expected_revert: None,
363                    });
364                }
365                CallStatus::Revert | CallStatus::ExceptionalHalt | CallStatus::Failure => {
366                    let reverter = expected.reverted_by(failed_callee, parent.first_failed_callee);
367                    if !self.expected_revert_matches(
368                        &mut parent,
369                        &expected,
370                        reverter,
371                        &outcome.state.frame.return_data,
372                    )? {
373                        return Ok(JoinedCallOutcome::Failure(parent));
374                    }
375                    if expected.consume_one() {
376                        parent.expected_revert = None;
377                    } else {
378                        parent.expected_revert = Some(expected);
379                    }
380                    return Ok(JoinedCallOutcome::ExpectedRevert(parent));
381                }
382            }
383        }
384
385        Ok(match outcome.status {
386            CallStatus::Success => JoinedCallOutcome::Success {
387                parent,
388                child: outcome.state,
389                unmet_expected_revert: None,
390            },
391            CallStatus::Revert => JoinedCallOutcome::Revert { parent, child: outcome.state },
392            CallStatus::ExceptionalHalt => JoinedCallOutcome::ExceptionalHalt(parent),
393            CallStatus::Failure => JoinedCallOutcome::Failure(parent),
394        })
395    }
396
397    fn resume_parent_paths(
398        &self,
399        state: &mut PathState,
400        worklist: &mut VecDeque<PathState>,
401        mut parents: VecDeque<PathState>,
402    ) -> StepOutcome {
403        let Some(first) = self.pop_next_path(&mut parents) else {
404            return StepOutcome::AssumeRejected;
405        };
406        *state = first;
407        worklist.extend(parents);
408        StepOutcome::Continue
409    }
410
411    fn execute_call_path_batch(
412        &mut self,
413        executor: &ExecutorView<'_>,
414        code: &SymCode,
415        worklist: &mut VecDeque<PathState>,
416        deferred_worklist: &mut VecDeque<PathState>,
417        completed_paths: &mut usize,
418        kind: CallPathKind,
419    ) -> Result<Vec<CallOutcome>, SymbolicError> {
420        let mut outcomes = Vec::new();
421        let mut outcomes_before_deferred = None;
422        let path_limit = self.config.path_width() as usize;
423        let depth_limit = self.config.execution_depth() as usize;
424
425        loop {
426            // Let callers inspect a completed outcome before spending the remaining budget on a
427            // deferred sibling. A later proof pass reconstructs and drains all nested paths.
428            if matches!(kind, CallPathKind::Sequence) && !outcomes.is_empty() {
429                break;
430            }
431            if matches!(kind, CallPathKind::External)
432                && matches!(self.nested_deferred_mode, DeferredPathMode::Yield)
433                && outcomes_before_deferred.is_some_and(|count| outcomes.len() > count)
434            {
435                if !worklist.is_empty() || !deferred_worklist.is_empty() {
436                    self.defer_hard_arithmetic();
437                }
438                break;
439            }
440            let deferred_mode = match kind {
441                CallPathKind::Sequence => DeferredPathMode::Drain,
442                CallPathKind::External => self.nested_deferred_mode,
443            };
444            let Some(next) =
445                self.pop_next_feasible_path(worklist, deferred_worklist, deferred_mode)?
446            else {
447                break;
448            };
449            if next.from_deferred
450                && matches!(kind, CallPathKind::External)
451                && matches!(deferred_mode, DeferredPathMode::Yield)
452            {
453                outcomes_before_deferred = Some(outcomes.len());
454            }
455            let mut state = next.state;
456            if *completed_paths >= path_limit {
457                return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
458            }
459            if std::mem::take(&mut state.pending_storage_hook_revert) {
460                *completed_paths += 1;
461                outcomes.push(CallOutcome { status: CallStatus::Revert, state });
462                continue;
463            }
464            let _path_span = matches!(kind, CallPathKind::Sequence).then(|| {
465                trace_span!("symbolic_path", completed_paths, worklist_size = worklist.len())
466                    .entered()
467            });
468            if matches!(kind, CallPathKind::Sequence) {
469                trace!(completed_paths, worklist_size = worklist.len(), "exploring symbolic path");
470            }
471
472            loop {
473                self.check_timeout()?;
474                if state.depth >= depth_limit {
475                    return Err(SymbolicError::Unsupported("symbolic depth limit exceeded"));
476                }
477                state.depth += 1;
478
479                let op = match kind {
480                    CallPathKind::Sequence => match code.opcode(&mut self.cx, state.pc)? {
481                        Some(op) => CallPathOpcode::Execute(op),
482                        None => CallPathOpcode::Halt,
483                    },
484                    CallPathKind::External => match code.guarded_opcode(&mut self.cx, state.pc)? {
485                        GuardedOpcode::End => CallPathOpcode::Halt,
486                        GuardedOpcode::Concrete(op) => CallPathOpcode::Execute(op),
487                        GuardedOpcode::SymbolicSize { condition, opcode } => {
488                            let mut in_bounds_constraints = state.constraints.clone();
489                            in_bounds_constraints.push(condition.clone());
490                            let in_bounds_sat =
491                                self.is_sat_with_state(&state, &in_bounds_constraints)?;
492
493                            let mut out_of_bounds_constraints = state.constraints.clone();
494                            out_of_bounds_constraints.push(condition.not(&mut self.cx));
495                            if self.is_sat_with_state(&state, &out_of_bounds_constraints)? {
496                                if *completed_paths >= path_limit {
497                                    return Err(SymbolicError::Unsupported(
498                                        "symbolic path limit exceeded",
499                                    ));
500                                }
501                                let mut halted = state.clone();
502                                halted.constraints = out_of_bounds_constraints;
503                                halted.return_data = SymReturnData::empty(&mut self.cx);
504                                *completed_paths += 1;
505                                let status =
506                                    self.successful_call_status(executor, kind, &mut halted)?;
507                                outcomes.push(CallOutcome { status, state: halted });
508                            }
509
510                            if in_bounds_sat {
511                                state.constraints = in_bounds_constraints;
512                                CallPathOpcode::Execute(opcode)
513                            } else {
514                                CallPathOpcode::Discard
515                            }
516                        }
517                    },
518                };
519                let op = match op {
520                    CallPathOpcode::Execute(op) => op,
521                    CallPathOpcode::Halt => {
522                        if !self.completed_path_is_feasible(&mut state, StepOutcome::Halt)? {
523                            break;
524                        }
525                        if *completed_paths >= path_limit {
526                            return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
527                        }
528                        *completed_paths += 1;
529                        // Running past the end of code stops like STOP, with no output.
530                        state.return_data = SymReturnData::empty(&mut self.cx);
531                        let status = self.successful_call_status(executor, kind, &mut state)?;
532                        outcomes.push(CallOutcome { status, state });
533                        break;
534                    }
535                    CallPathOpcode::Discard => break,
536                };
537
538                let _step_span = matches!(kind, CallPathKind::Sequence)
539                    .then(|| trace_span!("symbolic_step", pc = state.pc, op).entered());
540                let outcome =
541                    self.step(executor, code, &mut state, &mut *worklist, completed_paths, op)?;
542                if !self.completed_path_is_feasible(&mut state, outcome)? {
543                    break;
544                }
545                match outcome {
546                    StepOutcome::Continue => {}
547                    StepOutcome::Halt => {
548                        if *completed_paths >= path_limit {
549                            return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
550                        }
551                        *completed_paths += 1;
552                        let status = self.successful_call_status(executor, kind, &mut state)?;
553                        outcomes.push(CallOutcome { status, state });
554                        break;
555                    }
556                    StepOutcome::Revert => {
557                        if *completed_paths >= path_limit {
558                            return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
559                        }
560                        *completed_paths += 1;
561                        let status = Self::failed_call_status(kind, &state, CallStatus::Revert);
562                        outcomes.push(CallOutcome { status, state });
563                        break;
564                    }
565                    StepOutcome::ExceptionalHalt => {
566                        if *completed_paths >= path_limit {
567                            return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
568                        }
569                        *completed_paths += 1;
570                        // An exceptional halt returns no output.
571                        state.return_data = SymReturnData::empty(&mut self.cx);
572                        let status =
573                            Self::failed_call_status(kind, &state, CallStatus::ExceptionalHalt);
574                        outcomes.push(CallOutcome { status, state });
575                        break;
576                    }
577                    StepOutcome::Failure => {
578                        if *completed_paths >= path_limit {
579                            return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
580                        }
581                        *completed_paths += 1;
582                        outcomes.push(CallOutcome { status: CallStatus::Failure, state });
583                        break;
584                    }
585                    StepOutcome::AssumeRejected | StepOutcome::Forked => break,
586                }
587            }
588        }
589
590        Ok(outcomes)
591    }
592
593    /// Like Forge, a sequence call that reverts still fails if an assertion failed in it.
594    const fn failed_call_status(
595        kind: CallPathKind,
596        state: &PathState,
597        status: CallStatus,
598    ) -> CallStatus {
599        if matches!(kind, CallPathKind::Sequence) && state.assertion_failed {
600            CallStatus::Failure
601        } else {
602            status
603        }
604    }
605
606    /// Like Forge, a sequence call fails if an expectation is unmet, an assertion failed, or the
607    /// global fail slot is set.
608    fn successful_call_status(
609        &mut self,
610        executor: &ExecutorView<'_>,
611        kind: CallPathKind,
612        state: &mut PathState,
613    ) -> Result<CallStatus, SymbolicError> {
614        if matches!(kind, CallPathKind::External)
615            || (state.expectations_satisfied()
616                && !state.assertion_failed
617                && !self.global_fail_slot_set(executor, state)?)
618        {
619            Ok(CallStatus::Success)
620        } else {
621            Ok(CallStatus::Failure)
622        }
623    }
624}