Skip to main content

foundry_evm_symbolic/
runtime.rs

1use super::{abi::*, *};
2
3mod address;
4mod bytes;
5mod calldata;
6mod cheatcodes;
7mod control;
8mod evm;
9mod executor_view;
10mod expr;
11mod folded_slots;
12mod memory;
13mod precompiles;
14mod solver;
15mod state;
16mod symbols;
17
18pub(crate) use address::*;
19pub(crate) use bytes::*;
20pub(crate) use calldata::*;
21pub(crate) use cheatcodes::*;
22pub(crate) use control::*;
23pub(crate) use evm::*;
24pub use executor_view::ExecutorView;
25pub(crate) use expr::*;
26pub(crate) use folded_slots::*;
27pub(crate) use memory::*;
28pub(crate) use precompiles::*;
29pub(crate) use solver::{BranchFeasibility, SmtLibSubprocessSolver};
30pub(crate) use state::*;
31pub(crate) use symbols::*;
32
33/// One comparison site from a fuzz branch frontier to target during symbolic execution.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct SymbolicBranchTarget {
36    /// Contract address where the comparison executed.
37    address: Address,
38    /// Program counter of the comparison opcode.
39    pc: usize,
40    /// Comparison opcode.
41    opcode: u8,
42    /// Concrete result observed by fuzzing. Symbolic execution targets the opposite result.
43    result: bool,
44}
45
46impl SymbolicBranchTarget {
47    pub const fn new(address: Address, pc: usize, opcode: u8, result: bool) -> Self {
48        Self { address, pc, opcode, result }
49    }
50
51    pub(crate) const fn result(self) -> bool {
52        self.result
53    }
54
55    pub(crate) fn matches(self, address: Address, pc: usize, opcode: u8) -> bool {
56        self.address == address && self.pc == pc && self.opcode == opcode
57    }
58}
59
60pub struct SymbolicRunInput<'a> {
61    /// Read-only view of the concrete Foundry executor used as the source of deployed bytecode and
62    /// backend state.
63    pub executor: ExecutorView<'a>,
64    /// Address of the deployed test contract whose runtime bytecode will be explored.
65    pub target: Address,
66    /// Sender used for symbolic execution environment opcodes such as `CALLER` and `ORIGIN`.
67    pub sender: Address,
68    /// ABI function to invoke symbolically.
69    pub function: &'a Function,
70    /// Call value exposed to the symbolic execution through `CALLVALUE`.
71    pub value: U256,
72    /// Whether symbolic `vm.ffi` calls are allowed to execute subprocesses.
73    pub ffi_enabled: bool,
74    /// Whether to return one successful concrete input when execution is safe.
75    pub collect_success_input: bool,
76    /// Concrete fuzz corpus entries used as path-priority hints.
77    pub corpus_seeds: Vec<SymbolicConcreteInput>,
78    /// Optional comparison site whose opposite branch should be solved.
79    pub branch_target: Option<SymbolicBranchTarget>,
80}
81
82/// Error returned by the internal symbolic executor.
83///
84/// Public callers normally receive these errors as [`SymbolicRunResult::Incomplete`]
85/// through [`SymbolicExecutor::run`]. The enum is public so integration code and tests
86/// can inspect exact failure causes when using lower-level helpers in this crate.
87#[derive(Debug, Error)]
88pub enum SymbolicError {
89    /// The target account was not present in the executor backend.
90    #[error("missing account {0}")]
91    MissingAccount(Address),
92    /// The target account had no runtime bytecode.
93    #[error("missing code for account {0}")]
94    MissingCode(Address),
95    /// The concrete backend returned an error while reading account state.
96    #[error("backend error: {0}")]
97    Backend(String),
98    /// The function ABI contains a type that is not supported by the V1 symbolic calldata model.
99    #[error("unsupported ABI type for symbolic execution: {0}")]
100    UnsupportedAbi(String),
101    /// Symbolic calldata variant expansion exceeded the configured path-width budget.
102    #[error("symbolic calldata variant limit exceeded ({0})")]
103    CalldataVariantLimit(usize),
104    /// Symbolic execution reached a feature that is not implemented yet.
105    #[error("unsupported symbolic execution feature: {0}")]
106    Unsupported(&'static str),
107    /// Symbolic execution reached an opcode that is not implemented yet.
108    #[error("unsupported opcode 0x{0:02x}")]
109    UnsupportedOpcode(u8),
110    /// Runtime bytecode was malformed in a way that prevents symbolic execution.
111    #[error("invalid bytecode: {0}")]
112    InvalidBytecode(&'static str),
113    /// A jump targeted a byte offset that is not a valid `JUMPDEST`.
114    #[error("invalid jump destination {0}")]
115    InvalidJump(usize),
116    /// The symbolic stack was popped without enough values.
117    #[error("stack underflow")]
118    StackUnderflow,
119    /// The symbolic stack exceeded the EVM stack limit.
120    #[error("stack overflow")]
121    StackOverflow,
122    /// The solver process failed, timed out, or returned an unexpected response.
123    #[error("solver error: {0}")]
124    Solver(String),
125    /// The solver returned `unknown`.
126    #[error("solver returned unknown")]
127    SolverUnknown,
128    /// The configured symbolic execution timeout was exceeded.
129    #[error("symbolic execution timeout exceeded ({0}s)")]
130    Timeout(u32),
131    /// The configured maximum number of solver queries was reached.
132    #[error("symbolic solver query limit exceeded ({0})")]
133    SolverQueryLimit(usize),
134    /// ABI encoding failed while constructing a concrete counterexample call.
135    #[error(transparent)]
136    Abi(#[from] alloy_dyn_abi::Error),
137}
138
139impl SymbolicError {
140    pub(super) const fn stop_reason(&self) -> SymbolicStopReason {
141        match self {
142            Self::Unsupported(_)
143            | Self::CalldataVariantLimit(_)
144            | Self::UnsupportedOpcode(_)
145            | Self::SolverQueryLimit(_) => SymbolicStopReason::Stuck,
146            Self::SolverUnknown | Self::Timeout(_) => SymbolicStopReason::Timeout,
147            Self::Solver(_)
148            | Self::MissingAccount(_)
149            | Self::MissingCode(_)
150            | Self::Backend(_)
151            | Self::UnsupportedAbi(_)
152            | Self::InvalidBytecode(_)
153            | Self::InvalidJump(_)
154            | Self::StackUnderflow
155            | Self::StackOverflow
156            | Self::Abi(_) => SymbolicStopReason::Error,
157        }
158    }
159}
160
161impl fmt::Display for SymbolicRunResult {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            Self::Safe { stats, .. } => write!(f, "safe after {} paths", stats.paths),
165            Self::Counterexample { stats, .. } => {
166                write!(f, "counterexample after {} paths", stats.paths)
167            }
168            Self::Incomplete { kind, reason, .. } => {
169                write!(f, "incomplete symbolic execution ({kind:?}): {reason}")
170            }
171        }
172    }
173}