Skip to main content

foundry_evm_symbolic/runtime/
folded_slots.rs

1//! Registration of constant-folded mapping slots as concrete Keccak preimages.
2//!
3//! With the optimizer on, solc folds the slot of a mapping entry at a constant key,
4//! `keccak256(abi.encode(key, slot))`, into one `PUSH32`. The engine treats a constant slot as a
5//! hash only when it knows a preimage, so the folded slot would otherwise count as a fixed slot
6//! that a write through a symbolic key never reaches. A mapping entry that `setUp` wrote is such a
7//! constant slot in the backend, and a read through a symbolic key only selects it with a known
8//! preimage. Before a run, the mapping roots in the storage layout of each deployed contract are
9//! hashed with every candidate key: the source literals, the addresses of the backend's accounts,
10//! and the contract's `PUSH` immediates. The nested level of a nested mapping is a product over
11//! the literals and immediates, so it is searched only when the run accesses a large constant slot
12//! that the contract's code pushes, and only the match is recorded. A registered preimage is a
13//! real one, so this adds no unsoundness; constants that no candidate produces, such as ERC-1967
14//! and ERC-7201 roots, stay fixed slots.
15
16use super::*;
17use foundry_common::slot_identifier::{ENCODING_INPLACE, ENCODING_MAPPING};
18use foundry_compilers::artifacts::{Storage, StorageLayout, StorageType};
19
20const MAX_NESTED_MAPPING_HASHES: usize = 1 << 18;
21
22/// Candidate keys and storage layouts of the deployed contracts, kept to resolve the nested level
23/// of a folded mapping slot on demand.
24#[derive(Default)]
25pub(crate) struct FoldedSlots {
26    contracts: Vec<FoldedContract>,
27    /// Slots already searched for a nested preimage.
28    searched: HashSet<U256>,
29    nested_hashes: usize,
30}
31
32struct FoldedContract {
33    layout: Arc<StorageLayout>,
34    keys: Vec<U256>,
35    constants: HashSet<U256>,
36}
37
38impl FoldedSlots {
39    /// Records the first-level mapping slots of every deployed contract with a known storage
40    /// layout and keeps the layouts and candidate keys for the nested level.
41    pub(crate) fn register(
42        cx: &mut SymCx,
43        executor: &ExecutorView<'_>,
44        deadline: Option<Instant>,
45    ) -> Self {
46        let mut folded = Self::default();
47        let Some(known_contracts) = executor.known_contracts else { return folded };
48        let literals = executor
49            .literals
50            .map(|literals| {
51                literals
52                    .get()
53                    .words
54                    .values()
55                    .flatten()
56                    .map(|word| (*word).into())
57                    .collect::<HashSet<U256>>()
58            })
59            .unwrap_or_default();
60        for &address in &executor.account_addresses {
61            if let Ok(Some(account)) = executor.backend.basic(address)
62                && let Some(code) = &account.code
63                && !code.is_empty()
64                && let Some((_, contract)) =
65                    known_contracts.find_by_deployed_code_exact(code.original_byte_slice())
66                && let Some(layout) = &contract.storage_layout
67            {
68                let constants = push_immediates(code.original_byte_slice()).collect::<HashSet<_>>();
69                let mut keys = literals.clone();
70                keys.extend(constants.iter().copied());
71                let mut keys = keys.into_iter().collect::<Vec<_>>();
72                keys.sort_unstable();
73                // `setUp` often keys entries by deployed accounts, such as the test contract. A
74                // folded nested slot only has constant keys, so the nested search skips them.
75                let mut first_level_keys = keys.clone();
76                first_level_keys.extend(
77                    executor.account_addresses.iter().map(|&address| address_word(address)),
78                );
79                first_level_keys.sort_unstable();
80                first_level_keys.dedup();
81                for entry in &layout.storage {
82                    if let Ok(slot) = entry.slot.parse::<U256>()
83                        && !walk_mapping_slots(
84                            cx,
85                            layout,
86                            slot,
87                            &entry.storage_type,
88                            &first_level_keys,
89                            1,
90                            &mut |cx, key, slot| {
91                                (!past_deadline(deadline))
92                                    .then(|| record_mapping_preimage(cx, key, slot))
93                            },
94                        )
95                    {
96                        return folded;
97                    }
98                }
99                folded.contracts.push(FoldedContract { layout: layout.clone(), keys, constants });
100            }
101        }
102        folded
103    }
104
105    /// Records the preimage of `slot` when it is a folded entry of a nested mapping,
106    /// `keccak(inner . keccak(outer . root))` plus a struct offset below `2^64`, of a contract
107    /// whose code pushes `slot`. The code, not the storage account, decides the layout, so this
108    /// also covers a proxy that delegates to the contract. Each constant slot is searched once, so
109    /// a run that never accesses such a slot pays nothing for the key product.
110    pub(crate) fn resolve_nested(
111        &mut self,
112        cx: &mut SymCx,
113        slot: U256,
114        deadline: Option<Instant>,
115    ) -> bool {
116        let max_offset = U256::ONE << STORAGE_LAYOUT_OFFSET_BITS;
117        if slot < max_offset
118            || self.searched.contains(&slot)
119            || cx.concrete_keccak_base(slot, STORAGE_LAYOUT_OFFSET_BITS).is_some()
120        {
121            return true;
122        }
123        let nested_hashes = &mut self.nested_hashes;
124        let mut found = false;
125        'search: for contract in self.contracts.iter().filter(|c| c.constants.contains(&slot)) {
126            for entry in &contract.layout.storage {
127                let Ok(root) = entry.slot.parse::<U256>() else { continue };
128                let completed = walk_mapping_slots(
129                    cx,
130                    &contract.layout,
131                    root,
132                    &entry.storage_type,
133                    &contract.keys,
134                    2,
135                    &mut |cx, key, base| {
136                        if *nested_hashes >= MAX_NESTED_MAPPING_HASHES || past_deadline(deadline) {
137                            return None;
138                        }
139                        *nested_hashes += 1;
140                        let (hash, bytes) = mapping_preimage(key, base);
141                        if slot.wrapping_sub(hash) < max_offset {
142                            record_preimage_bytes(cx, hash, &bytes);
143                            found = true;
144                            return None;
145                        }
146                        Some(hash)
147                    },
148                );
149                if found {
150                    break 'search;
151                }
152                if !completed {
153                    return false;
154                }
155            }
156        }
157        self.searched.insert(slot);
158        true
159    }
160}
161
162fn past_deadline(deadline: Option<Instant>) -> bool {
163    deadline.is_some_and(|deadline| Instant::now() >= deadline)
164}
165
166/// Returns the right-aligned values of the `PUSH` immediates in `code`.
167fn push_immediates(code: &[u8]) -> impl Iterator<Item = U256> {
168    let mut pc = 0;
169    std::iter::from_fn(move || {
170        while let Some(&op) = code.get(pc) {
171            pc += 1;
172            if let opcode::PUSH1..=opcode::PUSH32 = op {
173                let len = usize::from(op - opcode::PUSH1 + 1);
174                let data = &code[pc..code.len().min(pc + len)];
175                pc += len;
176                return Some(U256::from_be_slice(data));
177            }
178        }
179        None
180    })
181}
182
183/// Calls `hash` for every candidate key that fits the key type of the mapping at `slot`, descending
184/// into struct members and `levels - 1` nested mapping levels through the returned hash. Returns
185/// `false` when `hash` stopped the walk.
186fn walk_mapping_slots(
187    cx: &mut SymCx,
188    layout: &StorageLayout,
189    slot: U256,
190    type_id: &str,
191    keys: &[U256],
192    levels: usize,
193    hash: &mut impl FnMut(&mut SymCx, U256, U256) -> Option<U256>,
194) -> bool {
195    let Some(ty) = layout.types.get(type_id) else { return true };
196    if levels == 0 {
197        return true;
198    }
199    if ty.encoding == ENCODING_MAPPING {
200        let Some((key_ty, value_id)) =
201            ty.key.as_deref().and_then(|key| layout.types.get(key)).zip(ty.value.as_deref())
202        else {
203            return true;
204        };
205        for &key in keys.iter().filter(|&&key| key_fits(key_ty, key)) {
206            let Some(value_slot) = hash(cx, key, slot) else { return false };
207            if !walk_mapping_slots(cx, layout, value_slot, value_id, keys, levels - 1, hash) {
208                return false;
209            }
210        }
211    } else if ty.encoding == ENCODING_INPLACE
212        && let Some(members) = ty
213            .other
214            .get("members")
215            .and_then(|members| serde_json::from_value::<Vec<Storage>>(members.clone()).ok())
216    {
217        for member in &members {
218            if let Ok(offset) = member.slot.parse::<U256>() {
219                let slot = slot.wrapping_add(offset);
220                if !walk_mapping_slots(cx, layout, slot, &member.storage_type, keys, levels, hash) {
221                    return false;
222                }
223            }
224        }
225    }
226    true
227}
228
229/// Returns whether `key` is a value of the mapping key type `ty` as `abi.encode` pads it.
230fn key_fits(ty: &StorageType, key: U256) -> bool {
231    let Ok(bytes) = ty.number_of_bytes.parse::<usize>() else { return false };
232    let bits = bytes * 8;
233    if bits == 0 || bits > 256 || ty.label == "string" || ty.label == "bytes" {
234        // Dynamic keys are hashed from their bytes, not from a padded word.
235        false
236    } else if ty.label.starts_with("int") {
237        let magnitude = U256::ONE << (bits - 1);
238        key < magnitude || key >= U256::ZERO.wrapping_sub(magnitude)
239    } else if ty.label.starts_with("bytes") {
240        key.trailing_zeros() >= 256 - bits
241    } else {
242        bits == 256 || key < U256::ONE << bits
243    }
244}
245
246/// Returns `keccak(key . slot)` and its 64-byte preimage.
247fn mapping_preimage(key: U256, slot: U256) -> (U256, [u8; 64]) {
248    let mut bytes = [0u8; 64];
249    bytes[..32].copy_from_slice(B256::from(key).as_slice());
250    bytes[32..].copy_from_slice(B256::from(slot).as_slice());
251    (keccak256(bytes).into(), bytes)
252}
253
254/// Records `keccak(key . slot)` with its preimage and returns the hash.
255fn record_mapping_preimage(cx: &mut SymCx, key: U256, slot: U256) -> U256 {
256    let (hash, bytes) = mapping_preimage(key, slot);
257    record_preimage_bytes(cx, hash, &bytes);
258    hash
259}
260
261fn record_preimage_bytes(cx: &mut SymCx, hash: U256, bytes: &[u8; 64]) {
262    let preimage = bytes.iter().map(|&byte| SymExpr::constant(cx, U256::from(byte))).collect();
263    cx.record_concrete_keccak_preimage(hash, preimage);
264}