forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.rs
More file actions
2716 lines (2463 loc) · 96.1 KB
/
Copy pathstate.rs
File metadata and controls
2716 lines (2463 loc) · 96.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::*;
#[derive(Clone, Debug)]
pub(crate) struct PathState {
pub(crate) depth: usize,
pub(crate) call_depth: usize,
pub(crate) origin: Address,
pub(crate) origin_word: SymExpr,
pub(crate) gas_price: SymExpr,
pub(crate) ffi_enabled: bool,
pub(crate) block: SymbolicBlock,
pub(crate) frame: CallFrame,
pub(crate) world: SymbolicWorld,
pub(crate) prank: SymbolicPrank,
pub(crate) constraints: Vec<SymBoolExpr>,
pub(crate) next_symbol: usize,
pub(crate) recorded_logs: Option<Vec<SymbolicLog>>,
pub(crate) access_record: Option<AccessRecord>,
pub(crate) root_calldata: Option<SymbolicCalldata>,
corpus_seed_models: Vec<Arc<SymbolicModel>>,
branch_target: Option<SymbolicBranchTarget>,
branch_target_reached: bool,
needs_feasibility_check: bool,
pub(crate) loop_jumps: HashMap<usize, u32>,
pub(crate) expected_revert: Option<ExpectedRevert>,
pub(crate) assume_no_revert_next_call: Option<AssumeNoRevert>,
pub(crate) expected_emit: Option<ExpectedEmit>,
pub(crate) expected_calls: Vec<ExpectedCall>,
pub(crate) expected_creates: Vec<ExpectedCreate>,
pub(crate) call_mocks: Vec<CallMock>,
pub(crate) function_mocks: Vec<FunctionMock>,
pub(crate) persistent_accounts: HashSet<Address>,
pub(crate) wallets: IndexSet<Address>,
pub(crate) labels: HashMap<Address, String>,
pub(crate) storage_load_hooks: HashMap<Address, SymbolicStorageHook>,
pub(crate) storage_store_hooks: HashMap<Address, SymbolicStorageHook>,
pub(crate) mapping_storage_store_hooks: HashMap<(Address, U256), SymbolicStorageHook>,
pub(crate) mapping_hook_keccak_preimages: HashMap<(Address, SymExpr), Arc<[SymExpr]>>,
pub(crate) storage_hook_active: bool,
pub(crate) pending_storage_hook_revert: bool,
}
impl PathState {
pub(crate) fn new(
cx: &mut SymCx,
address: Address,
caller: Address,
callvalue: U256,
calldata: SymbolicCalldata,
ffi_enabled: bool,
) -> Self {
let constraints = calldata.constraints().to_vec();
let call_data = calldata.call_data(cx);
let origin_word = SymExpr::constant(cx, address_word(caller));
let gas_price = SymExpr::zero(cx);
let block = SymbolicBlock::new(cx);
let callvalue = SymExpr::constant(cx, callvalue);
let frame = CallFrame::new(cx, address, address, caller, callvalue, false, call_data);
Self {
depth: 0,
call_depth: 0,
origin: caller,
origin_word,
gas_price,
ffi_enabled,
block,
frame,
world: SymbolicWorld::default(),
prank: SymbolicPrank::default(),
constraints,
next_symbol: 0,
recorded_logs: None,
access_record: None,
root_calldata: Some(calldata),
corpus_seed_models: Vec::new(),
branch_target: None,
branch_target_reached: false,
needs_feasibility_check: false,
loop_jumps: HashMap::default(),
expected_revert: None,
assume_no_revert_next_call: None,
expected_emit: None,
expected_calls: Vec::new(),
expected_creates: Vec::new(),
call_mocks: Vec::new(),
function_mocks: Vec::new(),
persistent_accounts: HashSet::default(),
wallets: IndexSet::default(),
labels: HashMap::default(),
storage_load_hooks: HashMap::default(),
storage_store_hooks: HashMap::default(),
mapping_storage_store_hooks: HashMap::default(),
mapping_hook_keccak_preimages: HashMap::default(),
storage_hook_active: false,
pending_storage_hook_revert: false,
}
}
pub(crate) fn empty(
cx: &mut SymCx,
address: Address,
caller: Address,
ffi_enabled: bool,
) -> Self {
let origin_word = SymExpr::constant(cx, address_word(caller));
let gas_price = SymExpr::zero(cx);
let block = SymbolicBlock::new(cx);
let callvalue = SymExpr::zero(cx);
let calldata = SymBytes::empty(cx);
let calldata = SymCalldata::from_bytes(cx, calldata);
let frame = CallFrame::new(cx, address, address, caller, callvalue, false, calldata);
Self {
depth: 0,
call_depth: 0,
origin: caller,
origin_word,
gas_price,
ffi_enabled,
block,
frame,
world: SymbolicWorld::default(),
prank: SymbolicPrank::default(),
constraints: Vec::new(),
next_symbol: 0,
recorded_logs: None,
access_record: None,
root_calldata: None,
corpus_seed_models: Vec::new(),
branch_target: None,
branch_target_reached: false,
needs_feasibility_check: false,
loop_jumps: HashMap::default(),
expected_revert: None,
assume_no_revert_next_call: None,
expected_emit: None,
expected_calls: Vec::new(),
expected_creates: Vec::new(),
call_mocks: Vec::new(),
function_mocks: Vec::new(),
persistent_accounts: HashSet::default(),
wallets: IndexSet::default(),
labels: HashMap::default(),
storage_load_hooks: HashMap::default(),
storage_store_hooks: HashMap::default(),
mapping_storage_store_hooks: HashMap::default(),
mapping_hook_keccak_preimages: HashMap::default(),
storage_hook_active: false,
pending_storage_hook_revert: false,
}
}
pub(crate) fn apply_executor_env<FEN: FoundryEvmNetwork>(
&mut self,
cx: &mut SymCx,
executor: &Executor<FEN>,
) {
self.block = SymbolicBlock::from_executor(cx, executor);
let gas_price = executor
.inspector()
.cheatcodes
.as_ref()
.and_then(|cheats| cheats.gas_price)
.unwrap_or_else(|| executor.tx_env().gas_price());
self.gas_price = SymExpr::constant(cx, U256::from(gas_price));
if let Some(cheats) = executor.inspector().cheatcodes.as_ref() {
for (target, overwrite) in cheats.arbitrary_storage_target_overwrite_modes() {
self.world.enable_arbitrary_storage(target, overwrite);
}
for (target, source) in cheats.arbitrary_storage_copied_target_sources() {
self.world.enable_arbitrary_storage_copy(source, target);
}
self.storage_load_hooks.extend(cheats.storage_load_hooks().map(|(target, hook)| {
(
target,
SymbolicStorageHook {
callback_target: hook.callback_target,
callback_selector: hook.callback_selector,
},
)
}));
self.storage_store_hooks.extend(cheats.storage_store_hooks().map(|(target, hook)| {
(
target,
SymbolicStorageHook {
callback_target: hook.callback_target,
callback_selector: hook.callback_selector,
},
)
}));
self.mapping_storage_store_hooks.extend(cheats.mapping_storage_store_hooks().map(
|(target, root, hook)| {
(
(target, root.into()),
SymbolicStorageHook {
callback_target: hook.callback_target,
callback_selector: hook.callback_selector,
},
)
},
));
}
}
pub(crate) fn child(&self, frame: CallFrame) -> Self {
let mut child = self.clone();
child.call_depth += 1;
child.frame = frame;
// A prank changes the call being entered; calls made by the callee use normal EVM caller
// semantics unless the callee sets its own prank.
child.prank = SymbolicPrank::default();
child.loop_jumps.clear();
child.expected_revert = None;
child.assume_no_revert_next_call = None;
child
}
pub(crate) fn storage_hook_child(&self, frame: CallFrame) -> Self {
let mut child = self.child(frame);
child.storage_hook_active = true;
child.recorded_logs = None;
child.access_record = None;
child.expected_emit = None;
child.expected_calls.clear();
child.expected_creates.clear();
child.call_mocks.clear();
child.function_mocks.clear();
child.set_branch_target(None);
child
}
pub(crate) fn copy_call_output_offset(
&mut self,
cx: &mut SymCx,
dest: SymExpr,
size: &BoundedCopySize,
) -> Result<(), SymbolicError> {
let CallFrame { memory, return_data, .. } = &mut self.frame;
memory.copy_call_output_offset(cx, dest, size, return_data)
}
pub(crate) fn copy_calldata_to_offset(
&mut self,
cx: &mut SymCx,
dest: SymExpr,
offset: SymExpr,
size: usize,
) -> Result<(), SymbolicError> {
let CallFrame { memory, calldata, .. } = &mut self.frame;
memory.copy_calldata_to_offset(cx, dest, offset, size, calldata)
}
pub(crate) fn copy_calldata_symbolic_size(
&mut self,
cx: &mut SymCx,
dest: SymExpr,
offset: SymExpr,
size: SymExpr,
max_size: usize,
) -> Result<(), SymbolicError> {
let CallFrame { memory, calldata, .. } = &mut self.frame;
memory.copy_calldata_symbolic_size(cx, dest, offset, size, max_size, calldata)
}
pub(crate) fn copy_return_data_to_offset(
&mut self,
cx: &mut SymCx,
dest: SymExpr,
offset: SymExpr,
size: usize,
) -> Result<(), SymbolicError> {
let CallFrame { memory, return_data, .. } = &mut self.frame;
memory.copy_return_data_to_offset(cx, dest, offset, size, return_data)
}
pub(crate) fn copy_return_data_symbolic_size(
&mut self,
cx: &mut SymCx,
dest: SymExpr,
offset: SymExpr,
size: SymExpr,
max_size: usize,
) -> Result<(), SymbolicError> {
let CallFrame { memory, return_data, .. } = &mut self.frame;
memory.copy_return_data_symbolic_size(cx, dest, offset, size, max_size, return_data)
}
pub(crate) fn constrained_usize(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<usize> {
self.constrained_usize_checked(cx, expr).and_then(Result::ok)
}
pub(crate) fn constrained_usize_checked(
&self,
cx: &mut SymCx,
expr: &SymExpr,
) -> Option<Result<usize, U256>> {
self.constrained_word(cx, expr).map(|value| usize::try_from(value).map_err(|_| value))
}
pub(crate) fn upper_bound_usize(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<usize> {
self.constrained_usize(cx, expr).or_else(|| {
expr.as_const()
.and_then(|value| usize::try_from(value).ok())
.or_else(|| self.expr_upper_bound_usize(expr))
})
}
pub(crate) fn constrained_word(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<U256> {
expr.as_const().or_else(|| {
self.constraints
.iter()
.find_map(|constraint| {
constraint.forces_expr_const_with_context(expr, &self.constraints)
})
.or_else(|| self.constrained_expr_value(cx, expr))
})
}
pub(crate) fn constrained_expr_value(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<U256> {
if let Some(value) = expr.eval() {
return Some(value);
}
if let Some(value) = expr.known_word() {
return Some(value);
}
let mut vars = SymbolicVars::default();
expr.collect_eval_vars(&mut vars);
let mut model = SymbolicModel::default();
for var in vars {
let var_expr = SymExpr::get_var(cx, var);
let value = self.constraints.iter().find_map(|constraint| {
constraint.forces_expr_const_with_context(&var_expr, &self.constraints)
})?;
model.insert(var, value);
}
expr.eval_model(&model).ok()
}
pub(crate) fn split_corpus_seed_models(
&self,
condition: &SymBoolExpr,
) -> (Vec<Arc<SymbolicModel>>, Vec<Arc<SymbolicModel>>) {
let mut true_models = Vec::new();
let mut false_models = Vec::new();
for model in &self.corpus_seed_models {
match condition.eval_model_if_complete(model.as_ref()) {
Ok(Some(true)) => true_models.push(Arc::clone(model)),
Ok(Some(false)) => false_models.push(Arc::clone(model)),
Ok(None) | Err(_) => {
true_models.push(Arc::clone(model));
false_models.push(Arc::clone(model));
}
}
}
(true_models, false_models)
}
pub(crate) fn set_corpus_seed_models(&mut self, models: Vec<Arc<SymbolicModel>>) {
self.corpus_seed_models = models;
}
pub(crate) const fn corpus_seed_model_count(&self) -> usize {
self.corpus_seed_models.len()
}
pub(crate) const fn set_branch_target(&mut self, target: Option<SymbolicBranchTarget>) {
self.branch_target = target;
self.branch_target_reached = false;
}
pub(crate) const fn branch_target(&self) -> Option<SymbolicBranchTarget> {
self.branch_target
}
pub(crate) const fn mark_branch_target_reached(&mut self) {
self.branch_target_reached = true;
}
pub(crate) fn inherit_branch_target_progress(&mut self, child: &Self) {
if self.branch_target == child.branch_target && child.branch_target_reached {
self.branch_target_reached = true;
}
}
pub(crate) fn take_noncommitting_check_state(&mut self, check: &mut Self) {
self.constraints = std::mem::take(&mut check.constraints);
self.next_symbol = self.next_symbol.max(check.next_symbol);
self.world.merge_replay_metadata_from(&check.world);
self.storage_load_hooks = std::mem::take(&mut check.storage_load_hooks);
self.storage_store_hooks = std::mem::take(&mut check.storage_store_hooks);
self.mapping_storage_store_hooks = std::mem::take(&mut check.mapping_storage_store_hooks);
}
pub(crate) fn take_call_outcome_state(&mut self, child: &mut Self) {
self.constraints = std::mem::take(&mut child.constraints);
self.next_symbol = child.next_symbol;
self.inherit_branch_target_progress(child);
self.storage_load_hooks = std::mem::take(&mut child.storage_load_hooks);
self.storage_store_hooks = std::mem::take(&mut child.storage_store_hooks);
self.mapping_storage_store_hooks = std::mem::take(&mut child.mapping_storage_store_hooks);
self.mapping_hook_keccak_preimages =
std::mem::take(&mut child.mapping_hook_keccak_preimages);
self.recorded_logs = child.recorded_logs.take();
self.access_record = child.access_record.take();
}
pub(crate) fn take_reverted_top_level_effects(&mut self, mut reverted: Self) {
self.take_noncommitting_check_state(&mut reverted);
self.block = reverted.block;
self.recorded_logs = reverted.recorded_logs;
self.access_record = reverted.access_record;
self.expected_revert = reverted.expected_revert;
self.assume_no_revert_next_call = reverted.assume_no_revert_next_call;
self.expected_emit = reverted.expected_emit;
self.expected_calls = reverted.expected_calls;
self.expected_creates = reverted.expected_creates;
self.call_mocks = reverted.call_mocks;
self.function_mocks = reverted.function_mocks;
}
pub(crate) const fn satisfies_branch_target(&self) -> bool {
self.branch_target.is_none() || self.branch_target_reached
}
pub(crate) const fn defer_feasibility_check(&mut self) {
self.needs_feasibility_check = true;
}
pub(crate) const fn take_deferred_feasibility_check(&mut self) -> bool {
let needs_check = self.needs_feasibility_check;
self.needs_feasibility_check = false;
needs_check
}
pub(crate) fn expr_upper_bound_usize(&self, expr: &SymExpr) -> Option<usize> {
if let Some(value) = expr.eval() {
return usize::try_from(value).ok();
}
if let Some(value) = expr.known_word() {
return usize::try_from(value).ok();
}
let constraint_bound = self.constraint_upper_bound_usize(expr);
let structural_bound = match expr.kind() {
SymExprKind::Const(value) => usize::try_from(*value).ok(),
SymExprKind::Var(_)
| SymExprKind::GasLeft(_)
| SymExprKind::Keccak { .. }
| SymExprKind::Hash { .. } => None,
SymExprKind::Not(_) => None,
SymExprKind::TernOp(_, _, _, modulus) => match modulus.eval() {
Some(modulus) if modulus.is_zero() => Some(0),
Some(modulus) => usize::try_from(modulus - U256::from(1)).ok(),
None => self.expr_upper_bound_usize(modulus).and_then(|bound| bound.checked_sub(1)),
},
SymExprKind::Ite(_, left, right) => {
Some(self.expr_upper_bound_usize(left)?.max(self.expr_upper_bound_usize(right)?))
}
SymExprKind::BinOp(op, left, right) => match op {
SymBinOp::Add => self
.expr_upper_bound_usize(left)?
.checked_add(self.expr_upper_bound_usize(right)?),
SymBinOp::Mul => self
.expr_upper_bound_usize(left)?
.checked_mul(self.expr_upper_bound_usize(right)?),
SymBinOp::UDiv => {
let left = self.expr_upper_bound_usize(left)?;
match right.eval()? {
divisor if divisor.is_zero() => Some(0),
divisor => Some(left / usize::try_from(divisor).ok()?),
}
}
SymBinOp::URem => match right.eval() {
Some(divisor) if divisor.is_zero() => Some(0),
Some(divisor) => usize::try_from(divisor - U256::from(1)).ok(),
None => self.expr_upper_bound_usize(left),
},
SymBinOp::And => right
.eval()
.and_then(|value| usize::try_from(value).ok())
.or_else(|| left.eval().and_then(|value| usize::try_from(value).ok()))
.map(|mask| {
self.expr_upper_bound_usize(left)
.or_else(|| self.expr_upper_bound_usize(right))
.map_or(mask, |bound| bound.min(mask))
}),
SymBinOp::Shr => {
let left = self.expr_upper_bound_usize(left)?;
let shift = usize::try_from(right.eval()?).ok()?;
Some(if shift >= usize::BITS as usize { 0 } else { left >> shift })
}
SymBinOp::Sub
| SymBinOp::SDiv
| SymBinOp::SRem
| SymBinOp::Or
| SymBinOp::Xor
| SymBinOp::Shl
| SymBinOp::Sar => None,
},
};
match (constraint_bound, structural_bound) {
(Some(left), Some(right)) => Some(left.min(right)),
(Some(bound), None) | (None, Some(bound)) => Some(bound),
(None, None) => None,
}
}
pub(crate) fn constraint_upper_bound_usize(&self, expr: &SymExpr) -> Option<usize> {
let mut bound: Option<usize> = None;
for constraint in &self.constraints {
if let Some(candidate) = constraint.upper_bound_usize(expr) {
bound = Some(bound.map_or(candidate, |bound| bound.min(candidate)));
}
}
bound
}
pub(crate) fn expect_constrained_usize(
&self,
cx: &mut SymCx,
expr: SymExpr,
reason: &'static str,
) -> Result<usize, SymbolicError> {
self.constrained_usize(cx, &expr).ok_or(SymbolicError::Unsupported(reason))
}
pub(crate) fn expect_constrained_word(
&self,
cx: &mut SymCx,
expr: SymExpr,
reason: &'static str,
) -> Result<U256, SymbolicError> {
self.constrained_word(cx, &expr).ok_or(SymbolicError::Unsupported(reason))
}
pub(crate) fn bin_word(
&mut self,
cx: &mut SymCx,
op: SymBinOp,
) -> Result<StepOutcome, SymbolicError> {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
self.stack.push(SymExpr::binop(cx, op, a, b))?;
Ok(StepOutcome::Continue)
}
pub(crate) fn bin_word_div_zero_guard(
&mut self,
cx: &mut SymCx,
op: SymBinOp,
) -> Result<StepOutcome, SymbolicError> {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
let zero = SymExpr::zero(cx);
let condition = SymBoolExpr::eq(cx, b.clone(), zero.clone());
let expr = SymExpr::binop(cx, op, a, b);
self.stack.push(SymExpr::ite(cx, condition, zero, expr))?;
Ok(StepOutcome::Continue)
}
#[cfg(test)]
pub(crate) fn cmp_word(
&mut self,
cx: &mut SymCx,
op: SymCmpOp,
) -> Result<StepOutcome, SymbolicError> {
let condition = self.cmp_word_condition(cx, op)?;
let value = SymExpr::bool_word(cx, condition);
self.stack.push(value)?;
Ok(StepOutcome::Continue)
}
pub(crate) fn cmp_word_condition(
&mut self,
cx: &mut SymCx,
op: SymCmpOp,
) -> Result<SymBoolExpr, SymbolicError> {
let a = self.stack.pop()?;
let b = self.stack.pop()?;
Ok(SymBoolExpr::cmp(cx, op, a, b))
}
pub(crate) fn shift_word(
&mut self,
cx: &mut SymCx,
kind: ShiftKind,
) -> Result<StepOutcome, SymbolicError> {
let shift = self.stack.pop()?;
let value = self.stack.pop()?;
let result = if let (Some(value), Some(shift)) = (value.as_const(), shift.as_const()) {
let result = if shift >= U256::from(256) {
if matches!(kind, ShiftKind::Sar) && ((value >> 255) == U256::from(1)) {
U256::MAX
} else {
U256::ZERO
}
} else {
let shift = usize::try_from(shift).expect("checked word shift");
match kind {
ShiftKind::Shl => value << shift,
ShiftKind::Shr => value >> shift,
ShiftKind::Sar => sar(value, shift),
}
};
SymExpr::constant(cx, result)
} else {
let expr = match kind {
ShiftKind::Shl => SymExpr::binop(cx, SymBinOp::Shl, value, shift),
ShiftKind::Shr => SymExpr::binop(cx, SymBinOp::Shr, value, shift),
ShiftKind::Sar => SymExpr::binop(cx, SymBinOp::Sar, value, shift),
};
expr.known_word().map(|word| SymExpr::constant(cx, word)).unwrap_or(expr)
};
self.stack.push(result)?;
Ok(StepOutcome::Continue)
}
pub(crate) fn exp_word(&mut self, cx: &mut SymCx) -> Result<StepOutcome, SymbolicError> {
let base = self.stack.pop()?;
let exponent = self.stack.pop()?;
let result = if let Some(exponent) = self.constrained_word(cx, &exponent) {
if let Some(base_value) = base.as_const() {
SymExpr::constant(cx, pow_mod(base_value, exponent))
} else if exponent <= U256::from(SYMBOLIC_EXP_CONCRETE_EXPONENT_LIMIT) {
exp_expr_for_concrete_exponent(
cx,
base,
usize::try_from(exponent).expect("checked symbolic exponent"),
)
} else {
return Err(SymbolicError::Unsupported("symbolic EXP base"));
}
} else {
let exponent_limit = if base.as_const().is_some() {
CONCRETE_BASE_SYMBOLIC_EXPONENT_LIMIT
} else {
SYMBOLIC_EXP_CONCRETE_EXPONENT_LIMIT
};
let max_exponent = self
.upper_bound_usize(cx, &exponent)
.filter(|exponent| *exponent <= exponent_limit as usize)
.ok_or(SymbolicError::Unsupported("symbolic EXP exponent"))?;
let mut expr = SymExpr::zero(cx);
for candidate in (0..=max_exponent).rev() {
let candidate_expr = SymExpr::constant(cx, U256::from(candidate));
let condition = SymBoolExpr::eq(cx, exponent.clone(), candidate_expr);
let value = exp_expr_for_concrete_exponent(cx, base.clone(), candidate);
expr = SymExpr::ite(cx, condition, value, expr);
}
expr
};
self.stack.push(result)?;
Ok(StepOutcome::Continue)
}
pub(crate) fn balance<FEN: FoundryEvmNetwork>(
&self,
cx: &mut SymCx,
executor: &Executor<FEN>,
address: Address,
) -> SymExpr {
self.world.balance_word_for_address(cx, executor, address)
}
pub(crate) fn balance_word<FEN: FoundryEvmNetwork>(
&mut self,
cx: &mut SymCx,
executor: &Executor<FEN>,
address_expr: SymExpr,
) -> Result<SymExpr, SymbolicError> {
self.world.balance_word(cx, executor, address_expr)
}
pub(crate) fn extcode_size_word<FEN: FoundryEvmNetwork>(
&mut self,
cx: &mut SymCx,
executor: &Executor<FEN>,
address_expr: SymExpr,
) -> Result<SymExpr, SymbolicError> {
self.world.extcode_size_word(cx, executor, address_expr)
}
pub(crate) fn extcode_hash_word<FEN: FoundryEvmNetwork>(
&mut self,
cx: &mut SymCx,
executor: &Executor<FEN>,
address_expr: SymExpr,
) -> Result<SymExpr, SymbolicError> {
self.world.extcode_hash_word(cx, executor, address_expr)
}
pub(crate) fn extcode_bytes_word<FEN: FoundryEvmNetwork>(
&mut self,
cx: &mut SymCx,
executor: &Executor<FEN>,
address_expr: SymExpr,
offset: SymExpr,
size: usize,
) -> Result<SymBytes, SymbolicError> {
self.world.extcode_bytes_word(cx, executor, address_expr, offset, size)
}
pub(crate) fn pop_address_word_or_symbolic_slot(
&mut self,
cx: &mut SymCx,
) -> Result<(SymExpr, Address), SymbolicError> {
let expr = self.stack.pop()?;
let address = self.address_or_symbolic_slot(cx, expr.clone());
Ok((expr, address))
}
pub(crate) fn address_or_symbolic_slot(&mut self, cx: &mut SymCx, expr: SymExpr) -> Address {
if let Some(value) = self.constrained_word(cx, &expr) {
return word_to_address(value);
}
self.world.resolve_address(&expr).unwrap_or_else(|| self.world.symbolic_address_slot(expr))
}
pub(crate) fn fresh_word(&mut self, cx: &mut SymCx, prefix: &'static str) -> SymExpr {
let id = self.next_symbol;
self.next_symbol += 1;
SymExpr::var(cx, &format!("{prefix}_{id}"))
}
pub(crate) fn fresh_gasleft(&mut self, cx: &mut SymCx) -> SymExpr {
let id = self.next_symbol;
self.next_symbol += 1;
SymExpr::gas_left(cx, id)
}
pub(crate) fn fresh_bounded_uint(&mut self, cx: &mut SymCx, bits: U256) -> SymExpr {
let value = self.fresh_word(cx, "symbolic");
if bits < U256::from(256) {
let upper = if bits.is_zero() {
U256::ZERO
} else {
U256::from(1) << usize::try_from(bits).expect("checked bit width")
};
self.constraints.push(SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &value, upper));
}
value
}
pub(crate) fn fresh_bytes(&mut self, cx: &mut SymCx, len: usize) -> Vec<SymExpr> {
(0..len).map(|_| self.fresh_bounded_uint(cx, U256::from(8))).collect()
}
pub(crate) fn fresh_printable_ascii_bytes(
&mut self,
cx: &mut SymCx,
len: usize,
) -> Vec<SymExpr> {
(0..len)
.map(|_| {
let byte = self.fresh_bounded_uint(cx, U256::from(8));
self.constraints.push(SymBoolExpr::cmp_word_const(
cx,
SymCmpOp::Uge,
&byte,
U256::from(0x20),
));
self.constraints.push(SymBoolExpr::cmp_word_const(
cx,
SymCmpOp::Ule,
&byte,
U256::from(0x7e),
));
byte
})
.collect()
}
pub(crate) fn fresh_bounded_int(&mut self, cx: &mut SymCx, bits: U256) -> SymExpr {
let value = self.fresh_word(cx, "symbolic");
if bits.is_zero() {
self.constraints.push(SymBoolExpr::eq_word_const(cx, &value, U256::ZERO));
} else if bits < U256::from(256) {
let magnitude =
U256::from(1) << (usize::try_from(bits).expect("checked bit width") - 1);
let lt = SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &value, magnitude);
let ge = SymBoolExpr::cmp_word_const(
cx,
SymCmpOp::Uge,
&value,
U256::ZERO.wrapping_sub(magnitude),
);
let condition = SymBoolExpr::or(cx, vec![lt, ge]);
self.constraints.push(condition);
}
value
}
pub(crate) fn prank_for_next_call(&mut self) -> (Address, SymExpr, Option<(Address, SymExpr)>) {
if let Some((caller, caller_word)) = self.prank.next_caller.take() {
(caller, caller_word, self.prank.next_origin.take())
} else {
match self.prank.persistent_caller.clone() {
Some((caller, caller_word)) => {
(caller, caller_word, self.prank.persistent_origin.clone())
}
None => {
(self.address, self.address_word.clone(), self.prank.persistent_origin.clone())
}
}
}
}
pub(crate) fn read_callers_words(&self, cx: &mut SymCx) -> Vec<SymExpr> {
let (mode, caller, origin) = if let Some((_, caller_word)) = self.prank.next_caller.as_ref()
{
(
U256::from(3),
caller_word.clone(),
self.prank
.next_origin
.as_ref()
.map(|(_, origin_word)| origin_word.clone())
.unwrap_or_else(|| self.origin_word.clone()),
)
} else if let Some((_, caller_word)) = self.prank.persistent_caller.as_ref() {
(
U256::from(4),
caller_word.clone(),
self.prank
.persistent_origin
.as_ref()
.map(|(_, origin_word)| origin_word.clone())
.unwrap_or_else(|| self.origin_word.clone()),
)
} else {
(U256::ZERO, self.caller_word.clone(), self.origin_word.clone())
};
vec![SymExpr::constant(cx, mode), caller, origin]
}
pub(crate) fn record_log(&mut self, log: SymbolicLog) {
if let Some(logs) = &mut self.recorded_logs {
logs.push(log);
}
}
pub(crate) fn record_sload(&mut self, address: Address, slot: SymExpr) {
if let Some(record) = &mut self.access_record {
record.read(address, slot);
}
}
pub(crate) fn record_sstore(&mut self, address: Address, slot: SymExpr) {
if let Some(record) = &mut self.access_record {
record.write(address, slot);
}
}
pub(crate) fn expectations_satisfied(&self) -> bool {
self.expected_revert.is_none()
&& self.expected_emit.as_ref().is_none_or(ExpectedEmit::is_satisfied)
&& self.expected_calls.iter().all(ExpectedCall::is_satisfied)
&& self.expected_creates.is_empty()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SymbolicStorageHook {
pub(crate) callback_target: Address,
pub(crate) callback_selector: [u8; 4],
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SymbolicLog {
topics: Arc<[SymExpr]>,
data_len: SymExpr,
data: SymBytes,
emitter: Address,
}
impl SymbolicLog {
pub(crate) fn new(
topics: Vec<SymExpr>,
data_len: SymExpr,
data: SymBytes,
emitter: Address,
) -> Self {
Self { topics: topics.into(), data_len, data, emitter }
}
pub(crate) fn into_parts(self) -> (Arc<[SymExpr]>, SymExpr, SymBytes, Address) {
(self.topics, self.data_len, self.data, self.emitter)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct AccessRecord {
reads: HashMap<Address, Vec<SymExpr>>,
writes: HashMap<Address, Vec<SymExpr>>,
}
impl AccessRecord {
pub(crate) fn read(&mut self, address: Address, slot: SymExpr) {
Self::push_unique_slot(self.reads.entry(address).or_default(), slot);
}
pub(crate) fn write(&mut self, address: Address, slot: SymExpr) {
self.read(address, slot.clone());
Self::push_unique_slot(self.writes.entry(address).or_default(), slot);
}
pub(crate) fn addresses(&self) -> Vec<Address> {
let mut addresses = HashSet::<Address>::default();
addresses.extend(self.reads.keys().copied());
addresses.extend(self.writes.keys().copied());
let mut addresses = addresses.into_iter().collect::<Vec<_>>();
addresses.sort_unstable();
addresses
}
pub(crate) fn read_slots(&self, address: Address) -> Vec<SymExpr> {
self.reads.get(&address).cloned().unwrap_or_default()
}
pub(crate) fn write_slots(&self, address: Address) -> Vec<SymExpr> {
self.writes.get(&address).cloned().unwrap_or_default()
}
fn push_unique_slot(slots: &mut Vec<SymExpr>, slot: SymExpr) {
if !slots.iter().any(|existing| existing == &slot) {
slots.push(slot);
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ExpectedRevert {
data: ExpectedRevertData,
reverter: Option<SymExpr>,
remaining: u64,
}
impl ExpectedRevert {
pub(crate) fn new(data: ExpectedRevertData, reverter: Option<SymExpr>, remaining: u64) -> Self {
Self { data, reverter, remaining: remaining.max(1) }
}
pub(crate) const fn consume_one(&mut self) -> bool {
self.remaining = self.remaining.saturating_sub(1);
self.remaining == 0
}
pub(crate) fn match_condition(
&self,
cx: &mut SymCx,
reverter: Address,
return_data: &SymReturnData,
) -> Option<SymBoolExpr> {
let mut conditions = Vec::new();
if let Some(expected_reverter) = &self.reverter {
conditions.push(expected_reverter.address_match_condition(cx, reverter));
}
match &self.data {
ExpectedRevertData::Any => {}
ExpectedRevertData::Prefix(prefix) => {
if return_data.len() < prefix.len() {
return None;
}
let prefix_len = SymExpr::constant(cx, U256::from(prefix.len()));
conditions.push(SymBoolExpr::cmp(
cx,
SymCmpOp::Uge,
return_data.len_expr(),
prefix_len,
));
conditions.extend((0..prefix.len()).map(|offset| {
let expected = prefix.byte(cx, offset);
let actual = return_data.byte(cx, offset);
SymBoolExpr::eq(cx, actual, expected)
}));
}
ExpectedRevertData::Exact(data) => {
if return_data.len() < data.len() {
return None;
}
let len = SymExpr::constant(cx, U256::from(data.len()));
conditions.push(SymBoolExpr::eq(cx, return_data.len_expr(), len));
conditions.extend((0..data.len()).map(|offset| {
let expected = data.byte(cx, offset);
let actual = return_data.byte(cx, offset);
SymBoolExpr::eq(cx, actual, expected)
}));
}
}
Some(SymBoolExpr::and(cx, conditions))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ExpectedRevertData {
Any,
Prefix(SymBytes),
Exact(SymBytes),