Skip to main content

foundry_evm_symbolic/runtime/
executor_view.rs

1use super::*;
2use evm2::evm::{AccountInfo, DbResult};
3use foundry_common::contracts::ContractsByArtifact;
4use foundry_evm::{
5    core::backend::Backend,
6    fuzz::strategies::LiteralsDictionary,
7    inspectors::cheatcodes::{CheatcodesCore, Prank, RecordAccess},
8};
9
10/// Reads of a backend's accepted state, independent of its network.
11pub(crate) trait AcceptedState {
12    /// Returns an account, with its code.
13    fn basic(&self, address: Address) -> DbResult<Option<AccountInfo>>;
14
15    /// Returns a storage slot.
16    fn storage(&self, address: Address, slot: U256) -> DbResult<U256>;
17
18    /// Returns the cached storage slots of an account, with their values, in slot order.
19    fn storage_slots(&self, address: Address) -> Vec<(U256, U256)>;
20
21    /// Returns a block hash.
22    fn block_hash(&self, number: U256) -> DbResult<B256>;
23}
24
25impl<FEN: FoundryEvmNetwork> AcceptedState for Backend<FEN> {
26    fn basic(&self, address: Address) -> DbResult<Option<AccountInfo>> {
27        Self::basic(self, address)
28    }
29
30    fn storage(&self, address: Address, slot: U256) -> DbResult<U256> {
31        Self::storage(self, address, slot)
32    }
33
34    fn storage_slots(&self, address: Address) -> Vec<(U256, U256)> {
35        let mut slots = self
36            .lifecycle()
37            .active()
38            .cache
39            .as_ref()
40            .and_then(|cache| cache.storage.get(&address))
41            .map(|storage| {
42                storage.slots.iter().map(|(slot, value)| (*slot, *value)).collect::<Vec<_>>()
43            })
44            .unwrap_or_default();
45        slots.sort_unstable();
46        slots
47    }
48
49    fn block_hash(&self, number: U256) -> DbResult<B256> {
50        Self::block_hash(self, number)
51    }
52}
53
54/// Network-independent, read-only view of a concrete Foundry executor.
55///
56/// The view is built by the caller of the public entry points so the symbolic executor does not
57/// have to be monomorphized for every [`FoundryEvmNetwork`].
58pub struct ExecutorView<'a> {
59    pub(crate) backend: &'a dyn AcceptedState,
60    pub(crate) spec_id: SpecId,
61    pub(crate) chain_id: u64,
62    pub(crate) memory_limit: u64,
63    /// Gas limit of the calls and deployments the executor runs.
64    pub(crate) gas_limit: u64,
65    pub(crate) max_code_size: usize,
66    /// Initcode size limit of CREATE, CREATE2, and `vm.deployCode`, or `usize::MAX` before
67    /// EIP-3860.
68    pub(crate) max_initcode_size: usize,
69    /// Whether calls to EIP-7702 delegated accounts run the delegate's code.
70    pub(crate) eip7702_delegations: bool,
71    pub(crate) active_fork_id: Option<U256>,
72    /// Addresses cached by the active context, including committed-session reads.
73    pub(crate) account_addresses: Vec<Address>,
74    pub(crate) block: ExecutorBlock,
75    pub(crate) gas_price: u128,
76    pub(crate) isolate: bool,
77    /// Whether `vm.expectRevert` may be satisfied by an internal call below the next call.
78    pub(crate) internal_expect_revert: bool,
79    /// Whether a failed assertion cheatcode reverts its call instead of setting the fail slot.
80    pub(crate) assertions_revert: bool,
81    pub(crate) blob_hashes: Vec<B256>,
82    pub(crate) arbitrary_storage_targets: Vec<(Address, bool)>,
83    pub(crate) arbitrary_storage_copies: Vec<(Address, Address)>,
84    pub(crate) storage_load_hooks: Vec<(Address, SymbolicStorageHook)>,
85    pub(crate) storage_store_hooks: Vec<(Address, SymbolicStorageHook)>,
86    pub(crate) mapping_storage_store_hooks: Vec<((Address, U256), SymbolicStorageHook)>,
87    /// Cheatcode state that `setUp` left behind, which Forge keeps for the test.
88    pub(crate) cheatcodes: Option<&'a CheatcodesCore>,
89    pub(crate) pranks: Vec<Prank>,
90    pub(crate) accesses: Option<&'a RecordAccess>,
91    pub(crate) recording_accesses: bool,
92    /// Project artifacts, used to find the storage layouts of deployed contracts.
93    pub(crate) known_contracts: Option<&'a ContractsByArtifact>,
94    /// Source literals, used as candidate keys of constant-folded mapping slots.
95    pub(crate) literals: Option<&'a LiteralsDictionary>,
96    pub(crate) expects_safe_memory: bool,
97    /// Accounts the backend marks persistent across fork switches, which `vm.isPersistent` sees.
98    pub(crate) persistent_accounts: Vec<Address>,
99}
100
101/// Block environment values exposed to symbolic execution.
102pub(crate) struct ExecutorBlock {
103    pub(crate) coinbase: Address,
104    pub(crate) timestamp: U256,
105    pub(crate) number: U256,
106    pub(crate) difficulty: U256,
107    pub(crate) gas_limit: U256,
108    pub(crate) basefee: U256,
109    pub(crate) blob_basefee: U256,
110    pub(crate) slot_num: U256,
111}
112
113impl<'a> ExecutorView<'a> {
114    /// Snapshots the environment, backend, and cheatcode configuration of `executor`.
115    pub fn new<FEN: FoundryEvmNetwork>(executor: &'a Executor<FEN>) -> Self {
116        let backend = executor.backend();
117        let evm_env = executor.evm_env();
118        let cheats = executor.inspector().cheatcodes.as_deref();
119        let block = cheats.and_then(|cheats| cheats.block.as_ref()).unwrap_or(&evm_env.block);
120        let difficulty = if evm_env.version.feature(EvmFeatures::EIP4399) {
121            block.prevrandao
122        } else {
123            block.difficulty
124        };
125        // Environment cheatcodes the running transaction cannot apply override their opcodes.
126        let overrides =
127            cheats.and_then(|cheats| cheats.env_overrides.get(backend.active_fork_id()));
128        let tx = executor.tx();
129
130        let account_addresses = backend
131            .lifecycle()
132            .active()
133            .cache
134            .as_ref()
135            .map(|cache| cache.accounts.keys().copied().collect())
136            .unwrap_or_default();
137
138        Self {
139            backend,
140            spec_id: executor.spec_id().into(),
141            chain_id: overrides
142                .and_then(|overrides| overrides.chain_id)
143                .unwrap_or(evm_env.chain_id()),
144            memory_limit: evm_env.version.memory_limit,
145            gas_limit: executor.gas_limit(),
146            max_code_size: evm_env.version.max_code_size,
147            max_initcode_size: if evm_env.version.feature(EvmFeatures::EIP3860) {
148                evm_env.version.max_initcode_size
149            } else {
150                usize::MAX
151            },
152            eip7702_delegations: evm_env.version.feature(EvmFeatures::EIP7702),
153            active_fork_id: backend.active_fork_id(),
154            account_addresses,
155            block: ExecutorBlock {
156                coinbase: block.beneficiary,
157                timestamp: block.timestamp,
158                number: block.number,
159                difficulty,
160                gas_limit: block.gas_limit,
161                basefee: overrides
162                    .and_then(|overrides| overrides.basefee_override())
163                    .map_or(block.basefee, U256::from),
164                blob_basefee: block.blob_basefee,
165                slot_num: block.slot_num,
166            },
167            gas_price: overrides
168                .and_then(|overrides| overrides.gas_price_override())
169                .or_else(|| cheats.and_then(|cheats| cheats.gas_price))
170                .unwrap_or_else(|| {
171                    tx.gas_price().or_else(|| tx.max_fee_per_gas()).unwrap_or_default()
172                }),
173            isolate: cheats.is_some_and(|cheats| cheats.core.config.isolate),
174            internal_expect_revert: cheats
175                .is_some_and(|cheats| cheats.core.config.internal_expect_revert),
176            assertions_revert: cheats.is_none_or(|cheats| cheats.core.config.assertions_revert),
177            blob_hashes: overrides
178                .and_then(|overrides| overrides.blob_hashes.clone())
179                .unwrap_or_else(|| tx.blob_versioned_hashes().unwrap_or_default().to_vec()),
180            arbitrary_storage_targets: cheats
181                .into_iter()
182                .flat_map(|cheats| cheats.arbitrary_storage_target_overwrite_modes())
183                .collect(),
184            arbitrary_storage_copies: cheats
185                .into_iter()
186                .flat_map(|cheats| cheats.arbitrary_storage_copied_target_sources())
187                .collect(),
188            storage_load_hooks: cheats
189                .into_iter()
190                .flat_map(|cheats| cheats.storage_load_hooks())
191                .map(|(target, hook)| {
192                    (
193                        target,
194                        SymbolicStorageHook {
195                            callback_target: hook.callback_target,
196                            callback_selector: hook.callback_selector,
197                        },
198                    )
199                })
200                .collect(),
201            storage_store_hooks: cheats
202                .into_iter()
203                .flat_map(|cheats| cheats.storage_store_hooks())
204                .map(|(target, hook)| {
205                    (
206                        target,
207                        SymbolicStorageHook {
208                            callback_target: hook.callback_target,
209                            callback_selector: hook.callback_selector,
210                        },
211                    )
212                })
213                .collect(),
214            mapping_storage_store_hooks: cheats
215                .into_iter()
216                .flat_map(|cheats| cheats.mapping_storage_store_hooks())
217                .map(|(target, root, hook)| {
218                    (
219                        (target, root.into()),
220                        SymbolicStorageHook {
221                            callback_target: hook.callback_target,
222                            callback_selector: hook.callback_selector,
223                        },
224                    )
225                })
226                .collect(),
227            cheatcodes: cheats.map(|cheats| &cheats.core),
228            pranks: cheats.into_iter().flat_map(|cheats| cheats.pranks.values().copied()).collect(),
229            accesses: cheats.map(|cheats| &cheats.accesses),
230            recording_accesses: cheats.is_some_and(|cheats| cheats.recording_accesses),
231            known_contracts: None,
232            literals: None,
233            expects_safe_memory: cheats.is_some_and(|cheats| !cheats.allowed_mem_writes.is_empty()),
234            persistent_accounts: backend.lifecycle().forks().persistent_accounts().collect(),
235        }
236    }
237
238    /// Attaches the project artifacts and source literals that register the constant-folded
239    /// mapping slots of deployed contracts before a run.
240    pub const fn with_project(
241        mut self,
242        known_contracts: &'a ContractsByArtifact,
243        literals: &'a LiteralsDictionary,
244    ) -> Self {
245        self.known_contracts = Some(known_contracts);
246        self.literals = Some(literals);
247        self
248    }
249}