-
Notifications
You must be signed in to change notification settings - Fork 93
/
abi.rs
1269 lines (1153 loc) · 38.8 KB
/
abi.rs
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
/// Definition of ABI types and their encoding, decoding, mutating methods
use crate::evm::abi::ABILossyType::{TArray, TDynamic, TEmpty, TUnknown, T256};
use crate::evm::mutation_utils::{byte_mutator, byte_mutator_with_expansion};
use crate::generic_vm::vm_state::VMStateT;
use crate::state::{HasCaller, HasItyState};
use bytes::Bytes;
use itertools::Itertools;
use libafl::inputs::{HasBytesVec, Input};
use libafl::mutators::MutationResult;
use libafl::prelude::{HasMetadata, Mutator, Rand};
use libafl::state::{HasMaxSize, HasRand, State};
use once_cell::sync::Lazy;
use rand::random;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter, Write};
use std::ops::{Deref, DerefMut};
use crate::evm::types::{EVMAddress, EVMU256};
use super::concolic::concolic_host::Expr;
/// Mapping from known signature to function name
static mut FUNCTION_SIG: Lazy<HashMap<[u8; 4], String>> = Lazy::new(|| HashMap::new());
/// todo: remove this
static mut CONCOLIC_COUNTER: u64 = 0;
/// Convert a vector of bytes to hex string
fn vec_to_hex(v: &Vec<u8>) -> String {
let mut s = String::new();
s.push_str("0x");
for i in v {
s.push_str(&format!("{:02x}", i));
}
s
}
/// Calculate the smallest multiple of [`multiplier`] that is larger than or equal to [`x`] (round up)
fn roundup(x: usize, multiplier: usize) -> usize {
(x + multiplier - 1) / multiplier * multiplier
}
/// Set the first 32 bytes of [`bytes`] to be [`len`] (LSB)
///
/// E.g. if len = 0x1234,
/// then bytes is set to 0x00000000000000000000000000000000000000000000001234
fn set_size(bytes: *mut u8, len: usize) {
let mut rem: usize = len;
unsafe {
for i in 0..32 {
*bytes.add(31 - i) = (rem & 0xff) as u8;
rem >>= 8;
}
}
}
/// ABI types
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum ABILossyType {
/// All 256-bit types (uint8, uint16, uint32, uint64, uint128, uint256, address...)
T256,
/// All array types (X[], X[n], (X,Y,Z))
TArray,
/// All dynamic types (string, bytes...)
TDynamic,
/// Empty type (nothing)
TEmpty,
/// Unknown type (e.g., those we don't know ABI, it can be any type)
TUnknown,
}
/// Traits of ABI types (encoding, decoding, etc.)
pub trait ABI: CloneABI + serde_traitobject::Serialize + serde_traitobject::Deserialize {
/// Is the args static (i.e., fixed size)
fn is_static(&self) -> bool;
/// Get the ABI-encoded bytes of args
fn get_bytes(&self) -> Vec<u8>;
/// Get the ABI type of args
fn get_type(&self) -> ABILossyType;
/// Set the bytes to args, used for decoding
fn set_bytes(&mut self, bytes: Vec<u8>);
/// Convert args to string (for debugging)
fn to_string(&self) -> String;
fn as_any(&mut self) -> &mut dyn Any;
fn get_concolic(&self) -> Vec<Box<Expr>>;
/// Get the size of args
fn get_size(&self) -> usize;
}
impl Debug for dyn ABI {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ABI")
.field("is_static", &self.is_static())
.field("get_bytes", &self.get_bytes())
.finish()
}
}
/// Cloneable trait object, to support serde serialization
pub trait CloneABI {
fn clone_box(&self) -> Box<dyn ABI>;
}
impl<T> CloneABI for T
where
T: ABI + Clone + 'static,
{
fn clone_box(&self) -> Box<dyn ABI> {
Box::new(self.clone())
}
}
/// ABI wrapper + function hash, to support serde serialization
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct BoxedABI {
/// ABI wrapper
#[serde(with = "serde_traitobject")]
pub b: Box<dyn ABI>,
/// Function hash, if it is 0x00000000, it means the function hash is not set or
/// this is to resume execution from a previous control leak
pub function: [u8; 4],
}
impl BoxedABI {
/// Create a new ABI wrapper with function hash = 0x00000000
pub fn new(b: Box<dyn ABI>) -> Self {
Self {
b,
function: [0; 4],
}
}
/// Get the args in ABI form (unencoded)
pub fn get(&self) -> &Box<dyn ABI> {
&self.b
}
/// Get the args in ABI form (unencoded) mutably
pub fn get_mut(&mut self) -> &mut Box<dyn ABI> {
&mut self.b
}
/// Get the function hash + encoded args (transaction data)
pub fn get_bytes(&self) -> Vec<u8> {
[Vec::from(self.function), self.b.get_bytes()].concat()
}
/// Get the function hash + encoded args (transaction data)
pub fn get_bytes_vec(&self) -> Vec<u8> {
self.b.get_bytes()
}
/// Determine if the args is static (i.e., fixed size)
pub fn is_static(&self) -> bool {
self.b.is_static()
}
/// Get the ABI type of args.
/// If the function has more than one args, it will return Array type (tuple of args)
pub fn get_type(&self) -> ABILossyType {
self.b.get_type()
}
/// Get the ABI type of args in string format
pub fn get_type_str(&self) -> String {
match self.b.get_type() {
T256 => "A256".to_string(),
TArray => "AArray".to_string(),
TDynamic => "ADynamic".to_string(),
TEmpty => "AEmpty".to_string(),
TUnknown => "AUnknown".to_string(),
}
}
/// Set the function hash
pub fn set_func(&mut self, function: [u8; 4]) {
self.function = function;
}
/// Set the function hash with function name, so that we can print the function name instead of hash
pub fn set_func_with_name(&mut self, function: [u8; 4], function_name: String) {
self.function = function;
unsafe {
FUNCTION_SIG.insert(function, function_name);
}
}
/// Convert function hash and args to string (for debugging)
pub fn to_string(&self) -> String {
if self.function == [0; 4] {
format!("Stepping with return: {}", hex::encode(self.b.to_string()))
} else {
let function_name = unsafe {
FUNCTION_SIG
.get(&self.function)
.unwrap_or(&hex::encode(self.function))
.clone()
};
format!("{}{}", function_name, self.b.to_string())
}
}
/// todo: remove this
pub fn get_concolic(self) -> Vec<Box<Expr>> {
[
self.function
.iter()
.map(|byte| Expr::const_byte(*byte))
.collect_vec(),
self.b.get_concolic(),
]
.concat()
}
/// Set the bytes to args, used for decoding
pub fn set_bytes(&mut self, bytes: Vec<u8>) {
self.b.set_bytes(bytes);
}
}
/// Randomly sample an args with any type with size `size`
fn sample_abi<Loc, Addr, VS, S>(state: &mut S, size: usize) -> BoxedABI
where
S: State + HasRand + HasItyState<Loc, Addr, VS> + HasMaxSize + HasCaller<EVMAddress>,
VS: VMStateT + Default,
Loc: Clone + Debug + Serialize + DeserializeOwned,
Addr: Clone + Debug + Serialize + DeserializeOwned,
{
// TODO(@shou): use a better sampling strategy
if size == 32 {
// sample a static type
match state.rand_mut().below(100) % 2 {
0 => BoxedABI::new(Box::new(A256 {
data: vec![0; 32],
is_address: false,
dont_mutate: false,
})),
1 => BoxedABI::new(Box::new(A256 {
data: state.get_rand_address().0.into(),
is_address: true,
dont_mutate: false,
})),
_ => unreachable!(),
}
} else {
// sample a dynamic type
let max_size = state.max_size();
let vec_size = state.rand_mut().below(max_size as u64) as usize;
match state.rand_mut().below(100) % 4 {
// dynamic
0 => BoxedABI::new(Box::new(ADynamic {
data: vec![state.rand_mut().below(255) as u8; vec_size],
multiplier: 32,
})),
// tuple
1 => BoxedABI::new(Box::new(AArray {
data: vec![sample_abi(state, 32); vec_size],
dynamic_size: false,
})),
// array[]
2 => {
let abi = sample_abi(state, 32);
BoxedABI::new(Box::new(AArray {
data: vec![abi; vec_size],
dynamic_size: false,
}))
}
// array[...]
3 => {
let abi = sample_abi(state, 32);
BoxedABI::new(Box::new(AArray {
data: vec![abi; vec_size],
dynamic_size: true,
}))
}
_ => unreachable!(),
}
}
}
impl BoxedABI {
/// Mutate the args
pub fn mutate<Loc, Addr, VS, S>(&mut self, state: &mut S) -> MutationResult
where
S: State
+ HasRand
+ HasMaxSize
+ HasItyState<Loc, Addr, VS>
+ HasCaller<EVMAddress>
+ HasMetadata,
VS: VMStateT + Default,
Loc: Clone + Debug + Serialize + DeserializeOwned,
Addr: Clone + Debug + Serialize + DeserializeOwned,
{
self.mutate_with_vm_slots(state, None)
}
/// Mutate the args and crossover with slots in the VM state
///
/// Check [`VMStateHintedMutator`] for more details
pub fn mutate_with_vm_slots<Loc, Addr, VS, S>(
&mut self,
state: &mut S,
vm_slots: Option<HashMap<EVMU256, EVMU256>>,
) -> MutationResult
where
S: State
+ HasRand
+ HasMaxSize
+ HasItyState<Loc, Addr, VS>
+ HasCaller<EVMAddress>
+ HasMetadata,
VS: VMStateT + Default,
Loc: Clone + Debug + Serialize + DeserializeOwned,
Addr: Clone + Debug + Serialize + DeserializeOwned,
{
match self.get_type() {
// no need to mutate empty args
TEmpty => MutationResult::Skipped,
// mutate static args
T256 => {
let v = self.b.deref_mut().as_any();
let a256 = v.downcast_mut::<A256>().unwrap();
if a256.dont_mutate {
return MutationResult::Skipped;
}
if a256.is_address {
if state.rand_mut().below(100) < 90 {
a256.data = state.get_rand_address().0.to_vec();
} else {
a256.data = [0; 20].to_vec();
}
MutationResult::Mutated
} else {
byte_mutator(state, a256, vm_slots)
}
}
// mutate dynamic args
TDynamic => {
let adyn = self
.b
.deref_mut()
.as_any()
.downcast_mut::<ADynamic>()
.unwrap();
// self.b.downcast_ref::<A256>().unwrap().mutate(state);
byte_mutator_with_expansion(state, adyn, vm_slots)
}
// mutate tuple/array args
TArray => {
let aarray = self
.b
.deref_mut()
.as_any()
.downcast_mut::<AArray>()
.unwrap();
let data_len = aarray.data.len();
if data_len == 0 {
return MutationResult::Skipped;
}
if aarray.dynamic_size {
match state.rand_mut().below(100) {
0..=80 => {
let index: usize = state.rand_mut().next() as usize % data_len;
let result = aarray.data[index].mutate_with_vm_slots(state, vm_slots);
return result;
}
81..=90 => {
// increase size
if state.max_size() <= aarray.data.len() {
return MutationResult::Skipped;
}
for _ in 0..state.rand_mut().next() as usize % state.max_size() {
aarray.data.push(aarray.data[0].clone());
}
}
91..=100 => {
// decrease size
if aarray.data.len() < 1 {
return MutationResult::Skipped;
}
let index: usize = state.rand_mut().next() as usize % data_len;
aarray.data.remove(index);
}
_ => {
unreachable!()
}
}
} else {
let index: usize = state.rand_mut().next() as usize % data_len;
return aarray.data[index].mutate_with_vm_slots(state, vm_slots);
}
MutationResult::Mutated
}
// mutate unknown args, may change the type
TUnknown => {
let a_unknown = self
.b
.deref_mut()
.as_any()
.downcast_mut::<AUnknown>()
.unwrap();
unsafe {
if a_unknown.size == 0 {
a_unknown.concrete = BoxedABI::new(Box::new(AEmpty {}));
return MutationResult::Skipped;
}
if (state.rand_mut().below(100)) < 80 {
a_unknown
.concrete
.mutate_with_vm_slots(state, vm_slots)
} else {
a_unknown.concrete = sample_abi(state, a_unknown.size);
MutationResult::Mutated
}
}
}
}
}
}
impl Clone for Box<dyn ABI> {
fn clone(&self) -> Box<dyn ABI> {
self.clone_box()
}
}
/// AEmpty is used to represent empty args
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AEmpty {}
impl Input for AEmpty {
fn generate_name(&self, idx: usize) -> String {
format!("AEmpty_{}", idx)
}
}
impl ABI for AEmpty {
fn is_static(&self) -> bool {
panic!("unreachable");
}
fn get_bytes(&self) -> Vec<u8> {
Vec::new()
}
fn get_type(&self) -> ABILossyType {
TEmpty
}
fn set_bytes(&mut self, bytes: Vec<u8>) {
assert!(bytes.len() == 0);
}
fn to_string(&self) -> String {
"".to_string()
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn get_concolic(&self) -> Vec<Box<Expr>> {
Vec::new()
}
fn get_size(&self) -> usize {
0
}
}
/// [`A256`] is used to represent 256-bit args
/// (including uint8, uint16... as they are all 256-bit behind the scene)
///
/// For address type, we need to distinguish between it and rest so that we can mutate correctly.
/// Instead of mutating address as a 256-bit integer, we mutate it to known address or zero address.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct A256 {
/// 256-bit or less data representing the arg
pub data: Vec<u8>,
/// whether this arg is an address
pub is_address: bool,
/// whether this arg should not be mutated
pub dont_mutate: bool,
}
impl Input for A256 {
fn generate_name(&self, idx: usize) -> String {
format!("A256_{}", idx)
}
}
impl HasBytesVec for A256 {
fn bytes(&self) -> &[u8] {
self.data.as_slice()
}
fn bytes_mut(&mut self) -> &mut Vec<u8> {
self.data.as_mut()
}
}
impl ABI for A256 {
fn is_static(&self) -> bool {
// 256-bit args are always static
true
}
fn get_bytes(&self) -> Vec<u8> {
// pad self.data to 32 bytes with 0s on the left
let mut bytes = vec![0; 32];
let data_len = self.data.len();
unsafe {
let mut ptr = bytes.as_mut_ptr();
ptr = ptr.add(32 - data_len);
for i in 0..data_len {
*ptr.add(i) = self.data[i];
}
}
bytes
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn get_type(&self) -> ABILossyType {
T256
}
fn set_bytes(&mut self, bytes: Vec<u8>) {
self.data = bytes;
}
fn to_string(&self) -> String {
vec_to_hex(&self.data)
}
fn get_concolic(&self) -> Vec<Box<Expr>> {
let mut bytes = vec![Expr::const_byte(0 as u8); 32];
let data_len = self.data.len();
unsafe {
let counter = CONCOLIC_COUNTER;
CONCOLIC_COUNTER += 1;
let mut ptr = bytes.as_mut_ptr();
ptr = ptr.add(32 - data_len);
for i in 0..data_len {
*ptr.add(i) = Expr::sym_byte(format!("{}_A256_{}", counter, i));
}
}
bytes
}
fn get_size(&self) -> usize {
32
}
}
/// [`ADynamic`] is used to represent dynamic args
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ADynamic {
/// data representing the arg
data: Vec<u8>,
/// multiplier used to round up the size of the data
multiplier: usize,
}
impl Input for ADynamic {
fn generate_name(&self, idx: usize) -> String {
format!("ADynamic_{}", idx)
}
}
impl HasBytesVec for ADynamic {
fn bytes(&self) -> &[u8] {
self.data.as_slice()
}
fn bytes_mut(&mut self) -> &mut Vec<u8> {
self.data.as_mut()
}
}
impl ABI for ADynamic {
fn is_static(&self) -> bool {
false
}
fn get_bytes(&self) -> Vec<u8> {
// pad self.data to K bytes with 0s on the left
// where K is the smallest multiple of self.multiplier that is larger than self.data.len()
let new_len: usize = roundup(self.data.len(), self.multiplier);
let mut bytes = vec![0; new_len + 32];
unsafe {
let ptr = bytes.as_mut_ptr();
set_size(ptr, self.data.len());
// set data
for i in 0..self.data.len() {
*ptr.add(i + 32) = self.data[i];
}
}
bytes
}
fn get_type(&self) -> ABILossyType {
TDynamic
}
fn to_string(&self) -> String {
vec_to_hex(&self.data)
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn set_bytes(&mut self, bytes: Vec<u8>) {
self.data = bytes;
}
fn get_concolic(&self) -> Vec<Box<Expr>> {
let new_len: usize = roundup(self.data.len(), self.multiplier);
let mut bytes = vec![Expr::const_byte(0 as u8); new_len + 32];
unsafe {
let counter = CONCOLIC_COUNTER;
CONCOLIC_COUNTER += 1;
let ptr = bytes.as_mut_ptr();
// here we assume the size of the dynamic data
// will not change. However, this may change as well
let mut rem: usize = self.data.len();
for i in 0..32 {
*ptr.add(31 - i) = Expr::const_byte((rem & 0xff) as u8);
rem >>= 8;
}
// set data
for i in 0..self.data.len() {
*ptr.add(i + 32) = Expr::sym_byte(format!("ADynamic_{}_{}", counter, i));
}
}
bytes
}
fn get_size(&self) -> usize {
self.data.len() + 32
}
}
/// [`AArray`] is used to represent array or tuple
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AArray {
/// vector of ABI objects in the array / tuple
pub(crate) data: Vec<BoxedABI>,
/// whether the size of the array is dynamic (i.e., is it dynamic size array)
pub(crate) dynamic_size: bool,
}
impl Input for AArray {
fn generate_name(&self, idx: usize) -> String {
format!("AArray_{}", idx)
}
}
fn set_size_concolic(bytes: *mut Box<Expr>, len: usize) {
let mut rem: usize = len;
unsafe {
for i in 0..32 {
*bytes.add(31 - i) = Expr::const_byte((rem & 0xff) as u8);
rem >>= 8;
}
}
}
impl ABI for AArray {
fn is_static(&self) -> bool {
if self.dynamic_size {
false
} else {
self.data.iter().all(|x| x.is_static())
}
}
fn get_bytes(&self) -> Vec<u8> {
// check Solidity spec for encoding of arrays
let mut tail_data: Vec<Vec<u8>> = Vec::new();
let mut tails_offset: Vec<usize> = Vec::new();
let mut head: Vec<Vec<u8>> = Vec::new();
let mut head_data: Vec<Vec<u8>> = Vec::new();
let mut head_size: usize = 0;
let dummy_bytes: Vec<u8> = vec![0; 0];
for i in 0..self.data.len() {
if self.data[i].is_static() {
let encoded = self.data[i].get_bytes_vec();
head_size += encoded.len();
head.push(encoded);
tail_data.push(dummy_bytes.clone());
} else {
tail_data.push(self.data[i].get_bytes_vec());
head.push(dummy_bytes.clone());
head_size += 32;
}
}
let mut content_size: usize = 0;
tails_offset.push(0);
let mut head_data_size: usize = 0;
let mut tail_data_size: usize = 0;
if tail_data.len() > 0 {
for i in 0..tail_data.len() - 1 {
content_size += tail_data[i].len();
tails_offset.push(content_size);
}
for i in 0..tails_offset.len() {
if head[i].len() == 0 {
head_data.push(vec![0; 32]);
head_data_size += 32;
set_size(head_data[i].as_mut_ptr(), tails_offset[i] + head_size);
} else {
head_data.push(head[i].clone());
head_data_size += head[i].len();
}
}
tail_data_size = content_size + tail_data[tail_data.len() - 1].len();
}
let mut bytes =
vec![0; head_data_size + tail_data_size + if self.dynamic_size { 32 } else { 0 }];
if self.dynamic_size {
set_size(bytes.as_mut_ptr(), self.data.len());
}
let mut offset: usize = if self.dynamic_size { 32 } else { 0 };
for i in 0..head_data.len() {
bytes[offset..offset + head_data[i].len()]
.copy_from_slice(head_data[i].to_vec().as_slice());
offset += head_data[i].len();
}
for i in 0..tail_data.len() {
bytes[offset..offset + tail_data[i].len()]
.copy_from_slice(tail_data[i].to_vec().as_slice());
offset += tail_data[i].len();
}
bytes
}
fn get_type(&self) -> ABILossyType {
TArray
}
fn to_string(&self) -> String {
format!(
"({})",
self.data.iter().map(|x| x.b.deref().to_string()).join(",")
)
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
// Input: packed concrete bytes produced by get_concolic
// Set the bytes in self.data accordingly
fn set_bytes(&mut self, bytes: Vec<u8>) {
// TODO: here we need to able to perform
// the inverse of get_bytes
if self.dynamic_size {
// to usize
let size: usize = bytes[0..32]
.iter()
.fold(0, |acc, x| (acc << 8) + *x as usize);
if size != self.data.len() {
unreachable!("Array size mismatch");
}
}
let mut offset = if self.dynamic_size { 32 } else { 0 };
//
// let head_offsets = vec![];
// let tail_offsets = vec![];
//
// for mut item in self.data {
// if item.is_static() {
// // let len = item.b.get_size();
// // let mut new_bytes = vec![0; len];
// // new_bytes.copy_from_slice(&bytes[offset..offset + len]);
// // item.b.set_bytes(new_bytes);
// // head_offsets.push();
// } else {
//
// }
// }
}
fn get_concolic(&self) -> Vec<Box<Expr>> {
let mut tail_data: Vec<Vec<u8>> = Vec::new();
let mut tails_offset: Vec<usize> = Vec::new();
let mut head: Vec<Vec<u8>> = Vec::new();
let mut head_data: Vec<Vec<u8>> = Vec::new();
let mut head_size: usize = 0;
let dummy_bytes: Vec<u8> = vec![0; 0];
for i in 0..self.data.len() {
if self.data[i].is_static() {
let encoded = self.data[i].get_bytes_vec();
head_size += encoded.len();
head.push(encoded);
tail_data.push(dummy_bytes.clone());
} else {
tail_data.push(self.data[i].get_bytes_vec());
head.push(dummy_bytes.clone());
head_size += 32;
}
}
let mut content_size: usize = 0;
tails_offset.push(0);
let mut head_data_size: usize = 0;
let mut tail_data_size: usize = 0;
if tail_data.len() > 0 {
for i in 0..tail_data.len() - 1 {
content_size += tail_data[i].len();
tails_offset.push(content_size);
}
for i in 0..tails_offset.len() {
if head[i].len() == 0 {
head_data.push(vec![0; 32]);
head_data_size += 32;
set_size(head_data[i].as_mut_ptr(), tails_offset[i] + head_size);
} else {
head_data.push(head[i].clone());
head_data_size += head[i].len();
}
}
tail_data_size = content_size + tail_data[tail_data.len() - 1].len();
}
let mut bytes =
vec![
Expr::const_byte(0);
head_data_size + tail_data_size + if self.dynamic_size { 32 } else { 0 }
];
if self.dynamic_size {
set_size_concolic(bytes.as_mut_ptr(), self.data.len());
}
let mut offset: usize = if self.dynamic_size { 32 } else { 0 };
for i in 0..head_data.len() {
if self.data[i].is_static() {
unsafe {
let counter = CONCOLIC_COUNTER;
CONCOLIC_COUNTER += 1;
for j in 0..head_data[i].len() {
bytes[offset + j] = Expr::sym_byte(format!(
"{}_{}_{}",
counter,
self.data[i].get_type_str(),
i
));
}
}
} else {
bytes[offset..offset + head_data[i].len()].clone_from_slice(
head_data[i]
.iter()
.map(|x| Expr::const_byte(*x))
.collect_vec()
.as_slice(),
);
}
offset += head_data[i].len();
}
for i in 0..tail_data.len() {
if tail_data[i].len() > 0 {
unsafe {
let counter = CONCOLIC_COUNTER;
CONCOLIC_COUNTER += 1;
for j in 0..tail_data[i].len() {
bytes[offset + j] = Expr::sym_byte(format!(
"{}_{}_{}",
counter,
self.data[i].get_type_str(),
i
));
}
}
offset += tail_data[i].len();
}
}
bytes
}
fn get_size(&self) -> usize {
let data_size = self.data.iter().map(|x| x.b.get_size()).sum::<usize>();
if self.dynamic_size {
32 + data_size
} else {
data_size
}
}
}
/// [`AUnknown`] represents arg with no known types (can be any type)
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AUnknown {
/// Current concrete arg
pub concrete: BoxedABI,
/// Size constraint
pub size: usize,
}
impl Input for AUnknown {
fn generate_name(&self, idx: usize) -> String {
format!("AUnknown_{}", idx)
}
}
impl ABI for AUnknown {
fn is_static(&self) -> bool {
self.concrete.is_static()
}
fn get_bytes(&self) -> Vec<u8> {
self.concrete.b.get_bytes()
}
fn get_type(&self) -> ABILossyType {
TUnknown
}
fn set_bytes(&mut self, bytes: Vec<u8>) {
self.concrete.b.set_bytes(bytes);
}
fn to_string(&self) -> String {
self.concrete.b.to_string()
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn get_concolic(&self) -> Vec<Box<Expr>> {
panic!("[Concolic] sAUnknown not supported")
}
fn get_size(&self) -> usize {
self.concrete.b.get_size()
}
}
/// Create a [`BoxedABI`] with default arg given the ABI type in string
pub fn get_abi_type_boxed(abi_name: &String) -> BoxedABI {
return BoxedABI {
b: get_abi_type(abi_name, &None),
function: [0; 4],
};
}
/// Create a [`BoxedABI`] with default arg given the ABI type in string and address
/// todo: remove this function
pub fn get_abi_type_boxed_with_address(abi_name: &String, address: Vec<u8>) -> BoxedABI {
return BoxedABI {
b: get_abi_type(abi_name, &Some(address)),
function: [0; 4],
};
}
/// Split a string with parenthesis
///
/// # Example
/// ```
/// use ityfuzz::evm::abi::split_with_parenthesis;
/// let s = "a,b,(c,d),e";
/// let result = split_with_parenthesis(s);
/// assert_eq!(result, vec!["a", "b", "(c,d)", "e"]);
/// ```
pub fn split_with_parenthesis(s: &str) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let mut current: String = String::new();
let mut parenthesis: i32 = 0;
for c in s.chars() {
if c == '(' {
parenthesis += 1;
} else if c == ')' {
parenthesis -= 1;
}
if c == ',' && parenthesis == 0 {
result.push(current);
current = String::new();
} else {
current.push(c);
}
}