1use super::*;
2use std::cmp::Reverse;
3
4impl SymbolicExecutor {
5 pub fn new(config: SymbolicConfig) -> Self {
13 let solver = SmtLibSubprocessSolver::from_config(&config);
14 Self {
15 config,
16 cx: SymCx::new(),
17 solver,
18 deferred_incomplete: None,
19 deadline: None,
20 nested_deferred_mode: DeferredPathMode::Skip,
21 stateless_retry_safe: true,
22 folded_slots: FoldedSlots::default(),
23 equivalence: None,
24 }
25 }
26
27 pub(super) fn ignores_out_of_gas(&self) -> bool {
29 self.equivalence.is_some_and(|mode| mode.ignore_out_of_gas)
30 }
31
32 pub(super) const fn symbolic_gas(&self) -> bool {
34 self.equivalence.is_some()
35 }
36
37 pub(super) fn reset_run_state(&mut self, use_wall_clock_deadline: bool) {
38 self.deferred_incomplete = None;
39 self.nested_deferred_mode = DeferredPathMode::Skip;
40 self.stateless_retry_safe = true;
41 self.deadline = if use_wall_clock_deadline {
42 self.config
43 .timeout
44 .filter(|seconds| *seconds > 0)
45 .map(|seconds| Instant::now() + Duration::from_secs(seconds.into()))
46 } else {
47 None
48 };
49 }
50
51 pub(super) fn check_timeout(&self) -> Result<(), SymbolicError> {
52 if let Some(deadline) = self.deadline
53 && Instant::now() >= deadline
54 {
55 return Err(SymbolicError::Timeout(self.config.timeout.unwrap_or_default()));
56 }
57 Ok(())
58 }
59
60 pub(super) fn defer_incomplete(&mut self, reason: &'static str) {
62 if self
63 .deferred_incomplete
64 .is_none_or(|reason| reason == DeferredIncomplete::HardArithmetic)
65 {
66 self.deferred_incomplete = Some(DeferredIncomplete::Unsupported(reason));
67 }
68 }
69
70 pub(super) fn defer_solver_unknown(&mut self) {
72 if self
73 .deferred_incomplete
74 .is_none_or(|reason| reason == DeferredIncomplete::HardArithmetic)
75 {
76 self.deferred_incomplete = Some(DeferredIncomplete::SolverUnknown);
77 }
78 }
79
80 pub(super) fn defer_hard_arithmetic(&mut self) {
82 self.deferred_incomplete.get_or_insert(DeferredIncomplete::HardArithmetic);
83 }
84
85 pub(super) fn is_sat_with_state(
86 &mut self,
87 state: &PathState,
88 constraints: &[SymBoolExpr],
89 ) -> Result<bool, SymbolicError> {
90 let replayable_storage = state.world.replay_storage_symbols();
91 self.solver.is_sat_with_replayable_storage(&mut self.cx, constraints, &replayable_storage)
92 }
93
94 pub(super) fn branch_is_sat_or_defer(
96 &mut self,
97 state: &PathState,
98 constraints: &[SymBoolExpr],
99 ) -> Result<bool, SymbolicError> {
100 match self.is_sat_with_state(state, constraints) {
101 Ok(feasible) => Ok(feasible),
102 Err(SymbolicError::SolverUnknown) => {
103 self.defer_solver_unknown();
104 Ok(false)
105 }
106 Err(err) => Err(err),
107 }
108 }
109
110 pub(super) fn completed_path_is_feasible(
113 &mut self,
114 state: &mut PathState,
115 outcome: StepOutcome,
116 ) -> Result<bool, SymbolicError> {
117 Ok(matches!(
118 outcome,
119 StepOutcome::Continue | StepOutcome::Forked | StepOutcome::AssumeRejected
120 ) || self.deferred_path_is_feasible(state)?)
121 }
122
123 pub(super) fn deferred_path_is_feasible(
125 &mut self,
126 state: &mut PathState,
127 ) -> Result<bool, SymbolicError> {
128 Ok(!state.take_deferred_feasibility_check()
129 || self.branch_is_sat_or_defer(state, &state.constraints)?)
130 }
131
132 pub(super) fn deferred_incomplete(&self) -> Option<(SymbolicStopReason, String)> {
134 match self.deferred_incomplete? {
135 DeferredIncomplete::Unsupported(reason) => Some((
136 SymbolicStopReason::Stuck,
137 format!("unsupported symbolic execution feature: {reason}"),
138 )),
139 DeferredIncomplete::SolverUnknown => {
140 Some((SymbolicStopReason::Timeout, "solver returned unknown".to_string()))
141 }
142 DeferredIncomplete::HardArithmetic => Some((
143 SymbolicStopReason::Timeout,
144 "nested hard arithmetic branch requires deferred SMT solving".to_string(),
145 )),
146 }
147 }
148
149 pub fn run(&mut self, input: SymbolicRunInput<'_>) -> SymbolicRunResult {
164 self.execute_run(input, None)
165 }
166
167 pub fn search_branch_target(
173 &mut self,
174 input: SymbolicRunInput<'_>,
175 ) -> SymbolicBranchTargetSearchResult {
176 let mut candidates = Vec::new();
177 if input.branch_target.is_none() {
178 return SymbolicBranchTargetSearchResult {
179 candidates,
180 execution: SymbolicRunResult::Incomplete {
181 kind: SymbolicStopReason::Error,
182 reason: "branch target search requires a branch target".to_string(),
183 stats: SymbolicStats::default(),
184 },
185 };
186 }
187
188 let execution = self.execute_run(input, Some(&mut candidates));
189 if let SymbolicRunResult::Counterexample { args, calldata, .. } = &execution {
190 candidates.insert(
191 0,
192 SymbolicConcreteInput { args: args.clone(), calldata: calldata.clone() },
193 );
194 }
195 SymbolicBranchTargetSearchResult { candidates, execution }
196 }
197
198 fn execute_run(
199 &mut self,
200 input: SymbolicRunInput<'_>,
201 mut branch_candidates: Option<&mut Vec<SymbolicConcreteInput>>,
202 ) -> SymbolicRunResult {
203 self.reset_run_state(branch_candidates.is_some());
204 self.solver.clear_context_caches();
205 self.cx = SymCx::new();
206 if let Err(err) = self.solver.check_available() {
207 return SymbolicRunResult::Incomplete {
208 kind: err.stop_reason(),
209 reason: err.to_string(),
210 stats: SymbolicStats::default(),
211 };
212 }
213
214 let mut completed_paths = 0;
215 let first =
216 match self.run_inner(&input, branch_candidates.as_deref_mut(), &mut completed_paths) {
217 Ok(result) => result,
218 Err(err) => {
219 return SymbolicRunResult::Incomplete {
220 kind: err.stop_reason(),
221 reason: err.to_string(),
222 stats: self.stats_with_paths(completed_paths),
223 };
224 }
225 };
226
227 let retry_nested_deferred = branch_candidates.is_none()
230 && self.stateless_retry_safe
231 && matches!(self.deferred_incomplete, Some(DeferredIncomplete::HardArithmetic))
232 && matches!(
233 &first,
234 SymbolicRunResult::Incomplete {
235 kind: SymbolicStopReason::RevertAll | SymbolicStopReason::Timeout,
236 ..
237 }
238 );
239 if !retry_nested_deferred {
240 return first;
241 }
242
243 if let Err(err) = self.check_timeout() {
244 return SymbolicRunResult::Incomplete {
245 kind: err.stop_reason(),
246 reason: err.to_string(),
247 stats: self.stats_with_paths(completed_paths),
248 };
249 }
250
251 self.deferred_incomplete = None;
252 self.nested_deferred_mode = DeferredPathMode::Yield;
253 let prioritized = match self.run_inner(&input, None, &mut completed_paths) {
254 Ok(result) => result,
255 Err(err) => {
256 return SymbolicRunResult::Incomplete {
257 kind: err.stop_reason(),
258 reason: err.to_string(),
259 stats: self.stats_with_paths(completed_paths),
260 };
261 }
262 };
263 let drain_nested_deferred = self.stateless_retry_safe
264 && matches!(self.deferred_incomplete, Some(DeferredIncomplete::HardArithmetic))
265 && matches!(
266 &prioritized,
267 SymbolicRunResult::Incomplete {
268 kind: SymbolicStopReason::RevertAll | SymbolicStopReason::Timeout,
269 ..
270 }
271 );
272 if !drain_nested_deferred {
273 return prioritized;
274 }
275
276 if let Err(err) = self.check_timeout() {
277 return SymbolicRunResult::Incomplete {
278 kind: err.stop_reason(),
279 reason: err.to_string(),
280 stats: self.stats_with_paths(completed_paths),
281 };
282 }
283
284 self.deferred_incomplete = None;
285 self.nested_deferred_mode = DeferredPathMode::Drain;
286 match self.run_inner(&input, None, &mut completed_paths) {
287 Ok(result) => result,
288 Err(err) => SymbolicRunResult::Incomplete {
289 kind: err.stop_reason(),
290 reason: err.to_string(),
291 stats: self.stats_with_paths(completed_paths),
292 },
293 }
294 }
295
296 pub fn modeled_corpus_seed_indexes(
298 config: &SymbolicConfig,
299 function: &Function,
300 corpus_seeds: &[SymbolicConcreteInput],
301 ) -> Result<Vec<usize>, SymbolicError> {
302 let mut cx = SymCx::new();
303 let variants = SymbolicCalldata::variants(function, config, &mut cx)?;
304 let mut modeled = vec![false; corpus_seeds.len()];
305 for calldata in &variants {
306 for (idx, seed) in corpus_seeds.iter().enumerate() {
307 if !modeled[idx] && calldata.seed_model(&mut cx, seed).is_some() {
308 modeled[idx] = true;
309 }
310 }
311 }
312 Ok(modeled
313 .into_iter()
314 .enumerate()
315 .filter_map(|(idx, modeled)| modeled.then_some(idx))
316 .collect())
317 }
318
319 pub fn run_invariant(
329 &mut self,
330 input: SymbolicInvariantRunInput<'_>,
331 ) -> SymbolicInvariantRunResult {
332 self.reset_run_state(true);
333 self.solver.clear_context_caches();
334 self.cx = SymCx::new();
335 if let Err(err) = self.solver.check_available() {
336 return SymbolicInvariantRunResult::Incomplete {
337 kind: err.stop_reason(),
338 reason: err.to_string(),
339 stats: SymbolicStats::default(),
340 };
341 }
342
343 match self.run_invariant_inner(input) {
344 Ok(result) => result,
345 Err(err) => SymbolicInvariantRunResult::Incomplete {
346 kind: err.stop_reason(),
347 reason: err.to_string(),
348 stats: self.solver.stats(),
349 },
350 }
351 }
352
353 pub fn search_invariant_candidates(
359 &mut self,
360 input: SymbolicInvariantCandidateInput<'_>,
361 ) -> SymbolicInvariantCandidateSearchResult {
362 self.reset_run_state(true);
363 self.solver.clear_context_caches();
364 self.cx = SymCx::new();
365 if let Err(error) = self.solver.check_available() {
366 return SymbolicInvariantCandidateSearchResult {
367 candidates: Vec::new(),
368 limitation: Some(error.into()),
369 };
370 }
371
372 let mut candidates = Vec::new();
373 let mut limitation = None;
374 if let Err(error) =
375 self.search_invariant_candidates_inner(&input, &mut candidates, &mut limitation)
376 {
377 limitation = Some(error.into());
378 }
379 if limitation.is_none()
382 && let Some((kind, reason)) = self.deferred_incomplete()
383 {
384 limitation = Some(SymbolicInvariantSearchLimitation { kind, reason });
385 }
386
387 SymbolicInvariantCandidateSearchResult { candidates, limitation }
388 }
389
390 pub(super) fn run_inner(
391 &mut self,
392 input: &SymbolicRunInput<'_>,
393 mut branch_candidates: Option<&mut Vec<SymbolicConcreteInput>>,
394 completed_paths: &mut usize,
395 ) -> Result<SymbolicRunResult, SymbolicError> {
396 let account = input
397 .executor
398 .backend
399 .basic(input.target)
400 .map_err(|err| SymbolicError::Backend(err.to_string()))?
401 .ok_or(SymbolicError::MissingAccount(input.target))?;
402 let bytecode = account.code.ok_or(SymbolicError::MissingCode(input.target))?;
403 let code = SymCode::from_bytecode(&mut self.cx, &bytecode);
404 self.folded_slots = FoldedSlots::register(&mut self.cx, &input.executor, self.deadline);
405 let mut roots = Vec::new();
406 for calldata in SymbolicCalldata::variants(input.function, &self.config, &mut self.cx)? {
407 let corpus_seed_models = input
408 .corpus_seeds
409 .iter()
410 .filter_map(|seed| calldata.seed_model(&mut self.cx, seed).map(Arc::new))
411 .collect();
412 let mut root = PathState::new(
413 &mut self.cx,
414 input.target,
415 input.sender,
416 input.value,
417 calldata,
418 input.ffi_enabled,
419 );
420 root.set_corpus_seed_models(corpus_seed_models);
421 root.set_branch_target(input.branch_target);
422 root.apply_executor_env(&mut self.cx, &input.executor)?;
423 root.world.set_storage_layout(self.config.storage_layout);
424 root.world.clear_transaction_scoped_state(&mut self.cx);
425 roots.push(root);
426 }
427 order_roots_by_corpus_seed_count(&mut roots, self.config.exploration_order);
428 let mut worklist = roots.into_iter().collect::<VecDeque<_>>();
429 let mut deferred_worklist = VecDeque::new();
430 let mut reverted_paths = 0usize;
431 let mut normal_paths = 0usize;
432 let mut success_input = None;
433 let path_limit = self.config.path_width() as usize;
434 let depth_limit = self.config.execution_depth() as usize;
435
436 while let Some(next) = self.pop_next_feasible_path(
437 &mut worklist,
438 &mut deferred_worklist,
439 DeferredPathMode::Drain,
440 )? {
441 let mut state = next.state;
442 if *completed_paths >= path_limit {
443 debug!(
444 completed_paths = *completed_paths,
445 path_limit, "symbolic path limit reached"
446 );
447 return Ok(SymbolicRunResult::Incomplete {
448 kind: SymbolicStopReason::Stuck,
449 reason: format!("symbolic path limit exceeded ({path_limit})"),
450 stats: self.stats_with_paths(*completed_paths),
451 });
452 }
453 if std::mem::take(&mut state.pending_storage_hook_revert) {
454 self.collect_branch_candidate(
455 branch_candidates.as_deref_mut(),
456 input.function,
457 &state,
458 )?;
459 *completed_paths += 1;
460 reverted_paths += 1;
461 continue;
462 }
463 let _path_span = trace_span!(
464 "symbolic_path",
465 completed_paths = *completed_paths,
466 worklist_size = worklist.len()
467 )
468 .entered();
469 trace!(
470 completed_paths = *completed_paths,
471 worklist_size = worklist.len(),
472 "exploring symbolic path"
473 );
474
475 loop {
476 self.check_timeout()?;
477 if state.depth >= depth_limit {
478 debug!(depth = state.depth, depth_limit, "symbolic depth limit reached");
479 return Ok(SymbolicRunResult::Incomplete {
480 kind: SymbolicStopReason::Stuck,
481 reason: format!("symbolic depth limit exceeded ({depth_limit})"),
482 stats: self.stats_with_paths(*completed_paths),
483 });
484 }
485 state.depth += 1;
486
487 let outcome = match code.opcode(&mut self.cx, state.pc)? {
488 Some(op) => {
489 let _step_span = trace_span!("symbolic_step", pc = state.pc, op).entered();
490 self.step(
491 &input.executor,
492 &code,
493 &mut state,
494 &mut worklist,
495 completed_paths,
496 op,
497 )?
498 }
499 None => StepOutcome::Halt,
500 };
501 if !self.completed_path_is_feasible(&mut state, outcome)? {
502 break;
503 }
504 let outcome = match outcome {
505 StepOutcome::Halt
507 if self.global_fail_slot_set(&input.executor, &mut state)? =>
508 {
509 StepOutcome::Failure
510 }
511 outcome => outcome,
512 };
513 match outcome {
514 StepOutcome::Continue => {}
515 StepOutcome::AssumeRejected | StepOutcome::Forked => break,
516 StepOutcome::Revert => {
517 self.collect_branch_candidate(
518 branch_candidates.as_deref_mut(),
519 input.function,
520 &state,
521 )?;
522 *completed_paths += 1;
523 reverted_paths += 1;
524 break;
525 }
526 StepOutcome::Halt if state.expectations_satisfied() => {
527 let candidate = self.collect_branch_candidate(
528 branch_candidates.as_deref_mut(),
529 input.function,
530 &state,
531 )?;
532 if input.collect_success_input
533 && state.satisfies_branch_target()
534 && state.can_materialize_seed()
535 && success_input.as_ref().is_none_or(|(depth, _)| state.depth > *depth)
536 {
537 let input = match candidate {
538 Some(input) => input,
539 None => self.materialize_root_input(input.function, &state)?.0,
540 };
541 success_input = Some((state.depth, input));
542 }
543 *completed_paths += 1;
544 normal_paths += 1;
545 break;
546 }
547 StepOutcome::Halt | StepOutcome::ExceptionalHalt | StepOutcome::Failure => {
548 if !state.satisfies_branch_target() {
549 *completed_paths += 1;
550 break;
551 }
552 debug!(
553 constraint_count = state.constraints.len(),
554 "materializing counterexample from solver model"
555 );
556 let (SymbolicConcreteInput { args, calldata }, model) =
557 self.materialize_root_input(input.function, &state)?;
558 let svm_returns = state
559 .svm_returns
560 .iter()
561 .map(|ret| ret.bytes.eval_model(&mut self.cx, &model).map(Bytes::from))
562 .collect::<Result<_, _>>()?;
563 let generic =
568 matches!(self.config.storage_layout, SymbolicStorageLayout::Generic);
569 let executor = &input.executor;
570 let storage = state
571 .world
572 .replay_storage_assignments(&model, true)
573 .inspect_err(|err| debug!(%err, "skipping symbolic storage replay"))
574 .unwrap_or_default()
575 .into_iter()
576 .filter(|assignment| {
577 generic
578 || executor
579 .arbitrary_storage_targets
580 .iter()
581 .map(|(target, _)| target)
582 .chain(
583 executor
584 .arbitrary_storage_copies
585 .iter()
586 .map(|(target, _)| target),
587 )
588 .any(|target| *target == assignment.address)
589 })
590 .collect();
591 return Ok(SymbolicRunResult::Counterexample {
592 args,
593 calldata,
594 svm_returns,
595 memory_halt_pc: state.memory_halt_pc,
596 storage,
597 stats: self.stats_with_paths(*completed_paths + 1),
598 });
599 }
600 }
601 }
602 }
603
604 if normal_paths == 0 && reverted_paths > 0 {
605 debug!(completed_paths = *completed_paths, "all symbolic paths reverted");
606 return Ok(SymbolicRunResult::Incomplete {
607 kind: SymbolicStopReason::RevertAll,
608 reason: "all symbolic paths reverted".to_string(),
609 stats: self.stats_with_paths(*completed_paths),
610 });
611 }
612
613 if let Some((kind, reason)) = self.deferred_incomplete() {
614 return Ok(SymbolicRunResult::Incomplete {
615 kind,
616 reason,
617 stats: self.stats_with_paths(*completed_paths),
618 });
619 }
620
621 if normal_paths == 0 {
622 return Ok(SymbolicRunResult::Incomplete {
623 kind: SymbolicStopReason::Stuck,
624 reason: "no successful symbolic paths".to_string(),
625 stats: self.stats_with_paths(*completed_paths),
626 });
627 }
628
629 debug!(completed_paths = *completed_paths, "symbolic execution safe");
630 Ok(SymbolicRunResult::Safe {
631 stats: self.stats_with_paths(*completed_paths),
632 success_input: success_input.map(|(_, input)| input),
633 })
634 }
635
636 fn collect_branch_candidate(
637 &mut self,
638 candidates: Option<&mut Vec<SymbolicConcreteInput>>,
639 function: &Function,
640 state: &PathState,
641 ) -> Result<Option<SymbolicConcreteInput>, SymbolicError> {
642 let Some(candidates) = candidates else {
643 return Ok(None);
644 };
645 if !state.satisfies_branch_target() || !state.can_materialize_seed() {
646 return Ok(None);
647 }
648
649 let (input, _) = self.materialize_root_input(function, state)?;
650 candidates.push(input.clone());
651 Ok(Some(input))
652 }
653
654 pub(super) fn witness_model(
656 &mut self,
657 state: &PathState,
658 ) -> Result<SymbolicModel, SymbolicError> {
659 let replayable_storage = state.world.replay_storage_symbols();
660 if !state.witness_preferences.is_empty() {
661 let mut constraints = state.constraints.clone();
662 constraints.extend(state.witness_preferences.iter().cloned());
663 if let Ok(model) = self.solver.model_with_replayable_storage(
664 &mut self.cx,
665 &constraints,
666 &replayable_storage,
667 ) {
668 return Ok(model);
669 }
670 }
671 self.solver.model_with_replayable_storage(
672 &mut self.cx,
673 &state.constraints,
674 &replayable_storage,
675 )
676 }
677
678 fn materialize_root_input(
680 &mut self,
681 function: &Function,
682 state: &PathState,
683 ) -> Result<(SymbolicConcreteInput, SymbolicModel), SymbolicError> {
684 let calldata = state
685 .root_calldata
686 .as_ref()
687 .ok_or(SymbolicError::Unsupported("missing root symbolic calldata"))?;
688 let model = self.witness_model(state)?;
689 let args = calldata.model_to_args(&mut self.cx, &model)?;
690 let calldata_bytes = Bytes::from(function.abi_encode_input(&args)?);
691 Ok((SymbolicConcreteInput { args, calldata: calldata_bytes }, model))
692 }
693
694 pub(super) fn run_invariant_inner(
695 &mut self,
696 input: SymbolicInvariantRunInput<'_>,
697 ) -> Result<SymbolicInvariantRunResult, SymbolicError> {
698 if input.targets.is_empty() {
699 return Err(SymbolicError::Unsupported("symbolic invariant has no targets"));
700 }
701
702 let mut senders =
703 if input.senders.is_empty() { vec![input.sender] } else { input.senders.clone() };
704 senders.retain(|sender| !input.excluded_senders.contains(sender));
705 if senders.is_empty() {
706 return Err(SymbolicError::Unsupported("symbolic invariant senders are excluded"));
707 }
708 let after_invariant_for = |steps_len: usize| {
709 (steps_len == input.depth).then_some(input.after_invariant).flatten()
710 };
711 let mut completed_paths = 0usize;
712 let mut initial_state = PathState::empty(
713 &mut self.cx,
714 input.invariant_address,
715 input.sender,
716 input.ffi_enabled,
717 );
718 initial_state.apply_executor_env(&mut self.cx, &input.executor)?;
719 initial_state.world.set_storage_layout(self.config.storage_layout);
720 self.folded_slots = FoldedSlots::register(&mut self.cx, &input.executor, self.deadline);
721 let initial = SequencePath { state: initial_state, steps: Vec::new() };
722
723 for outcome in self.execute_invariant_check(
725 &input.executor,
726 &initial.state,
727 input.invariant_address,
728 input.invariant,
729 after_invariant_for(0),
730 &mut completed_paths,
731 )? {
732 if outcome.failed {
733 let (sequence, storage) =
734 self.materialize_sequence(&initial.steps, &outcome.state)?;
735 return Ok(SymbolicInvariantRunResult::Counterexample {
736 kind: SymbolicInvariantCounterexampleKind::Predicate,
737 sequence,
738 storage,
739 stats: self.stats_with_paths(completed_paths),
740 });
741 }
742 }
743
744 let path_limit = self.config.path_width() as usize;
745 let mut frontier = vec![initial];
746 for depth in 0..input.depth {
747 self.check_timeout()?;
748 let mut next_frontier = Vec::new();
749 for sequence in frontier {
750 self.check_timeout()?;
751 for (target_idx, target) in input.targets.iter().enumerate() {
752 for (sender_idx, sender) in senders.iter().copied().enumerate() {
753 self.check_timeout()?;
754 let prefix = format!("sequence_{depth}_{target_idx}_{sender_idx}");
755 let calldatas = SymbolicCalldata::variants_with_prefix(
756 &target.function,
757 &self.config,
758 &mut self.cx,
759 &prefix,
760 )?;
761 for calldata in calldatas {
762 let step = SequenceStepTemplate {
763 sender,
764 address: target.address,
765 contract_name: target.contract_name.clone(),
766 function: target.function.clone(),
767 calldata,
768 };
769 let calldata = step.calldata.call_data(&mut self.cx);
770 let constraints = step.calldata.constraints().to_vec();
771 let mut call = self.prepare_sequence_call(
772 &input.executor,
773 sequence.state.clone(),
774 target.address,
775 sender,
776 calldata,
777 constraints,
778 )?;
779
780 while let Some(outcome) = self.execute_sequence_call_next(
781 &input.executor,
782 &mut call,
783 &mut completed_paths,
784 )? {
785 let mut steps = sequence.steps.clone();
786 steps.push(step.clone());
787
788 let post_state = match outcome.status {
789 CallStatus::Failure => {
790 let (sequence, storage) =
791 self.materialize_sequence(&steps, &outcome.state)?;
792 return Ok(SymbolicInvariantRunResult::Counterexample {
793 kind: SymbolicInvariantCounterexampleKind::Handler,
794 sequence,
795 storage,
796 stats: self.stats_with_paths(completed_paths),
797 });
798 }
799 CallStatus::Revert | CallStatus::ExceptionalHalt => {
800 if input.fail_on_revert {
801 let (sequence, storage) =
802 self.materialize_sequence(&steps, &outcome.state)?;
803 return Ok(
804 SymbolicInvariantRunResult::Counterexample {
805 kind: SymbolicInvariantCounterexampleKind::Predicate,
806 sequence,
807 storage,
808 stats: self.stats_with_paths(completed_paths),
809 },
810 );
811 }
812 let mut reverted_state = sequence.state.clone();
819 reverted_state
820 .take_reverted_top_level_effects(outcome.state);
821 reverted_state
822 }
823 CallStatus::Success => outcome.state,
824 };
825 if symbolic_invariant_should_check(
826 steps.len(),
827 input.depth,
828 input.check_interval,
829 ) {
830 for mut invariant_outcome in self.execute_invariant_check(
831 &input.executor,
832 &post_state,
833 input.invariant_address,
834 input.invariant,
835 after_invariant_for(steps.len()),
836 &mut completed_paths,
837 )? {
838 if invariant_outcome.failed {
839 let (sequence, storage) = self.materialize_sequence(
840 &steps,
841 &invariant_outcome.state,
842 )?;
843 return Ok(SymbolicInvariantRunResult::Counterexample {
844 kind: SymbolicInvariantCounterexampleKind::Predicate,
845 sequence,
846 storage,
847 stats: self.stats_with_paths(completed_paths),
848 });
849 }
850 let mut state = post_state.clone();
851 state.take_noncommitting_check_state(
852 &mut invariant_outcome.state,
853 );
854 next_frontier
855 .push(SequencePath { state, steps: steps.clone() });
856 }
857 } else {
858 next_frontier.push(SequencePath { state: post_state, steps });
859 }
860
861 if completed_paths >= path_limit {
862 return Ok(SymbolicInvariantRunResult::Incomplete {
863 kind: SymbolicStopReason::Stuck,
864 reason: format!(
865 "symbolic path limit exceeded ({path_limit})"
866 ),
867 stats: self.stats_with_paths(completed_paths),
868 });
869 }
870 }
871 }
872 }
873 }
874 }
875
876 if next_frontier.is_empty() {
877 break;
878 }
879 frontier = next_frontier;
880 }
881
882 if let Some((kind, reason)) = self.deferred_incomplete() {
883 return Ok(SymbolicInvariantRunResult::Incomplete {
884 kind,
885 reason,
886 stats: self.stats_with_paths(completed_paths),
887 });
888 }
889
890 Ok(SymbolicInvariantRunResult::Safe(self.stats_with_paths(completed_paths)))
891 }
892
893 pub(super) fn stats_with_paths(&self, paths: usize) -> SymbolicStats {
894 let mut stats = self.solver.stats();
895 stats.paths = paths;
896 stats
897 }
898}
899
900fn order_roots_by_corpus_seed_count(roots: &mut [PathState], order: SymbolicExplorationOrder) {
901 let Some((first, rest)) = roots.split_first() else {
902 return;
903 };
904 if rest.iter().all(|root| root.corpus_seed_model_count() == first.corpus_seed_model_count()) {
905 return;
906 }
907
908 match order {
909 SymbolicExplorationOrder::Bfs => {
910 roots.sort_by_key(|root| Reverse(root.corpus_seed_model_count()));
911 }
912 SymbolicExplorationOrder::Dfs => {
913 roots.sort_by_key(PathState::corpus_seed_model_count);
914 }
915 }
916}
917
918const fn symbolic_invariant_should_check(
919 sequence_len: usize,
920 depth: usize,
921 check_interval: u32,
922) -> bool {
923 sequence_len == depth
924 || (check_interval != 0 && sequence_len.is_multiple_of(check_interval as usize))
925}