Skip to main content

foundry_evm_symbolic/executor/
opcodes.rs

1use super::*;
2use evm2::{constants::STACK_LIMIT, interpreter::opcode::OpCode};
3
4enum MappingStorageProvenance {
5    None,
6    Exact(SymbolicMappingProvenance),
7    Fork { equality: Vec<SymBoolExpr>, inequality: Vec<SymBoolExpr> },
8}
9
10impl SymbolicExecutor {
11    fn classify_mapping_match(
12        &mut self,
13        state: &PathState,
14        matches: SymBoolExpr,
15        provenance: SymbolicMappingProvenance,
16    ) -> Result<Option<MappingStorageProvenance>, SymbolicError> {
17        let does_not_match = matches.clone().not(&mut self.cx);
18        let (inequality, inequality_is_sat) =
19            self.constraints_with_condition(state, does_not_match)?;
20        if !inequality_is_sat {
21            return Ok(Some(MappingStorageProvenance::Exact(provenance)));
22        }
23        let (equality, equality_is_sat) = self.constraints_with_condition(state, matches)?;
24        Ok(equality_is_sat.then_some(MappingStorageProvenance::Fork { equality, inequality }))
25    }
26
27    fn observed_mapping_chain(
28        &mut self,
29        state: &PathState,
30        hash: &SymExpr,
31    ) -> Option<(SymExpr, Vec<SymExpr>)> {
32        let account = state.storage_address;
33        let mut current = hash.clone();
34        let mut keys = Vec::new();
35        let mut visited = Vec::new();
36        loop {
37            if visited.contains(&current) {
38                return None;
39            }
40            visited.push(current.clone());
41            let Some(bytes) =
42                state.mapping_hook_keccak_preimages.get(&(account, current.clone())).cloned()
43            else {
44                keys.reverse();
45                return Some((current, keys));
46            };
47            if bytes.len() != 64 {
48                return None;
49            }
50            keys.push(SymExpr::from_bytes(&mut self.cx, bytes[..32].iter().cloned()));
51            current = SymExpr::from_bytes(&mut self.cx, bytes[32..64].iter().cloned());
52        }
53    }
54
55    fn mapping_storage_provenance(
56        &mut self,
57        state: &PathState,
58        key: &SymExpr,
59    ) -> Result<MappingStorageProvenance, SymbolicError> {
60        let account = state.storage_address;
61        let observed = |hash: &SymExpr| {
62            state.mapping_hook_keccak_preimages.get(&(account, hash.clone())).cloned()
63        };
64        if let Some(provenance) =
65            key.storage_mapping_provenance_observed_with(&mut self.cx, observed)
66        {
67            return Ok(MappingStorageProvenance::Exact(provenance));
68        }
69        let mut hashes = state
70            .mapping_hook_keccak_preimages
71            .keys()
72            .filter(|(address, _)| *address == account)
73            .map(|(_, hash)| hash.clone())
74            .collect::<Vec<_>>();
75        let contains_observed_hash =
76            hashes.iter().any(|hash| key.visit_bool(|candidate| candidate == hash));
77        let key_is_const = key.as_const().is_some();
78        let key_contains_keccak = key.contains_keccak();
79        let key_is_storage_mapping_key = key.storage_mapping_key(&mut self.cx).is_some();
80        let roots = state
81            .mapping_storage_store_hooks
82            .keys()
83            .filter(|(address, _)| *address == account)
84            .map(|(_, root)| *root)
85            .collect::<Vec<_>>();
86        hashes.sort_by_key(|hash| hash != key);
87        for hash in hashes {
88            if contains_observed_hash && !key.visit_bool(|candidate| candidate == &hash) {
89                continue;
90            }
91            let use_legacy_match = contains_observed_hash || !key_contains_keccak;
92            if use_legacy_match
93                && let Some(provenance) =
94                    hash.storage_mapping_provenance_observed_with(&mut self.cx, |candidate| {
95                        state
96                            .mapping_hook_keccak_preimages
97                            .get(&(account, candidate.clone()))
98                            .cloned()
99                    })
100            {
101                if !state.mapping_storage_store_hooks.contains_key(&(account, provenance.root_slot))
102                {
103                    continue;
104                }
105                let equality = SymBoolExpr::eq(&mut self.cx, key.clone(), hash.clone());
106                if key_is_const {
107                    let inequality = equality.not(&mut self.cx);
108                    let (_, inequality_is_sat) =
109                        self.constraints_with_condition(state, inequality)?;
110                    if !inequality_is_sat {
111                        return Ok(MappingStorageProvenance::Exact(provenance));
112                    }
113                    continue;
114                }
115                if let Some(provenance) =
116                    self.classify_mapping_match(state, equality, provenance)?
117                {
118                    return Ok(provenance);
119                }
120                continue;
121            }
122            if (key_is_const || key_contains_keccak) && !key_is_storage_mapping_key {
123                continue;
124            }
125            let Some((root, keys)) = self.observed_mapping_chain(state, &hash) else {
126                continue;
127            };
128            for &root_slot in &roots {
129                let slot_matches = if key_is_const || key.visit_bool(|candidate| candidate == &hash)
130                {
131                    SymBoolExpr::eq(&mut self.cx, key.clone(), hash.clone())
132                } else {
133                    key.storage_key_eq(&mut self.cx, &hash)
134                };
135                let matches = if let Some(constrained_root) =
136                    state.constrained_word(&mut self.cx, &root)
137                {
138                    if constrained_root != root_slot {
139                        continue;
140                    }
141                    slot_matches
142                } else {
143                    let root_slot_expr = SymExpr::constant(&mut self.cx, root_slot);
144                    let root_matches = SymBoolExpr::eq(&mut self.cx, root.clone(), root_slot_expr);
145                    SymBoolExpr::and(&mut self.cx, vec![slot_matches, root_matches])
146                };
147                let provenance = SymbolicMappingProvenance { root_slot, keys: keys.clone() };
148                if let Some(provenance) = self.classify_mapping_match(state, matches, provenance)? {
149                    return Ok(provenance);
150                }
151            }
152        }
153        Ok(MappingStorageProvenance::None)
154    }
155
156    fn storage_hook_calldata(
157        &mut self,
158        selector: [u8; 4],
159        words: impl IntoIterator<Item = SymExpr>,
160    ) -> SymCalldata {
161        let selector = SymBytes::concrete(&mut self.cx, selector.to_vec());
162        let words = words.into_iter().map(|word| word.into_bytes(&mut self.cx)).collect::<Vec<_>>();
163        let bytes = SymBytes::concat(&mut self.cx, std::iter::once(selector).chain(words));
164        SymCalldata::from_bytes(&mut self.cx, bytes)
165    }
166
167    fn mapping_storage_hook_calldata(
168        &mut self,
169        selector: [u8; 4],
170        [account, computed_slot, root_slot, old_value, new_value]: [SymExpr; 5],
171        keys: Vec<SymExpr>,
172    ) -> SymCalldata {
173        let selector = SymBytes::concrete(&mut self.cx, selector.to_vec());
174        let keys_offset = SymExpr::constant(&mut self.cx, U256::from(6 * 32));
175        let mut words = vec![account, computed_slot, root_slot, keys_offset, old_value, new_value];
176        words.push(SymExpr::constant(&mut self.cx, U256::from(keys.len())));
177        words.extend(keys);
178        let words = words.into_iter().map(|word| word.into_bytes(&mut self.cx)).collect::<Vec<_>>();
179        let bytes = SymBytes::concat(&mut self.cx, std::iter::once(selector).chain(words));
180        SymCalldata::from_bytes(&mut self.cx, bytes)
181    }
182
183    fn invoke_storage_hook(
184        &mut self,
185        executor: &ExecutorView<'_>,
186        state: &mut PathState,
187        worklist: &mut VecDeque<PathState>,
188        completed_paths: &mut usize,
189        hook: SymbolicStorageHook,
190        calldata: SymCalldata,
191    ) -> Result<StepOutcome, SymbolicError> {
192        let code = state.world.extcode(&mut self.cx, executor, hook.callback_target)?;
193        if code.is_empty() {
194            return Ok(StepOutcome::Continue);
195        }
196
197        let callvalue = SymExpr::zero(&mut self.cx);
198        let frame = CallFrame::new(
199            &mut self.cx,
200            hook.callback_target,
201            hook.callback_target,
202            CHEATCODE_ADDRESS,
203            callvalue,
204            false,
205            calldata,
206        );
207        let child = state.storage_hook_child(frame);
208        let outcomes = self.execute_external_call(executor, child, &code, completed_paths)?;
209        if outcomes.is_empty() {
210            return Ok(StepOutcome::AssumeRejected);
211        }
212
213        let mut parents = VecDeque::with_capacity(outcomes.len());
214        for mut outcome in outcomes {
215            let mut parent = state.clone();
216            parent.constraints = std::mem::take(&mut outcome.state.constraints);
217            parent.witness_preferences = std::mem::take(&mut outcome.state.witness_preferences);
218            parent.next_symbol = outcome.state.next_symbol;
219            parent.svm_returns = std::mem::take(&mut outcome.state.svm_returns);
220            parent.storage_load_hooks = std::mem::take(&mut outcome.state.storage_load_hooks);
221            parent.storage_store_hooks = std::mem::take(&mut outcome.state.storage_store_hooks);
222            parent.mapping_storage_store_hooks =
223                std::mem::take(&mut outcome.state.mapping_storage_store_hooks);
224            parent.mapping_hook_keccak_preimages =
225                std::mem::take(&mut outcome.state.mapping_hook_keccak_preimages);
226            parent.persistent_writes = std::mem::take(&mut outcome.state.persistent_writes);
227            parent.storage_hook_active = false;
228
229            match outcome.status {
230                CallStatus::Success => {
231                    parent.world = outcome.state.world;
232                    parent.block = outcome.state.block;
233                }
234                CallStatus::Revert | CallStatus::ExceptionalHalt | CallStatus::Failure => {
235                    parent.world.merge_replay_metadata_from(&outcome.state.world);
236                    let start = state.persistent_writes.len();
237                    parent.replay_persistent_writes(&mut self.cx, executor, start)?;
238                    parent.return_data = outcome.state.frame.return_data;
239                    parent.pending_storage_hook_revert = true;
240                }
241            }
242            parents.push_back(parent);
243        }
244
245        let Some(first) = self.pop_next_path(&mut parents) else {
246            return Ok(StepOutcome::AssumeRejected);
247        };
248        *state = first;
249        worklist.extend(parents);
250        Ok(if std::mem::take(&mut state.pending_storage_hook_revert) {
251            StepOutcome::Revert
252        } else {
253            StepOutcome::Continue
254        })
255    }
256
257    fn push_comparison_result(
258        &mut self,
259        state: &mut PathState,
260        op_pc: usize,
261        opcode: u8,
262        condition: SymBoolExpr,
263    ) -> Result<StepOutcome, SymbolicError> {
264        if !self.apply_branch_target_constraint(state, op_pc, opcode, &condition)? {
265            return Ok(StepOutcome::AssumeRejected);
266        }
267        let value = SymExpr::bool_word(&mut self.cx, condition);
268        state.stack.push(value)?;
269        Ok(StepOutcome::Continue)
270    }
271
272    fn apply_branch_target_constraint(
273        &mut self,
274        state: &mut PathState,
275        op_pc: usize,
276        opcode: u8,
277        condition: &SymBoolExpr,
278    ) -> Result<bool, SymbolicError> {
279        let Some(target) = state.branch_target() else {
280            return Ok(true);
281        };
282        if state.satisfies_branch_target() {
283            return Ok(true);
284        }
285        if !target.matches(state.address, op_pc, opcode) {
286            return Ok(true);
287        }
288
289        let desired =
290            if target.result() { condition.clone().not(&mut self.cx) } else { condition.clone() };
291        let mut constraints = state.constraints.clone();
292        constraints.push(desired);
293        if !self.branch_is_sat_or_defer(state, &constraints)? {
294            return Ok(false);
295        }
296        state.constraints = constraints;
297        state.mark_branch_target_reached();
298        Ok(true)
299    }
300
301    fn guard_fixed_memory_access(
302        &mut self,
303        executor: &ExecutorView<'_>,
304        state: &mut PathState,
305        worklist: &mut VecDeque<PathState>,
306        offset: &SymExpr,
307        size: usize,
308    ) -> Result<Option<StepOutcome>, SymbolicError> {
309        let memory_limit = executor.memory_limit;
310        let host_max_offset = (usize::MAX & !31usize).checked_sub(size);
311        let constrained_offset = state.constrained_usize_checked(&mut self.cx, offset);
312        if constrained_offset.as_ref().is_some_and(|offset| match offset {
313            Ok(offset) => host_max_offset.is_none_or(|max| *offset > max),
314            Err(_) => true,
315        }) {
316            if self.ignores_out_of_gas() {
317                return Ok(Some(StepOutcome::AssumeRejected));
318            }
319            return Ok(Some(self.memory_halt(state)));
320        }
321
322        let expanded_size_bound = state
323            .upper_bound_usize(&mut self.cx, offset)
324            .and_then(|offset| offset.checked_add(size))
325            .and_then(|end| end.checked_add(31))
326            .and_then(|end| u64::try_from(end & !31usize).ok());
327        if expanded_size_bound.is_some_and(|size| size <= memory_limit) {
328            return Ok(None);
329        }
330
331        let representable = if let Some(host_max_offset) = host_max_offset {
332            let host_max_offset = SymExpr::constant(&mut self.cx, U256::from(host_max_offset));
333            SymBoolExpr::cmp_word_expr(&mut self.cx, SymCmpOp::Ule, offset, host_max_offset)
334        } else {
335            SymBoolExpr::constant(&mut self.cx, false)
336        };
337        let size = SymExpr::constant(&mut self.cx, U256::from(size));
338        let local_size =
339            state.memory.size_after_range_expansion_word(&mut self.cx, offset.clone(), size);
340        if let Some(local_size) = local_size.as_const() {
341            if local_size <= U256::from(memory_limit) {
342                return Ok(None);
343            }
344            if self.ignores_out_of_gas() {
345                return Ok(Some(StepOutcome::AssumeRejected));
346            }
347            return Ok(Some(self.memory_halt(state)));
348        }
349        let memory_limit = SymExpr::constant(&mut self.cx, U256::from(memory_limit));
350        let within_limit = SymBoolExpr::cmp(&mut self.cx, SymCmpOp::Ule, local_size, memory_limit);
351        let valid_access = SymBoolExpr::and(&mut self.cx, vec![representable, within_limit]);
352        if self.ignores_out_of_gas() {
353            let (constraints, feasible) = self.constraints_with_condition(state, valid_access)?;
354            if !feasible {
355                return Ok(Some(StepOutcome::AssumeRejected));
356            }
357            state.constraints = constraints;
358            return Ok(None);
359        }
360        let outcome = self.apply_memory_access_guard(state, worklist, valid_access)?;
361        if matches!(outcome, Some(StepOutcome::ExceptionalHalt)) {
362            state.memory_halt_pc = Some(state.pc - 1);
363        }
364        Ok(outcome)
365    }
366
367    fn apply_memory_access_guard(
368        &mut self,
369        state: &mut PathState,
370        worklist: &mut VecDeque<PathState>,
371        valid_access: SymBoolExpr,
372    ) -> Result<Option<StepOutcome>, SymbolicError> {
373        let (valid_constraints, valid_sat) =
374            self.constraints_with_condition(state, valid_access.clone())?;
375        let invalid = valid_access.clone().not(&mut self.cx);
376        let (invalid_constraints, invalid_sat) = self.constraints_with_condition(state, invalid)?;
377        match (valid_sat, invalid_sat) {
378            (true, true) => {
379                let (valid_seed_models, invalid_seed_models) =
380                    state.split_corpus_seed_models(&valid_access);
381                let mut valid = state.clone();
382                valid.pc = valid.pc.saturating_sub(1);
383                valid.depth = valid.depth.saturating_sub(1);
384                valid.constraints = valid_constraints;
385                valid.set_corpus_seed_models(valid_seed_models);
386                worklist.push_back(valid);
387                state.constraints = invalid_constraints;
388                state.set_corpus_seed_models(invalid_seed_models);
389                state.return_data = SymReturnData::empty(&mut self.cx);
390                Ok(Some(StepOutcome::ExceptionalHalt))
391            }
392            (true, false) => {
393                state.constraints = valid_constraints;
394                Ok(None)
395            }
396            (false, true) => {
397                state.constraints = invalid_constraints;
398                state.return_data = SymReturnData::empty(&mut self.cx);
399                Ok(Some(StepOutcome::ExceptionalHalt))
400            }
401            (false, false) => Ok(Some(StepOutcome::AssumeRejected)),
402        }
403    }
404
405    /// Halts `state` exceptionally on a memory access the EVM cannot expand to. The access is
406    /// the instruction before `state.pc`.
407    fn memory_halt(&mut self, state: &mut PathState) -> StepOutcome {
408        state.return_data = SymReturnData::empty(&mut self.cx);
409        state.memory_halt_pc = Some(state.pc - 1);
410        StepOutcome::ExceptionalHalt
411    }
412
413    pub(super) fn guard_memory_range(
414        &mut self,
415        executor: &ExecutorView<'_>,
416        state: &mut PathState,
417        worklist: &mut VecDeque<PathState>,
418        offset: &SymExpr,
419        size: &SymExpr,
420    ) -> Result<Option<StepOutcome>, SymbolicError> {
421        let memory_limit = executor.memory_limit;
422        if let (Some(offset_value), Some(size_value)) = (offset.as_const(), size.as_const()) {
423            let valid = size_value.is_zero()
424                || usize::try_from(offset_value)
425                    .ok()
426                    .zip(usize::try_from(size_value).ok())
427                    .and_then(|(offset, size)| offset.checked_add(size))
428                    .and_then(|end| end.checked_add(31))
429                    .and_then(|end| u64::try_from(end & !31usize).ok())
430                    .is_some_and(|end| end <= memory_limit);
431            if !valid {
432                if self.ignores_out_of_gas() {
433                    return Ok(Some(StepOutcome::AssumeRejected));
434                }
435                return Ok(Some(self.memory_halt(state)));
436            }
437            state.memory.expand_range(&mut self.cx, offset.clone(), size.clone());
438            return Ok(None);
439        }
440
441        let offset_bound = state.upper_bound_usize(&mut self.cx, offset);
442        let size_bound = state.upper_bound_usize(&mut self.cx, size);
443        if offset_bound
444            .zip(size_bound)
445            .and_then(|(offset, size)| offset.checked_add(size))
446            .and_then(|end| end.checked_add(31))
447            .and_then(|end| u64::try_from(end & !31usize).ok())
448            .is_some_and(|end| end <= memory_limit)
449        {
450            state.memory.expand_range(&mut self.cx, offset.clone(), size.clone());
451            return Ok(None);
452        }
453
454        let zero_size = SymBoolExpr::eq_word_const(&mut self.cx, size, U256::ZERO);
455        let host_max = SymExpr::constant(&mut self.cx, U256::from(usize::MAX & !31usize));
456        let size_fits =
457            SymBoolExpr::cmp_word_expr(&mut self.cx, SymCmpOp::Ule, size, host_max.clone());
458        let max_offset = SymExpr::binop(&mut self.cx, SymBinOp::Sub, host_max, size.clone());
459        let offset_fits =
460            SymBoolExpr::cmp_word_expr(&mut self.cx, SymCmpOp::Ule, offset, max_offset);
461
462        let local_size = state.memory.size_after_range_expansion_word(
463            &mut self.cx,
464            offset.clone(),
465            size.clone(),
466        );
467        let memory_limit = SymExpr::constant(&mut self.cx, U256::from(memory_limit));
468        let local_fits = SymBoolExpr::cmp(&mut self.cx, SymCmpOp::Ule, local_size, memory_limit);
469        let nonzero_valid =
470            SymBoolExpr::and(&mut self.cx, vec![size_fits, offset_fits, local_fits]);
471        let valid_access = SymBoolExpr::or(&mut self.cx, vec![zero_size, nonzero_valid]);
472
473        // An equivalence check modulo gas leaves out the inputs that run out of memory gas.
474        if self.ignores_out_of_gas() {
475            let (constraints, feasible) = self.constraints_with_condition(state, valid_access)?;
476            if !feasible {
477                return Ok(Some(StepOutcome::AssumeRejected));
478            }
479            state.constraints = constraints;
480            state.memory.expand_range(&mut self.cx, offset.clone(), size.clone());
481            return Ok(None);
482        }
483        let outcome = self.apply_memory_access_guard(state, worklist, valid_access)?;
484        if outcome.is_none() {
485            state.memory.expand_range(&mut self.cx, offset.clone(), size.clone());
486        }
487        if matches!(outcome, Some(StepOutcome::ExceptionalHalt)) {
488            state.memory_halt_pc = Some(state.pc - 1);
489        }
490        Ok(outcome)
491    }
492
493    pub(super) fn step(
494        &mut self,
495        executor: &ExecutorView<'_>,
496        code: &SymCode,
497        state: &mut PathState,
498        worklist: &mut VecDeque<PathState>,
499        completed_paths: &mut usize,
500        op: u8,
501    ) -> Result<StepOutcome, SymbolicError> {
502        // A path that kept running without a feasibility check, such as a caught `vm.assume`
503        // rejection, is checked before it calls out or logs: a callee, cheatcodes in particular,
504        // or a pending `vm.expectEmit` can record limitations for the whole run.
505        if matches!(
506            op,
507            opcode::CALL
508                | opcode::CALLCODE
509                | opcode::DELEGATECALL
510                | opcode::STATICCALL
511                | opcode::CREATE
512                | opcode::CREATE2
513                | opcode::LOG0..=opcode::LOG4
514        ) && !self.deferred_path_is_feasible(state)?
515        {
516            return Ok(StepOutcome::AssumeRejected);
517        }
518        state.pc += 1;
519
520        if executor.spec_id < opcode_activation(op) {
521            state.return_data = SymReturnData::empty(&mut self.cx);
522            return Ok(StepOutcome::ExceptionalHalt);
523        }
524
525        // The EVM halts a frame exceptionally before it runs an undefined opcode or one whose
526        // stack inputs or outputs do not fit, so the handlers below never see such a stack.
527        let fits = OpCode::new(op).is_some_and(|opcode| {
528            let height = state.stack.len();
529            let inputs = opcode.inputs() as usize;
530            height >= inputs && height - inputs + opcode.outputs() as usize <= STACK_LIMIT
531        });
532        if !fits {
533            state.return_data = SymReturnData::empty(&mut self.cx);
534            return Ok(StepOutcome::ExceptionalHalt);
535        }
536
537        match op {
538            opcode::PUSH0 => {
539                state.stack.push(SymExpr::zero(&mut self.cx))?;
540            }
541            opcode::PUSH1..=opcode::PUSH32 => {
542                let n = (op - opcode::PUSH1 + 1) as usize;
543                // Data cut off by the end of the code is zero-padded, and the frame then stops.
544                let value = code.push_data_word(&mut self.cx, state.pc, n);
545                state.pc = state.pc.saturating_add(n);
546                state.stack.push(value)?;
547            }
548            opcode::DUP1..=opcode::DUP16 => {
549                let n = (op - opcode::DUP1 + 1) as usize;
550                let value = state.stack.peek(n - 1)?.clone();
551                state.stack.push(value)?;
552            }
553            opcode::SWAP1..=opcode::SWAP16 => {
554                let n = (op - opcode::SWAP1 + 1) as usize;
555                state.stack.exchange(0, n)?;
556            }
557            opcode::DUPN | opcode::SWAPN | opcode::EXCHANGE => {
558                // EIP-8024: a missing trailing immediate reads as zero, like revm's padded code.
559                let immediate = code.opcode(&mut self.cx, state.pc)?.unwrap_or_default();
560                state.pc += 1;
561                let decoded = if op == opcode::EXCHANGE {
562                    decode_exchange_immediate(immediate)
563                } else {
564                    decode_stack_immediate(immediate).map(|n| (0, n))
565                };
566                let Some((n, m)) = decoded else {
567                    return Ok(StepOutcome::ExceptionalHalt);
568                };
569                if op == opcode::DUPN {
570                    let value = state.stack.peek(m - 1)?.clone();
571                    state.stack.push(value)?;
572                } else {
573                    state.stack.exchange(n, m)?;
574                }
575            }
576            opcode::STOP => {
577                // STOP returns no output; drop the return data of the frame's last call.
578                state.return_data = SymReturnData::empty(&mut self.cx);
579                return Ok(StepOutcome::Halt);
580            }
581            opcode::ADD | opcode::SUB | opcode::MUL | opcode::AND | opcode::OR | opcode::XOR => {
582                let bin_op = match op {
583                    opcode::ADD => SymBinOp::Add,
584                    opcode::SUB => SymBinOp::Sub,
585                    opcode::MUL => SymBinOp::Mul,
586                    opcode::AND => SymBinOp::And,
587                    opcode::OR => SymBinOp::Or,
588                    _ => SymBinOp::Xor,
589                };
590                state.bin_word(&mut self.cx, bin_op)?
591            }
592            opcode::EXP => state.exp_word(&mut self.cx)?,
593            opcode::DIV | opcode::SDIV | opcode::MOD | opcode::SMOD => {
594                let bin_op = match op {
595                    opcode::DIV => SymBinOp::UDiv,
596                    opcode::SDIV => SymBinOp::SDiv,
597                    opcode::MOD => SymBinOp::URem,
598                    _ => SymBinOp::SRem,
599                };
600                state.bin_word_div_zero_guard(&mut self.cx, bin_op)?
601            }
602            opcode::ADDMOD | opcode::MULMOD => {
603                let a = state.stack.pop()?;
604                let b = state.stack.pop()?;
605                let n = state.stack.pop()?;
606                let tern_op =
607                    if op == opcode::ADDMOD { SymTernOp::AddMod } else { SymTernOp::MulMod };
608                state.stack.push(SymExpr::ternop(&mut self.cx, tern_op, a, b, n))?;
609            }
610            opcode::LT | opcode::GT | opcode::SLT | opcode::SGT => {
611                let op_pc = state.pc - 1;
612                let cmp_op = match op {
613                    opcode::LT => SymCmpOp::Ult,
614                    opcode::GT => SymCmpOp::Ugt,
615                    opcode::SLT => SymCmpOp::Slt,
616                    _ => SymCmpOp::Sgt,
617                };
618                let condition = state.cmp_word_condition(&mut self.cx, cmp_op)?;
619                return self.push_comparison_result(state, op_pc, op, condition);
620            }
621            opcode::EQ => {
622                let op_pc = state.pc - 1;
623                let a = state.stack.pop()?;
624                let b = state.stack.pop()?;
625                let condition = SymBoolExpr::eq(&mut self.cx, b, a);
626                return self.push_comparison_result(state, op_pc, op, condition);
627            }
628            opcode::ISZERO => {
629                let op_pc = state.pc - 1;
630                let value = state.stack.pop()?;
631                let value = value.into_zero_bool(&mut self.cx);
632                return self.push_comparison_result(state, op_pc, op, value);
633            }
634            opcode::NOT => {
635                let value = state.stack.pop()?;
636                state.stack.push(SymExpr::not(&mut self.cx, value))?;
637            }
638            opcode::SIGNEXTEND => {
639                let byte_index = state.stack.pop()?;
640                let value = state.stack.pop()?;
641                state.stack.push(signextend_word_dynamic(&mut self.cx, byte_index, value))?;
642            }
643            opcode::BYTE => {
644                let index = state.stack.pop()?;
645                let word = state.stack.pop()?;
646                state.stack.push(byte_word_dynamic(&mut self.cx, index, word))?;
647            }
648            opcode::SHL => state.shift_word(&mut self.cx, SymBinOp::Shl)?,
649            opcode::SHR => state.shift_word(&mut self.cx, SymBinOp::Shr)?,
650            opcode::SAR => state.shift_word(&mut self.cx, SymBinOp::Sar)?,
651            opcode::CLZ => {
652                let value = state.stack.pop()?;
653                state.stack.push(clz_word(&mut self.cx, value))?;
654            }
655            opcode::KECCAK256 => {
656                let offset = state.stack.peek(0)?.clone();
657                let size = state.stack.peek(1)?.clone();
658                if let Some(outcome) =
659                    self.guard_memory_range(executor, state, worklist, &offset, &size)?
660                {
661                    return Ok(outcome);
662                }
663                let offset = state.stack.pop()?;
664                let size = state.stack.pop()?;
665                match state.constrained_usize_checked(&mut self.cx, &size) {
666                    Some(Ok(size)) => {
667                        let bytes = state.memory.read_byte_exprs_offset(&mut self.cx, offset, size);
668                        let hash = keccak_word(&mut self.cx, bytes.clone());
669                        let has_mapping_hook = state
670                            .mapping_storage_store_hooks
671                            .keys()
672                            .any(|(address, _)| *address == state.storage_address);
673                        if has_mapping_hook && !state.storage_hook_active && size == 64 {
674                            state
675                                .mapping_hook_keccak_preimages
676                                .entry((state.storage_address, hash.clone()))
677                                .or_insert_with(|| bytes.into());
678                        }
679                        state.stack.push(hash)?;
680                    }
681                    Some(Err(_)) => {
682                        return Ok(StepOutcome::Revert);
683                    }
684                    None => {
685                        let has_mapping_hook = state
686                            .mapping_storage_store_hooks
687                            .keys()
688                            .any(|(address, _)| *address == state.storage_address);
689                        if has_mapping_hook && !state.storage_hook_active {
690                            let mapping_size = SymExpr::constant(&mut self.cx, U256::from(64));
691                            let mapping_size_feasible =
692                                SymBoolExpr::eq(&mut self.cx, size.clone(), mapping_size);
693                            let (_, mapping_size_feasible) =
694                                self.constraints_with_condition(state, mapping_size_feasible)?;
695                            if mapping_size_feasible {
696                                self.defer_incomplete(
697                                    "symbolic KECCAK256 size may conceal mapping provenance",
698                                );
699                            }
700                        }
701                        let max_limit = self.config.max_calldata_bytes as usize;
702                        let max_size = match self.solver_upper_bound_usize(
703                            state,
704                            &size,
705                            max_limit,
706                            "symbolic SHA3 size",
707                        ) {
708                            Ok(max_size) => max_size,
709                            // An equivalence check hashes an unbounded region to a symbol named
710                            // by the whole memory, the offset and the size, so equal memory
711                            // gives the two programs the same hash.
712                            Err(SymbolicError::Unsupported(_)) if self.equivalence.is_some() => {
713                                let mut identity = state.memory.identity_exprs(&mut self.cx);
714                                identity.push(offset);
715                                identity.push(size);
716                                let digest = ExpressionDigests::identity(identity.iter());
717                                let hash =
718                                    SymExpr::var(&mut self.cx, &format!("keccak_{digest:x}"));
719                                state.stack.push(hash)?;
720                                return Ok(StepOutcome::Continue);
721                            }
722                            Err(err) => return Err(err),
723                        };
724                        let bytes = state.memory.read_byte_exprs_symbolic_size(
725                            &mut self.cx,
726                            offset,
727                            size.clone(),
728                            max_size,
729                        );
730                        state.stack.push(keccak_word_with_len(&mut self.cx, bytes, size))?;
731                    }
732                }
733            }
734            opcode::ADDRESS | opcode::CALLER | opcode::ORIGIN | opcode::CALLVALUE => {
735                let value = match op {
736                    opcode::ADDRESS => state.address_word.clone(),
737                    opcode::CALLER => state.caller_word.clone(),
738                    opcode::ORIGIN => state.origin_word.clone(),
739                    _ => state.callvalue.clone(),
740                };
741                state.stack.push(value)?;
742            }
743            opcode::BLOCKHASH => {
744                let number = state.stack.pop()?;
745                let hash = state.block.block_hash_word(&mut self.cx, executor, number)?;
746                state.stack.push(hash)?;
747            }
748            opcode::BALANCE => {
749                let target = state.stack.pop()?;
750                let balance = state.balance_word(&mut self.cx, executor, target)?;
751                state.stack.push(balance)?;
752            }
753            opcode::SELFBALANCE => {
754                let balance = state.balance(&mut self.cx, executor, state.address)?;
755                state.stack.push(balance)?;
756            }
757            opcode::EXTCODESIZE => {
758                let target = state.stack.pop()?;
759                let size = state.extcode_size_word(&mut self.cx, executor, target)?;
760                state.stack.push(size)?;
761            }
762            opcode::EXTCODEHASH => {
763                let target = state.stack.pop()?;
764                let hash = state.extcode_hash_word(&mut self.cx, executor, target)?;
765                state.stack.push(hash)?;
766            }
767            opcode::EXTCODECOPY => {
768                let dest = state.stack.peek(1)?.clone();
769                let size = state.stack.peek(3)?.clone();
770                if let Some(outcome) =
771                    self.guard_memory_range(executor, state, worklist, &dest, &size)?
772                {
773                    return Ok(outcome);
774                }
775                let target = state.stack.pop()?;
776                let dest = state.stack.pop()?;
777                let offset = state.stack.pop()?;
778                let size = state.stack.pop()?;
779                match state.constrained_usize_checked(&mut self.cx, &size) {
780                    Some(Ok(size)) => {
781                        let bytes = state.extcode_bytes_word(
782                            &mut self.cx,
783                            executor,
784                            target,
785                            offset,
786                            size,
787                        )?;
788                        state.memory.store_bytes_offset(&mut self.cx, dest, bytes);
789                    }
790                    Some(Err(_)) => {
791                        return Ok(StepOutcome::Revert);
792                    }
793                    None => {
794                        let max_limit = self.config.max_calldata_bytes as usize;
795                        let max_size = self.solver_upper_bound_usize(
796                            state,
797                            &size,
798                            max_limit,
799                            "symbolic EXTCODECOPY size",
800                        )?;
801                        if max_size != 0 {
802                            let bytes = state.extcode_bytes_word(
803                                &mut self.cx,
804                                executor,
805                                target,
806                                offset,
807                                max_size,
808                            )?;
809                            state.memory.copy_bytes_size_offset(&mut self.cx, dest, size, bytes)?;
810                        }
811                    }
812                }
813            }
814            opcode::CALLDATALOAD => {
815                let offset = state.stack.pop()?;
816                let value = state.calldata.load_word(&mut self.cx, offset);
817                state.stack.push(value)?;
818            }
819            opcode::CALLDATASIZE => {
820                let size = state.calldata.size_word();
821                state.stack.push(size)?;
822            }
823            opcode::CALLDATACOPY => {
824                let dest = state.stack.peek(0)?.clone();
825                let size = state.stack.peek(2)?.clone();
826                if let Some(outcome) =
827                    self.guard_memory_range(executor, state, worklist, &dest, &size)?
828                {
829                    return Ok(outcome);
830                }
831                let dest = state.stack.pop()?;
832                let offset = state.stack.pop()?;
833                let size = state.stack.pop()?;
834                match state.constrained_usize_checked(&mut self.cx, &size) {
835                    Some(Ok(size)) => {
836                        if size != 0 {
837                            let CallFrame { memory, calldata, .. } = &mut state.frame;
838                            memory.copy_calldata_to_offset(
839                                &mut self.cx,
840                                dest,
841                                offset,
842                                size,
843                                calldata,
844                            );
845                        }
846                    }
847                    Some(Err(_)) => {
848                        return Ok(StepOutcome::Revert);
849                    }
850                    None => {
851                        let max_limit = self.config.max_calldata_bytes as usize;
852                        let max_size = self.solver_upper_bound_usize(
853                            state,
854                            &size,
855                            max_limit,
856                            "symbolic CALLDATACOPY size",
857                        )?;
858                        if max_size != 0 {
859                            let CallFrame { memory, calldata, .. } = &mut state.frame;
860                            memory.copy_calldata_symbolic_size(
861                                &mut self.cx,
862                                dest,
863                                offset,
864                                size,
865                                max_size,
866                                calldata,
867                            )?;
868                        }
869                    }
870                }
871            }
872            opcode::CODESIZE => {
873                let value = SymExpr::constant(&mut self.cx, U256::from(code.len()));
874                state.stack.push(value)?;
875            }
876            opcode::CODECOPY => {
877                let dest = state.stack.peek(0)?.clone();
878                let size = state.stack.peek(2)?.clone();
879                if let Some(outcome) =
880                    self.guard_memory_range(executor, state, worklist, &dest, &size)?
881                {
882                    return Ok(outcome);
883                }
884                let dest = state.stack.pop()?;
885                let offset = state.stack.pop()?;
886                let size = state.stack.pop()?;
887                match state.constrained_usize_checked(&mut self.cx, &size) {
888                    Some(Ok(size)) => {
889                        let bytes = code.read_bytes_offset(&mut self.cx, offset, size);
890                        state.memory.store_bytes_offset(&mut self.cx, dest, bytes);
891                    }
892                    Some(Err(_)) => {
893                        return Ok(StepOutcome::Revert);
894                    }
895                    None => {
896                        let max_limit = self.config.max_calldata_bytes as usize;
897                        let max_size = self.solver_upper_bound_usize(
898                            state,
899                            &size,
900                            max_limit,
901                            "symbolic CODECOPY size",
902                        )?;
903                        if max_size != 0 {
904                            let bytes = code.read_bytes_offset(&mut self.cx, offset, max_size);
905                            state.memory.copy_bytes_size_offset(&mut self.cx, dest, size, bytes)?;
906                        }
907                    }
908                }
909            }
910            opcode::RETURNDATASIZE => {
911                let size = state.return_data.len_word.clone();
912                state.stack.push(size)?;
913            }
914            opcode::RETURNDATACOPY => {
915                let dest = state.stack.peek(0)?.clone();
916                let offset = state.stack.peek(1)?.clone();
917                let size = state.stack.peek(2)?.clone();
918                if let Some(outcome) =
919                    self.guard_memory_range(executor, state, worklist, &dest, &size)?
920                {
921                    return Ok(outcome);
922                }
923                if let Some(outcome) =
924                    self.guard_returndata_copy_range(state, worklist, &offset, &size)?
925                {
926                    return Ok(outcome);
927                }
928                let dest = state.stack.pop()?;
929                let offset = state.stack.pop()?;
930                let size = state.stack.pop()?;
931                match state.constrained_usize_checked(&mut self.cx, &size) {
932                    Some(Ok(size)) => {
933                        let CallFrame { memory, return_data, .. } = &mut state.frame;
934                        memory.copy_return_data_to_offset(
935                            &mut self.cx,
936                            dest,
937                            offset,
938                            size,
939                            return_data,
940                        )?;
941                    }
942                    Some(Err(_)) => {
943                        return Ok(StepOutcome::Revert);
944                    }
945                    None => {
946                        let available = state
947                            .constrained_usize(&mut self.cx, &offset)
948                            .map(|offset| state.return_data.len().saturating_sub(offset))
949                            .unwrap_or(state.return_data.len());
950                        let max_limit = available.min(self.config.max_calldata_bytes as usize);
951                        let max_size = self.solver_upper_bound_usize(
952                            state,
953                            &size,
954                            max_limit,
955                            "symbolic RETURNDATACOPY size",
956                        )?;
957                        let CallFrame { memory, return_data, .. } = &mut state.frame;
958                        memory.copy_return_data_symbolic_size(
959                            &mut self.cx,
960                            dest,
961                            offset,
962                            size,
963                            max_size,
964                            return_data,
965                        )?;
966                    }
967                }
968            }
969            opcode::POP => {
970                state.stack.pop()?;
971            }
972            opcode::MLOAD => {
973                let offset = state.stack.peek(0)?.clone();
974                if let Some(outcome) =
975                    self.guard_fixed_memory_access(executor, state, worklist, &offset, 32)?
976                {
977                    return Ok(outcome);
978                }
979                let offset = state.stack.pop()?;
980                let value = state.memory.load_word_offset(&mut self.cx, offset)?;
981                state.stack.push(value)?;
982            }
983            opcode::MSTORE => {
984                let offset = state.stack.peek(0)?.clone();
985                if let Some(outcome) =
986                    self.guard_fixed_memory_access(executor, state, worklist, &offset, 32)?
987                {
988                    return Ok(outcome);
989                }
990                let offset = state.stack.pop()?;
991                let value = state.stack.pop()?;
992                let minimum_offset = state.lower_bound_usize(&offset);
993                state.memory.store_word_offset(&mut self.cx, offset, value, minimum_offset);
994            }
995            opcode::MSTORE8 => {
996                let offset = state.stack.peek(0)?.clone();
997                if let Some(outcome) =
998                    self.guard_fixed_memory_access(executor, state, worklist, &offset, 1)?
999                {
1000                    return Ok(outcome);
1001                }
1002                let offset = state.stack.pop()?;
1003                let value = state.stack.pop()?;
1004                let minimum_offset = state.lower_bound_usize(&offset);
1005                state.memory.store_byte_offset(&mut self.cx, offset, value, minimum_offset);
1006            }
1007            opcode::SLOAD => {
1008                let key = state.stack.pop()?;
1009                state.record_sload(state.storage_address, key.clone());
1010                if let Some(slot) = key.as_const()
1011                    && !self.folded_slots.resolve_nested(&mut self.cx, slot, self.deadline)
1012                {
1013                    self.defer_incomplete("folded mapping slot search incomplete");
1014                }
1015                let concrete_key = state.constrained_word(&mut self.cx, &key);
1016                let value = state.world.sload(
1017                    &mut self.cx,
1018                    executor,
1019                    state.storage_address,
1020                    key.clone(),
1021                    concrete_key,
1022                )?;
1023                state.stack.push(value.clone())?;
1024                if !state.storage_hook_active
1025                    && let Some(hook) =
1026                        state.storage_load_hooks.get(&state.storage_address).copied()
1027                {
1028                    let account =
1029                        SymExpr::constant(&mut self.cx, address_word(state.storage_address));
1030                    let calldata =
1031                        self.storage_hook_calldata(hook.callback_selector, [account, key, value]);
1032                    return self.invoke_storage_hook(
1033                        executor,
1034                        state,
1035                        worklist,
1036                        completed_paths,
1037                        hook,
1038                        calldata,
1039                    );
1040                }
1041            }
1042            opcode::SSTORE => {
1043                if state.is_static {
1044                    // Forge records the access in `step`, before the static-call check halts.
1045                    if let Ok(key) = state.stack.peek(0).cloned() {
1046                        state.record_sstore(state.storage_address, key);
1047                    }
1048                    state.return_data = SymReturnData::empty(&mut self.cx);
1049                    return Ok(StepOutcome::ExceptionalHalt);
1050                }
1051                let key = state.stack.peek(0)?.clone();
1052                state.stack.peek(1)?;
1053                if let Some(slot) = key.as_const()
1054                    && !self.folded_slots.resolve_nested(&mut self.cx, slot, self.deadline)
1055                {
1056                    self.defer_incomplete("folded mapping slot search incomplete");
1057                }
1058                let hook = (!state.storage_hook_active)
1059                    .then(|| state.storage_store_hooks.get(&state.storage_address).copied())
1060                    .flatten();
1061                let mapping = if state.storage_hook_active {
1062                    MappingStorageProvenance::None
1063                } else {
1064                    self.mapping_storage_provenance(state, &key)?
1065                };
1066                let mapping = match mapping {
1067                    MappingStorageProvenance::None => None,
1068                    MappingStorageProvenance::Exact(provenance) => state
1069                        .mapping_storage_store_hooks
1070                        .get(&(state.storage_address, provenance.root_slot))
1071                        .copied()
1072                        .map(|hook| (hook, provenance)),
1073                    MappingStorageProvenance::Fork { equality, inequality } => {
1074                        let store_pc = state.pc - 1;
1075                        let mut equality_state = state.clone();
1076                        equality_state.pc = store_pc;
1077                        equality_state.depth = equality_state.depth.saturating_sub(1);
1078                        equality_state.constraints = equality;
1079                        let mut inequality_state = state.clone();
1080                        inequality_state.pc = store_pc;
1081                        inequality_state.depth = inequality_state.depth.saturating_sub(1);
1082                        inequality_state.constraints = inequality;
1083                        worklist.push_back(equality_state);
1084                        worklist.push_back(inequality_state);
1085                        return Ok(StepOutcome::Forked);
1086                    }
1087                };
1088                state.stack.pop()?;
1089                let value = state.stack.pop()?;
1090                state.record_sstore(state.storage_address, key.clone());
1091                let old_value = if hook.is_some() || mapping.is_some() {
1092                    let concrete_key = state.constrained_word(&mut self.cx, &key);
1093                    Some(state.world.sload(
1094                        &mut self.cx,
1095                        executor,
1096                        state.storage_address,
1097                        key.clone(),
1098                        concrete_key,
1099                    )?)
1100                } else {
1101                    None
1102                };
1103                state.world.sstore(state.storage_address, key.clone(), value.clone());
1104                if let Some(hook) = hook {
1105                    let account =
1106                        SymExpr::constant(&mut self.cx, address_word(state.storage_address));
1107                    let calldata = self.storage_hook_calldata(
1108                        hook.callback_selector,
1109                        [
1110                            account,
1111                            key,
1112                            old_value.expect("old value loaded for storage hook"),
1113                            value,
1114                        ],
1115                    );
1116                    return self.invoke_storage_hook(
1117                        executor,
1118                        state,
1119                        worklist,
1120                        completed_paths,
1121                        hook,
1122                        calldata,
1123                    );
1124                } else if let Some((hook, provenance)) = mapping {
1125                    let account =
1126                        SymExpr::constant(&mut self.cx, address_word(state.storage_address));
1127                    let root = SymExpr::constant(&mut self.cx, provenance.root_slot);
1128                    let calldata = self.mapping_storage_hook_calldata(
1129                        hook.callback_selector,
1130                        [
1131                            account,
1132                            key,
1133                            root,
1134                            old_value.expect("old value loaded for mapping storage hook"),
1135                            value,
1136                        ],
1137                        provenance.keys,
1138                    );
1139                    return self.invoke_storage_hook(
1140                        executor,
1141                        state,
1142                        worklist,
1143                        completed_paths,
1144                        hook,
1145                        calldata,
1146                    );
1147                }
1148            }
1149            opcode::TLOAD => {
1150                let key = state.stack.pop()?;
1151                let value = state.world.tload(&mut self.cx, state.storage_address, key);
1152                state.stack.push(value)?;
1153            }
1154            opcode::TSTORE => {
1155                if state.is_static {
1156                    state.return_data = SymReturnData::empty(&mut self.cx);
1157                    return Ok(StepOutcome::ExceptionalHalt);
1158                }
1159                let key = state.stack.pop()?;
1160                let value = state.stack.pop()?;
1161                state.world.tstore(state.storage_address, key, value);
1162            }
1163            opcode::JUMP => {
1164                let dest = state.stack.pop()?;
1165                let Some(dest) =
1166                    self.resolve_jump_destination(state, code, dest, "symbolic JUMP destination")?
1167                else {
1168                    state.return_data = SymReturnData::empty(&mut self.cx);
1169                    return Ok(StepOutcome::ExceptionalHalt);
1170                };
1171                if !self.take_loop_jump(state, code, state.pc, dest) {
1172                    return Ok(StepOutcome::AssumeRejected);
1173                }
1174                state.pc = dest;
1175            }
1176            opcode::JUMPI => {
1177                let dest = state.stack.pop()?;
1178                let cond = state.stack.pop()?;
1179                match cond.as_const().map(|value| !value.is_zero()) {
1180                    Some(true) => {
1181                        let Some(dest) = self.resolve_jump_destination(
1182                            state,
1183                            code,
1184                            dest,
1185                            "symbolic JUMPI destination",
1186                        )?
1187                        else {
1188                            state.return_data = SymReturnData::empty(&mut self.cx);
1189                            return Ok(StepOutcome::ExceptionalHalt);
1190                        };
1191                        if !self.take_loop_jump(state, code, state.pc, dest) {
1192                            return Ok(StepOutcome::AssumeRejected);
1193                        }
1194                        state.pc = dest;
1195                    }
1196                    Some(false) => {}
1197                    None => {
1198                        let true_cond = cond.nonzero_bool(&mut self.cx);
1199                        let dest = match self.resolve_jump_destination(
1200                            state,
1201                            code,
1202                            dest,
1203                            "symbolic JUMPI destination",
1204                        ) {
1205                            Ok(Some(dest)) => dest,
1206                            Ok(None) => {
1207                                return self.branch_invalid_jumpi(state, worklist, true_cond);
1208                            }
1209                            Err(err) => {
1210                                let (_, taken_sat) =
1211                                    self.constraints_with_condition(state, true_cond.clone())?;
1212                                if taken_sat {
1213                                    return Err(err);
1214                                }
1215                                let (_, not_taken_seed_models) =
1216                                    state.split_corpus_seed_models(&true_cond);
1217                                state.constraints.push(true_cond.not(&mut self.cx));
1218                                state.set_corpus_seed_models(not_taken_seed_models);
1219                                return Ok(StepOutcome::Continue);
1220                            }
1221                        };
1222                        let op_pc = state.pc.saturating_sub(1);
1223                        let _branch_span = trace_span!("jumpi_branch", pc = op_pc, dest).entered();
1224                        let false_cond = true_cond.clone().not(&mut self.cx);
1225                        let fallthrough = state.pc;
1226                        let (true_seed_models, false_seed_models) =
1227                            state.split_corpus_seed_models(&true_cond);
1228                        let mut true_state = state.clone();
1229                        true_state.constraints.push(true_cond);
1230                        true_state.set_corpus_seed_models(true_seed_models);
1231                        true_state.pc = dest;
1232                        let mut false_state = state.clone();
1233                        false_state.constraints.push(false_cond);
1234                        false_state.set_corpus_seed_models(false_seed_models);
1235                        false_state.pc = fallthrough;
1236
1237                        let true_pending =
1238                            self.take_loop_jump(&mut true_state, code, fallthrough, dest);
1239                        if true_pending {
1240                            true_state.defer_feasibility_check();
1241                        }
1242                        false_state.defer_feasibility_check();
1243                        trace!(true_pending, false_pending = true, "JUMPI symbolic branch");
1244                        if true_pending {
1245                            let true_seed_count = true_state.corpus_seed_model_count();
1246                            let false_seed_count = false_state.corpus_seed_model_count();
1247                            match (
1248                                false_seed_count.cmp(&true_seed_count),
1249                                self.config.exploration_order,
1250                            ) {
1251                                (std::cmp::Ordering::Greater, SymbolicExplorationOrder::Bfs)
1252                                | (std::cmp::Ordering::Less, SymbolicExplorationOrder::Dfs) => {
1253                                    worklist.push_back(false_state);
1254                                    worklist.push_back(true_state);
1255                                }
1256                                (std::cmp::Ordering::Greater, SymbolicExplorationOrder::Dfs)
1257                                | (std::cmp::Ordering::Less, SymbolicExplorationOrder::Bfs)
1258                                | (std::cmp::Ordering::Equal, _) => {
1259                                    worklist.push_back(true_state);
1260                                    worklist.push_back(false_state);
1261                                }
1262                            }
1263                        } else {
1264                            worklist.push_back(false_state);
1265                        }
1266                        return Ok(StepOutcome::Forked);
1267                    }
1268                }
1269            }
1270            opcode::PC => {
1271                let pc = state.pc - 1;
1272                let pc = SymExpr::constant(&mut self.cx, U256::from(pc));
1273                state.stack.push(pc)?;
1274            }
1275            opcode::MSIZE => {
1276                let size = state.memory.size_word(&mut self.cx);
1277                state.stack.push(size)?;
1278            }
1279            opcode::GAS => {
1280                // An equivalence check gives each program its own unconstrained gas readings.
1281                let gas = if let Some(mode) = &mut self.equivalence {
1282                    mode.reads_gas = true;
1283                    state.fresh_word(&mut self.cx, "gas")
1284                } else {
1285                    state.fresh_gasleft(&mut self.cx)
1286                };
1287                state.stack.push(gas)?;
1288            }
1289            opcode::JUMPDEST => {}
1290            opcode::MCOPY => {
1291                let dest = state.stack.peek(0)?.clone();
1292                let src = state.stack.peek(1)?.clone();
1293                let size = state.stack.peek(2)?.clone();
1294                if let Some(outcome) =
1295                    self.guard_memory_range(executor, state, worklist, &dest, &size)?
1296                {
1297                    return Ok(outcome);
1298                }
1299                if let Some(outcome) =
1300                    self.guard_memory_range(executor, state, worklist, &src, &size)?
1301                {
1302                    return Ok(outcome);
1303                }
1304                let dest = state.stack.pop()?;
1305                let src = state.stack.pop()?;
1306                let size = state.stack.pop()?;
1307                match state.constrained_usize_checked(&mut self.cx, &size) {
1308                    Some(Ok(size)) => {
1309                        state.memory.copy_memory_to_offset(&mut self.cx, dest, src, size)?;
1310                    }
1311                    Some(Err(_)) => {
1312                        return Ok(StepOutcome::Revert);
1313                    }
1314                    None => {
1315                        let max_limit = self.config.max_calldata_bytes as usize;
1316                        let max_size = self.solver_upper_bound_usize(
1317                            state,
1318                            &size,
1319                            max_limit,
1320                            "symbolic MCOPY size",
1321                        )?;
1322                        if max_size != 0 {
1323                            state.memory.copy_memory_symbolic_size(
1324                                &mut self.cx,
1325                                dest,
1326                                src,
1327                                size,
1328                                max_size,
1329                            )?;
1330                        }
1331                    }
1332                }
1333            }
1334            opcode::RETURN | opcode::REVERT => {
1335                let offset = state.stack.peek(0)?.clone();
1336                let size = state.stack.peek(1)?.clone();
1337                if let Some(outcome) =
1338                    self.guard_memory_range(executor, state, worklist, &offset, &size)?
1339                {
1340                    return Ok(outcome);
1341                }
1342                return self.return_or_revert(state, op == opcode::REVERT);
1343            }
1344            opcode::INVALID => return Ok(StepOutcome::ExceptionalHalt),
1345            opcode::CALL => {
1346                return self.call(executor, state, worklist, completed_paths, CallKind::Call);
1347            }
1348            opcode::CALLCODE => {
1349                return self.call(executor, state, worklist, completed_paths, CallKind::CallCode);
1350            }
1351            opcode::DELEGATECALL => {
1352                return self.call(
1353                    executor,
1354                    state,
1355                    worklist,
1356                    completed_paths,
1357                    CallKind::DelegateCall,
1358                );
1359            }
1360            opcode::STATICCALL => {
1361                return self.call(executor, state, worklist, completed_paths, CallKind::StaticCall);
1362            }
1363            opcode::CREATE => {
1364                return self.create(executor, state, worklist, completed_paths, CreateKind::Create);
1365            }
1366            opcode::CREATE2 => {
1367                return self.create(
1368                    executor,
1369                    state,
1370                    worklist,
1371                    completed_paths,
1372                    CreateKind::Create2,
1373                );
1374            }
1375            opcode::SELFDESTRUCT => {
1376                if state.is_static {
1377                    state.return_data = SymReturnData::empty(&mut self.cx);
1378                    return Ok(StepOutcome::ExceptionalHalt);
1379                }
1380                let spec_id = executor.spec_id;
1381                // A fresh symbolic beneficiary slot never aliases an existing account, so the
1382                // credit would ignore the balance the beneficiary already holds.
1383                let beneficiary = state.stack.pop()?;
1384                let beneficiary = word_to_address(state.expect_constrained_word(
1385                    &mut self.cx,
1386                    beneficiary,
1387                    "symbolic SELFDESTRUCT beneficiary",
1388                )?);
1389                if spec_id < SpecId::CANCUN
1390                    || state.world.was_created_in_current_transaction(state.address)
1391                {
1392                    state.world.selfdestruct_legacy(
1393                        &mut self.cx,
1394                        executor,
1395                        state.address,
1396                        beneficiary,
1397                    )?;
1398                } else {
1399                    state.world.selfdestruct_cancun_existing(
1400                        &mut self.cx,
1401                        executor,
1402                        state.address,
1403                        beneficiary,
1404                    )?;
1405                }
1406                state.return_data = SymReturnData::empty(&mut self.cx);
1407                return Ok(StepOutcome::Halt);
1408            }
1409            opcode::CHAINID => {
1410                let value = state.block.chain_id.clone();
1411                state.stack.push(value)?;
1412            }
1413            opcode::BASEFEE => {
1414                let value = state.block.basefee.clone();
1415                state.stack.push(value)?;
1416            }
1417            opcode::GASPRICE => {
1418                let gas_price = state.gas_price.clone();
1419                state.stack.push(gas_price)?;
1420            }
1421            opcode::BLOBHASH => {
1422                let index = state.stack.pop()?;
1423                let index = state.expect_constrained_word(
1424                    &mut self.cx,
1425                    index,
1426                    "symbolic BLOBHASH index",
1427                )?;
1428                // An index past the blob list, including one beyond `usize`, reads zero.
1429                let hash = usize::try_from(index)
1430                    .ok()
1431                    .and_then(|index| state.block.blob_hashes.get(index))
1432                    .copied()
1433                    .unwrap_or_default();
1434                let hash = SymExpr::constant(&mut self.cx, U256::from_be_slice(hash.as_slice()));
1435                state.stack.push(hash)?;
1436            }
1437            opcode::COINBASE => {
1438                let coinbase = match state.block.coinbase_word.clone() {
1439                    Some(coinbase) => coinbase,
1440                    None => SymExpr::constant(&mut self.cx, address_word(state.block.coinbase)),
1441                };
1442                state.stack.push(coinbase)?;
1443            }
1444            opcode::TIMESTAMP => {
1445                let value = state.block.timestamp.clone();
1446                state.stack.push(value)?;
1447            }
1448            opcode::NUMBER => {
1449                let value = state.block.number.clone();
1450                state.stack.push(value)?;
1451            }
1452            opcode::DIFFICULTY => {
1453                let value = state.block.difficulty.clone();
1454                state.stack.push(value)?;
1455            }
1456            opcode::GASLIMIT => {
1457                let value = state.block.gaslimit.clone();
1458                state.stack.push(value)?;
1459            }
1460            opcode::BLOBBASEFEE => {
1461                let value = state.block.blob_basefee.clone();
1462                state.stack.push(value)?;
1463            }
1464            opcode::SLOTNUM => {
1465                let value = state.block.slot_num.clone();
1466                state.stack.push(value)?;
1467            }
1468            opcode::LOG0 | opcode::LOG1 | opcode::LOG2 | opcode::LOG3 | opcode::LOG4 => {
1469                if state.is_static {
1470                    state.return_data = SymReturnData::empty(&mut self.cx);
1471                    return Ok(StepOutcome::ExceptionalHalt);
1472                }
1473                let topics = (op - opcode::LOG0) as usize;
1474                let offset = state.stack.peek(0)?.clone();
1475                let size = state.stack.peek(1)?.clone();
1476                if let Some(outcome) =
1477                    self.guard_memory_range(executor, state, worklist, &offset, &size)?
1478                {
1479                    return Ok(outcome);
1480                }
1481                let offset = state.stack.pop()?;
1482                if !self.symbolic_gas() && offset.contains_gasleft() {
1483                    return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
1484                }
1485                let size = state.stack.pop()?;
1486                if !self.symbolic_gas() && size.contains_gasleft() {
1487                    return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
1488                }
1489                let (data_len, data) = match state.constrained_usize_checked(&mut self.cx, &size) {
1490                    Some(Ok(size)) => (
1491                        SymExpr::constant(&mut self.cx, U256::from(size)),
1492                        state.memory.read_bytes_offset(&mut self.cx, offset, size),
1493                    ),
1494                    Some(Err(_)) => {
1495                        return Ok(StepOutcome::Revert);
1496                    }
1497                    None => {
1498                        let max_limit = self.config.max_calldata_bytes as usize;
1499                        let max_size = self.solver_upper_bound_usize(
1500                            state,
1501                            &size,
1502                            max_limit,
1503                            "symbolic LOG size",
1504                        )?;
1505                        let data = state.memory.read_bytes_symbolic_size(
1506                            &mut self.cx,
1507                            offset,
1508                            size.clone(),
1509                            max_size,
1510                        );
1511                        (size, data)
1512                    }
1513                };
1514                let mut log_topics = Vec::with_capacity(topics);
1515                for _ in 0..topics {
1516                    let topic = state.stack.pop()?;
1517                    if !self.symbolic_gas() && topic.contains_gasleft() {
1518                        return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
1519                    }
1520                    log_topics.push(topic);
1521                }
1522                return self.handle_log(
1523                    state,
1524                    worklist,
1525                    SymbolicLog::new(log_topics, data_len, data, state.address),
1526                );
1527            }
1528            _ => return Err(SymbolicError::UnsupportedOpcode(op)),
1529        };
1530
1531        Ok(StepOutcome::Continue)
1532    }
1533
1534    fn resolve_jump_destination(
1535        &mut self,
1536        state: &PathState,
1537        code: &SymCode,
1538        dest: SymExpr,
1539        unsupported: &'static str,
1540    ) -> Result<Option<usize>, SymbolicError> {
1541        let dest = state.expect_constrained_word(&mut self.cx, dest, unsupported)?;
1542        let Ok(dest) = usize::try_from(dest) else { return Ok(None) };
1543        Ok(code.is_valid_jumpdest(dest)?.then_some(dest))
1544    }
1545
1546    fn branch_invalid_jumpi(
1547        &mut self,
1548        state: &mut PathState,
1549        worklist: &mut VecDeque<PathState>,
1550        taken: SymBoolExpr,
1551    ) -> Result<StepOutcome, SymbolicError> {
1552        let (taken_constraints, taken_sat) =
1553            self.constraints_with_condition(state, taken.clone())?;
1554        let not_taken = taken.clone().not(&mut self.cx);
1555        let (taken_seed_models, not_taken_seed_models) = state.split_corpus_seed_models(&taken);
1556        if !taken_sat {
1557            state.constraints.push(not_taken);
1558            state.set_corpus_seed_models(not_taken_seed_models);
1559            return Ok(StepOutcome::Continue);
1560        }
1561
1562        let (not_taken_constraints, not_taken_sat) =
1563            self.constraints_with_condition(state, not_taken)?;
1564        if not_taken_sat {
1565            let mut fallthrough = state.clone();
1566            fallthrough.constraints = not_taken_constraints;
1567            fallthrough.set_corpus_seed_models(not_taken_seed_models);
1568            worklist.push_back(fallthrough);
1569        }
1570        state.constraints = taken_constraints;
1571        state.set_corpus_seed_models(taken_seed_models);
1572        state.return_data = SymReturnData::empty(&mut self.cx);
1573        Ok(StepOutcome::ExceptionalHalt)
1574    }
1575
1576    fn guard_returndata_copy_range(
1577        &mut self,
1578        state: &mut PathState,
1579        worklist: &mut VecDeque<PathState>,
1580        offset: &SymExpr,
1581        size: &SymExpr,
1582    ) -> Result<Option<StepOutcome>, SymbolicError> {
1583        if !self.symbolic_gas() && (offset.contains_gasleft() || size.contains_gasleft()) {
1584            return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
1585        }
1586        let return_data_len = state.return_data.len_word.clone();
1587        let offset_in_bounds = SymBoolExpr::cmp_word_expr(
1588            &mut self.cx,
1589            SymCmpOp::Ule,
1590            offset,
1591            return_data_len.clone(),
1592        );
1593        let remaining =
1594            SymExpr::binop(&mut self.cx, SymBinOp::Sub, return_data_len, offset.clone());
1595        let size_in_bounds =
1596            SymBoolExpr::cmp_word_expr(&mut self.cx, SymCmpOp::Ule, size, remaining);
1597        let valid_access = SymBoolExpr::and(&mut self.cx, vec![offset_in_bounds, size_in_bounds]);
1598        self.apply_memory_access_guard(state, worklist, valid_access)
1599    }
1600
1601    pub(super) fn return_or_revert(
1602        &mut self,
1603        state: &mut PathState,
1604        is_revert: bool,
1605    ) -> Result<StepOutcome, SymbolicError> {
1606        let offset = state.stack.pop()?;
1607        let size = state.stack.pop()?;
1608        match state.constrained_usize_checked(&mut self.cx, &size) {
1609            Some(Ok(size)) => {
1610                state.return_data = state.memory.return_data(&mut self.cx, offset, size)?;
1611            }
1612            Some(Err(_)) => return Ok(StepOutcome::Revert),
1613            None => {
1614                let max_limit = self.config.max_calldata_bytes as usize;
1615                let reason =
1616                    if is_revert { "symbolic REVERT size" } else { "symbolic RETURN size" };
1617                let max_size = self.solver_upper_bound_usize(state, &size, max_limit, reason)?;
1618                state.return_data =
1619                    state.memory.return_data_symbolic_size(&mut self.cx, offset, size, max_size)?;
1620            }
1621        }
1622        if is_revert { self.classify_revert(state) } else { Ok(StepOutcome::Halt) }
1623    }
1624
1625    pub(super) fn classify_revert(
1626        &mut self,
1627        state: &mut PathState,
1628    ) -> Result<StepOutcome, SymbolicError> {
1629        // Forge consumes this assumption in call_end, not create_end. A constructor must leave
1630        // both its revert bytes and any pending assumption for the caller to handle.
1631        let assumed = !state.frame.is_constructor && state.assume_no_revert_next_call.is_some();
1632        if assumed
1633            && let Some(assumption) = state.assume_no_revert_next_call.take()
1634            && self.assume_no_revert_matches(
1635                state,
1636                &assumption,
1637                assumption.reverted_by.unwrap_or(state.address),
1638                &state.return_data,
1639            )?
1640        {
1641            state.return_data =
1642                SymReturnData::from_concrete_bytes(&mut self.cx, MAGIC_ASSUME.to_vec());
1643        }
1644        // Forge's call_end then skips `vm.expectRevert` for this revert. A nested frame leaves it
1645        // pending for later calls, which is not modeled.
1646        if assumed && state.call_depth != 0 && state.expected_revert.is_some() {
1647            return Err(SymbolicError::Unsupported(
1648                "symbolic vm.expectRevert pending after vm.assumeNoRevert",
1649            ));
1650        }
1651        if state.call_depth != 0 {
1652            return Ok(StepOutcome::Revert);
1653        }
1654        let data = state.return_data.read_concrete(&mut self.cx, "symbolic revert data");
1655        // Like Forge's fuzz and invariant runners, a `vm.assume` or `vm.assumeNoRevert` rejection
1656        // or a `vm.skip` that reaches the top frame discards the run. Invariant predicates still
1657        // treat it as a revert.
1658        if !state.invariant_predicate
1659            && data
1660                .as_deref()
1661                .is_ok_and(|data| data == MAGIC_ASSUME || data.starts_with(MAGIC_SKIP))
1662        {
1663            return Ok(StepOutcome::AssumeRejected);
1664        }
1665        // Like Forge, a test that reverts after a failed assertion fails, even when the assertion
1666        // was caught or only set the fail slot.
1667        if state.root_calldata.is_some() && state.assertion_failed {
1668            return Ok(StepOutcome::Failure);
1669        }
1670        // Like Forge's `call_end` for the test call, a pending `vm.expectRevert` that a frame
1671        // deeper left pending passes the depth check and turns a matching revert into a return.
1672        if state.root_calldata.is_some()
1673            && !assumed
1674            && let Some(mut expected) = state.expected_revert.take_if(|e| e.deeper_frame_ran())
1675        {
1676            let reverter = expected.reverted_by(Some(state.address), state.first_failed_callee);
1677            let return_data = state.return_data.clone();
1678            if !self.expected_revert_matches(state, &expected, reverter, &return_data)? {
1679                return Ok(StepOutcome::Failure);
1680            }
1681            if !expected.consume_one() {
1682                state.expected_revert = Some(expected);
1683            }
1684            return Ok(StepOutcome::Halt);
1685        }
1686        // In `check*`/`prove*` tests, a `CheatcodeError` that reaches the top frame, such as an
1687        // unmet `vm.expectRevert`, is a failure. Invariant handlers treat it as a revert.
1688        // Match its selector independently of the memory address and the rest of the payload.
1689        if state.root_calldata.is_some()
1690            && let Some(condition) =
1691                cheatcode_error_revert_condition(&mut self.cx, &state.return_data)
1692            && let Some(constraints) = self.constraints_for_condition(state, condition)?
1693        {
1694            state.constraints = constraints;
1695            return Ok(StepOutcome::Failure);
1696        }
1697        match data {
1698            Ok(data) => {
1699                if is_assertion_revert(&data) {
1700                    return Ok(StepOutcome::Failure);
1701                }
1702            }
1703            // Symbolic revert data fails on the paths where it decodes as an assertion failure.
1704            Err(_) => {
1705                if let Some(condition) =
1706                    assertion_revert_condition(&mut self.cx, &state.return_data)
1707                    && let Some(constraints) = self.constraints_for_condition(state, condition)?
1708                {
1709                    state.constraints = constraints;
1710                    return Ok(StepOutcome::Failure);
1711                }
1712            }
1713        }
1714        // A call that failed a pending `vm.expectEmit` reverted with a bare string, so an
1715        // uncaught failure is classified from the expectation, not from the revert data.
1716        if state.root_calldata.is_some()
1717            && state.expected_emit.as_ref().is_some_and(ExpectedEmit::failed)
1718        {
1719            return Ok(StepOutcome::Failure);
1720        }
1721        Ok(StepOutcome::Revert)
1722    }
1723}
1724
1725/// Returns the activation fork for opcodes implemented by the symbolic executor.
1726const fn opcode_activation(op: u8) -> SpecId {
1727    match op {
1728        opcode::DELEGATECALL => SpecId::HOMESTEAD,
1729        opcode::RETURNDATASIZE | opcode::RETURNDATACOPY | opcode::STATICCALL | opcode::REVERT => {
1730            SpecId::BYZANTIUM
1731        }
1732        opcode::SHL | opcode::SHR | opcode::SAR | opcode::EXTCODEHASH | opcode::CREATE2 => {
1733            SpecId::PETERSBURG
1734        }
1735        opcode::CHAINID | opcode::SELFBALANCE => SpecId::ISTANBUL,
1736        opcode::BASEFEE => SpecId::LONDON,
1737        opcode::PUSH0 => SpecId::SHANGHAI,
1738        opcode::TLOAD | opcode::TSTORE | opcode::MCOPY | opcode::BLOBHASH | opcode::BLOBBASEFEE => {
1739            SpecId::CANCUN
1740        }
1741        opcode::CLZ => SpecId::OSAKA,
1742        opcode::SLOTNUM | opcode::DUPN | opcode::SWAPN | opcode::EXCHANGE => SpecId::AMSTERDAM,
1743        _ => SpecId::FRONTIER,
1744    }
1745}
1746
1747/// Decodes the EIP-8024 `DUPN`/`SWAPN` immediate into a stack depth.
1748///
1749/// Bytes `0x5b..=0x7f` are invalid so that the immediate is never a `JUMPDEST` or `PUSH` opcode.
1750const fn decode_stack_immediate(immediate: u8) -> Option<usize> {
1751    let x = immediate as usize;
1752    if x <= 90 || x >= 128 { Some((x + 145) % 256) } else { None }
1753}
1754
1755/// Decodes the EIP-8024 `EXCHANGE` immediate into a pair of stack depths `n < m`.
1756const fn decode_exchange_immediate(immediate: u8) -> Option<(usize, usize)> {
1757    let x = immediate as usize;
1758    if x > 81 && x < 128 {
1759        return None;
1760    }
1761    let k = x ^ 143;
1762    let (q, r) = (k / 16, k % 16);
1763    if q < r { Some((q + 1, r + 1)) } else { Some((r + 1, 29 - q)) }
1764}