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
use crate::{borrow_graph::BorrowGraph, error::VMError};
use move_binary_format::{
access::ModuleAccess,
file_format::{
empty_module, Ability, AbilitySet, CompiledModule, FieldInstantiation,
FieldInstantiationIndex, FunctionHandleIndex, FunctionInstantiation,
FunctionInstantiationIndex, Signature, SignatureIndex, SignatureToken,
StructDefInstantiation, StructDefInstantiationIndex, StructDefinitionIndex, TableIndex,
},
};
use std::{
collections::{HashMap, HashSet},
fmt,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BorrowState {
Available,
Unavailable,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbstractValue {
pub token: SignatureToken,
pub abilities: AbilitySet,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mutability {
Mutable,
Immutable,
Either,
}
impl AbstractValue {
pub fn new_primitive(token: SignatureToken) -> AbstractValue {
checked_precondition!(
match token {
SignatureToken::Struct(_)
| SignatureToken::StructInstantiation(_, _)
| SignatureToken::Reference(_)
| SignatureToken::MutableReference(_)
| SignatureToken::Signer
| SignatureToken::Vector(_)
| SignatureToken::TypeParameter(_) => false,
SignatureToken::Bool
| SignatureToken::Address
| SignatureToken::U8
| SignatureToken::U64
| SignatureToken::U128 => true,
},
"AbstractValue::new_primitive must be applied with primitive type"
);
AbstractValue {
token,
abilities: AbilitySet::PRIMITIVES,
}
}
pub fn new_reference(token: SignatureToken, abilities: AbilitySet) -> AbstractValue {
checked_precondition!(
matches!(
token,
SignatureToken::Reference(_) | SignatureToken::MutableReference(_)
),
"AbstractValue::new_reference must be applied with a reference type"
);
AbstractValue { token, abilities }
}
pub fn new_struct(token: SignatureToken, abilities: AbilitySet) -> AbstractValue {
checked_precondition!(
matches!(token, SignatureToken::Struct(_)),
"AbstractValue::new_struct must be applied with a struct type"
);
AbstractValue { token, abilities }
}
pub fn new_value(token: SignatureToken, abilities: AbilitySet) -> AbstractValue {
AbstractValue { token, abilities }
}
pub fn is_generic(&self) -> bool {
Self::is_generic_token(&self.token)
}
fn is_generic_token(token: &SignatureToken) -> bool {
match token {
SignatureToken::TypeParameter(_) => true,
SignatureToken::StructInstantiation(_, _) => true,
SignatureToken::Reference(tok) | SignatureToken::MutableReference(tok) => {
Self::is_generic_token(tok)
}
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallGraph {
calls: HashMap<FunctionHandleIndex, HashSet<FunctionHandleIndex>>,
max_function_handle_index: usize,
}
impl CallGraph {
pub fn new(max_function_handle_index: usize) -> Self {
Self {
calls: HashMap::new(),
max_function_handle_index,
}
}
pub fn add_call(&mut self, caller: FunctionHandleIndex, callee: FunctionHandleIndex) {
self.calls
.entry(caller)
.or_insert_with(HashSet::new)
.insert(callee);
}
pub fn can_call(&self, my_index: FunctionHandleIndex) -> Vec<FunctionHandleIndex> {
(0..self.max_function_handle_index)
.filter(|index| {
self.call_depth(my_index, FunctionHandleIndex(*index as TableIndex))
.is_some()
})
.map(|i| FunctionHandleIndex(i as TableIndex))
.collect()
}
pub fn max_calling_depth(&self, index: FunctionHandleIndex) -> usize {
let mut instantiation_depth = 0;
for (caller, callees) in self.calls.iter() {
for callee in callees.iter() {
if *callee == index {
let depth = self.max_calling_depth(*caller) + 1;
instantiation_depth = std::cmp::max(depth, instantiation_depth);
}
}
}
instantiation_depth
}
pub fn call_depth(
&self,
caller: FunctionHandleIndex,
callee: FunctionHandleIndex,
) -> Option<usize> {
if caller == callee {
return None;
}
match self.calls.get(&callee) {
None => Some(1),
Some(callee_callees) => {
if callee_callees.contains(&caller) {
return None;
}
let call_depths = callee_callees
.iter()
.filter_map(|callee_callee| self.call_depth(caller, *callee_callee))
.collect::<Vec<_>>();
if call_depths.len() < callee_callees.len() {
None
} else {
let max = call_depths.iter().max().unwrap();
Some(max + 1)
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct InstantiableModule {
sig_instance_for_offset: Vec<Vec<SignatureToken>>,
instantiations: HashMap<Vec<SignatureToken>, SignatureIndex>,
struct_instance_for_offset: Vec<StructDefInstantiation>,
struct_instantiations: HashMap<StructDefInstantiation, StructDefInstantiationIndex>,
func_instance_for_offset: Vec<FunctionInstantiation>,
function_instantiations: HashMap<FunctionInstantiation, FunctionInstantiationIndex>,
field_instance_for_offset: Vec<FieldInstantiation>,
field_instantiations: HashMap<FieldInstantiation, FieldInstantiationIndex>,
pub module: CompiledModule,
}
impl InstantiableModule {
pub fn new(module: CompiledModule) -> Self {
Self {
instantiations: module
.signatures()
.iter()
.enumerate()
.map(|(index, sig)| (sig.0.clone(), SignatureIndex(index as TableIndex)))
.collect::<HashMap<_, _>>(),
sig_instance_for_offset: module
.signatures()
.iter()
.map(|loc_sig| loc_sig.0.clone())
.collect(),
struct_instantiations: module
.struct_instantiations()
.iter()
.enumerate()
.map(|(index, si)| (si.clone(), StructDefInstantiationIndex(index as TableIndex)))
.collect::<HashMap<_, _>>(),
struct_instance_for_offset: module.struct_instantiations().to_vec(),
function_instantiations: module
.function_instantiations()
.iter()
.enumerate()
.map(|(index, fi)| (fi.clone(), FunctionInstantiationIndex(index as TableIndex)))
.collect::<HashMap<_, _>>(),
func_instance_for_offset: module.function_instantiations().to_vec(),
field_instantiations: module
.field_instantiations()
.iter()
.enumerate()
.map(|(index, fi)| (fi.clone(), FieldInstantiationIndex(index as TableIndex)))
.collect::<HashMap<_, _>>(),
field_instance_for_offset: module.field_instantiations().to_vec(),
module,
}
}
pub fn add_instantiation(&mut self, instantiant: Vec<SignatureToken>) -> SignatureIndex {
match self.instantiations.get(&instantiant) {
Some(index) => *index,
None => {
let current_index =
SignatureIndex(self.sig_instance_for_offset.len() as TableIndex);
self.instantiations
.insert(instantiant.clone(), current_index);
self.sig_instance_for_offset.push(instantiant);
current_index
}
}
}
pub fn add_struct_instantiation(
&mut self,
instantiant: StructDefInstantiation,
) -> StructDefInstantiationIndex {
match self.struct_instantiations.get(&instantiant) {
Some(index) => *index,
None => {
let current_index = StructDefInstantiationIndex(
self.struct_instance_for_offset.len() as TableIndex,
);
self.struct_instantiations
.insert(instantiant.clone(), current_index);
self.struct_instance_for_offset.push(instantiant);
current_index
}
}
}
pub fn add_function_instantiation(
&mut self,
instantiant: FunctionInstantiation,
) -> FunctionInstantiationIndex {
match self.function_instantiations.get(&instantiant) {
Some(index) => *index,
None => {
let current_index =
FunctionInstantiationIndex(self.func_instance_for_offset.len() as TableIndex);
self.function_instantiations
.insert(instantiant.clone(), current_index);
self.func_instance_for_offset.push(instantiant);
current_index
}
}
}
pub fn add_field_instantiation(
&mut self,
instantiant: FieldInstantiation,
) -> FieldInstantiationIndex {
match self.field_instantiations.get(&instantiant) {
Some(index) => *index,
None => {
let current_index =
FieldInstantiationIndex(self.field_instance_for_offset.len() as TableIndex);
self.field_instantiations
.insert(instantiant.clone(), current_index);
self.field_instance_for_offset.push(instantiant);
current_index
}
}
}
pub fn instantiantiation_at(&self, index: SignatureIndex) -> &Vec<SignatureToken> {
match self.sig_instance_for_offset.get(index.0 as usize) {
Some(vec) => vec,
None => {
panic!("Unable to get instantiation at offset: {:#?}", index);
}
}
}
pub fn struct_instantiantiation_at(
&self,
index: StructDefInstantiationIndex,
) -> &StructDefInstantiation {
match self.struct_instance_for_offset.get(index.0 as usize) {
Some(struct_inst) => struct_inst,
None => {
panic!("Unable to get instantiation at offset: {:#?}", index);
}
}
}
pub fn function_instantiantiation_at(
&self,
index: FunctionInstantiationIndex,
) -> &FunctionInstantiation {
match self.func_instance_for_offset.get(index.0 as usize) {
Some(func_inst) => func_inst,
None => {
panic!("Unable to get instantiation at offset: {:#?}", index);
}
}
}
pub fn field_instantiantiation_at(
&self,
index: FieldInstantiationIndex,
) -> &FieldInstantiation {
match self.field_instance_for_offset.get(index.0 as usize) {
Some(field_inst) => field_inst,
None => {
panic!("Unable to get instantiation at offset: {:#?}", index);
}
}
}
pub fn instantiate(self) -> CompiledModule {
let mut module = self.module;
module.signatures = self
.sig_instance_for_offset
.into_iter()
.map(Signature)
.collect();
module.struct_def_instantiations = self.struct_instance_for_offset;
module.function_instantiations = self.func_instance_for_offset;
module.field_instantiations = self.field_instance_for_offset;
module
}
}
#[derive(Debug, Clone)]
pub struct AbstractState {
stack: Vec<AbstractValue>,
pub instantiation: Vec<AbilitySet>,
locals: HashMap<usize, (AbstractValue, BorrowState)>,
register: Option<AbstractValue>,
pub module: InstantiableModule,
pub acquires_global_resources: Vec<StructDefinitionIndex>,
aborted: bool,
control_flow_allowed: bool,
borrow_graph: BorrowGraph,
pub call_graph: CallGraph,
}
impl AbstractState {
pub fn new() -> AbstractState {
let compiled_module = empty_module();
AbstractState {
stack: Vec::new(),
instantiation: Vec::new(),
locals: HashMap::new(),
register: None,
module: InstantiableModule::new(compiled_module),
acquires_global_resources: Vec::new(),
aborted: false,
control_flow_allowed: false,
borrow_graph: BorrowGraph::new(0),
call_graph: CallGraph::new(0),
}
}
pub fn from_locals(
module: CompiledModule,
locals: HashMap<usize, (AbstractValue, BorrowState)>,
instantiation: Vec<AbilitySet>,
acquires_global_resources: Vec<StructDefinitionIndex>,
call_graph: CallGraph,
) -> AbstractState {
let locals_len = locals.len();
let module = InstantiableModule::new(module);
AbstractState {
stack: Vec::new(),
instantiation,
locals,
module,
register: None,
acquires_global_resources,
aborted: false,
control_flow_allowed: false,
borrow_graph: BorrowGraph::new(locals_len as u8),
call_graph,
}
}
pub fn register_copy(&self) -> Option<AbstractValue> {
self.register.clone()
}
pub fn register_move(&mut self) -> Option<AbstractValue> {
let value = self.register.clone();
self.register = None;
value
}
pub fn register_set(&mut self, value: AbstractValue) {
self.register = Some(value);
}
pub fn stack_push(&mut self, item: AbstractValue) {
assume!(self.stack.len() < usize::max_value());
self.stack.push(item);
}
pub fn stack_push_register(&mut self) -> Result<(), VMError> {
if let Some(abstract_value) = self.register_move() {
assume!(self.stack.len() < usize::max_value());
self.stack.push(abstract_value);
Ok(())
} else {
Err(VMError::new("Error: No value in register".to_string()))
}
}
pub fn stack_pop(&mut self) -> Result<(), VMError> {
if self.stack.is_empty() {
Err(VMError::new("Pop attempted on empty stack".to_string()))
} else {
self.register = self.stack.pop();
Ok(())
}
}
pub fn stack_peek(&self, index: usize) -> Option<AbstractValue> {
if index < self.stack.len() {
Some(self.stack[self.stack.len() - 1 - index].clone())
} else {
None
}
}
pub fn stack_len(&self) -> usize {
self.stack.len()
}
pub fn local_exists(&self, i: usize) -> bool {
self.locals.get(&i).is_some()
}
pub fn local_get(&self, i: usize) -> Option<&(AbstractValue, BorrowState)> {
self.locals.get(&i)
}
pub fn local_take(&mut self, i: usize) -> Result<(), VMError> {
if let Some((abstract_value, _)) = self.locals.get(&i) {
self.register = Some(abstract_value.clone());
Ok(())
} else {
Err(VMError::new(format!("Local does not exist at index {}", i)))
}
}
pub fn local_take_borrow(&mut self, i: usize, mutability: Mutability) -> Result<(), VMError> {
if let Some((abstract_value, _)) = self.locals.get(&i) {
let ref_token = match mutability {
Mutability::Mutable => {
SignatureToken::MutableReference(Box::new(abstract_value.token.clone()))
}
Mutability::Immutable => {
SignatureToken::Reference(Box::new(abstract_value.token.clone()))
}
Mutability::Either => {
return Err(VMError::new("Mutability cannot be Either".to_string()))
}
};
self.register = Some(AbstractValue::new_reference(
ref_token,
abstract_value.abilities,
));
Ok(())
} else {
Err(VMError::new(format!("Local does not exist at index {}", i)))
}
}
pub fn local_set(&mut self, i: usize, availability: BorrowState) -> Result<(), VMError> {
if let Some((abstract_value, _)) = self.locals.clone().get(&i) {
self.locals
.insert(i, (abstract_value.clone(), availability));
Ok(())
} else {
Err(VMError::new(format!("Local does not exist at index {}", i)))
}
}
pub fn local_availability_is(
&self,
i: usize,
availability: BorrowState,
) -> Result<bool, VMError> {
if let Some((_, availability1)) = self.locals.get(&i) {
Ok(availability == *availability1)
} else {
Err(VMError::new(format!("Local does not exist at index {}", i)))
}
}
pub fn local_has_ability(&self, i: usize, ability: Ability) -> Result<bool, VMError> {
if let Some((abstract_value, _)) = self.locals.get(&i) {
Ok(abstract_value.abilities.has_ability(ability))
} else {
Err(VMError::new(format!("Local does not exist at index {}", i)))
}
}
pub fn local_insert(
&mut self,
i: usize,
abstract_value: AbstractValue,
availability: BorrowState,
) {
self.locals.insert(i, (abstract_value, availability));
}
pub fn local_place(&mut self, i: usize) -> Result<(), VMError> {
if let Some(abstract_value) = self.register_move() {
self.locals
.insert(i, (abstract_value, BorrowState::Available));
Ok(())
} else {
Err(VMError::new(
"Could not insert local, register is empty".to_string(),
))
}
}
pub fn get_locals(&self) -> &HashMap<usize, (AbstractValue, BorrowState)> {
&self.locals
}
pub fn abort(&mut self) {
self.aborted = true;
}
pub fn has_aborted(&self) -> bool {
self.aborted
}
pub fn allow_control_flow(&mut self) {
self.control_flow_allowed = true;
}
pub fn is_control_flow_allowed(&self) -> bool {
self.control_flow_allowed
}
pub fn is_final(&self) -> bool {
self.stack.is_empty()
}
}
impl fmt::Display for AbstractState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Stack: {:?} | Locals: {:?} | Instantiation: {:?}",
self.stack, self.locals, self.instantiation
)
}
}
impl Default for AbstractState {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for AbstractValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:?}: {:?})", self.token, self.abilities)
}
}