-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathinterpreter.v
1182 lines (1063 loc) · 40 KB
/
interpreter.v
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
Require Import CoqOfRust.CoqOfRust.
Require Import CoqOfRust.simulations.M.
Require Import CoqOfRust.lib.lib.
Import simulations.M.Notations.
Require Import CoqOfRust.move_sui.simulations.move_binary_format.errors.
Require Import CoqOfRust.move_sui.simulations.move_binary_format.file_format_index.
Require Import CoqOfRust.move_sui.simulations.move_binary_format.file_format.
Require Import CoqOfRust.move_sui.simulations.move_core_types.vm_status.
Require Import CoqOfRust.move_sui.simulations.move_vm_config.runtime.
Require Import CoqOfRust.move_sui.simulations.move_vm_runtime.loader.
Require Import CoqOfRust.move_sui.simulations.move_vm_types.values.values_impl.
(* TODO(progress):
- Investigate `unpack`
- Implement functions in `Resolver`
- Implement `Reference`
- (MUTUAL DEPENDENCY)Implement `StructRef::borrow_field`
- Implement `Interpreter::binop_int`
- Investigate `IntegerValue`'s operations
- Resolve mutual dependency issue for `Container`s
*)
(* NOTE: In the future when lens are more frequently defined, we might want to stub the lens into
corresponded types where only smallstate or the opposite is the exact type *)
(* NOTE(STUB): only implement if necessary *)
Module _Type.
Parameter t : Set.
End _Type.
(* **************** *)
(* NOTE: This trait doesn't have a complete implementation throughout the library. We might be able to just ignore its occurence
/// Trait that defines a generic gas meter interface, allowing clients of the Move VM to implement
/// their own metering scheme.
pub trait GasMeter {
/// Charge an instruction and fail if not enough gas units are left.
fn charge_simple_instr(&mut self, instr: SimpleInstruction) -> PartialVMResult<()>;
fn charge_pop(&mut self, popped_val: impl ValueView) -> PartialVMResult<()>;
fn charge_call(
&mut self,
module_id: &ModuleId,
func_name: &str,
args: impl ExactSizeIterator<Item = impl ValueView>,
num_locals: NumArgs,
) -> PartialVMResult<()>;
fn charge_call_generic(
&mut self,
module_id: &ModuleId,
func_name: &str,
ty_args: impl ExactSizeIterator<Item = impl TypeView>,
args: impl ExactSizeIterator<Item = impl ValueView>,
num_locals: NumArgs,
) -> PartialVMResult<()>;
fn charge_ld_const(&mut self, size: NumBytes) -> PartialVMResult<()>;
fn charge_ld_const_after_deserialization(&mut self, val: impl ValueView)
-> PartialVMResult<()>;
fn charge_copy_loc(&mut self, val: impl ValueView) -> PartialVMResult<()>;
fn charge_move_loc(&mut self, val: impl ValueView) -> PartialVMResult<()>;
fn charge_store_loc(&mut self, val: impl ValueView) -> PartialVMResult<()>;
fn charge_pack(
&mut self,
is_generic: bool,
args: impl ExactSizeIterator<Item = impl ValueView>,
) -> PartialVMResult<()>;
fn charge_unpack(
&mut self,
is_generic: bool,
args: impl ExactSizeIterator<Item = impl ValueView>,
) -> PartialVMResult<()>;
fn charge_read_ref(&mut self, val: impl ValueView) -> PartialVMResult<()>;
fn charge_write_ref(
&mut self,
new_val: impl ValueView,
old_val: impl ValueView,
) -> PartialVMResult<()>;
fn charge_eq(&mut self, lhs: impl ValueView, rhs: impl ValueView) -> PartialVMResult<()>;
fn charge_neq(&mut self, lhs: impl ValueView, rhs: impl ValueView) -> PartialVMResult<()>;
fn charge_vec_pack<'a>(
&mut self,
ty: impl TypeView + 'a,
args: impl ExactSizeIterator<Item = impl ValueView>,
) -> PartialVMResult<()>;
fn charge_vec_len(&mut self, ty: impl TypeView) -> PartialVMResult<()>;
fn charge_vec_borrow(
&mut self,
is_mut: bool,
ty: impl TypeView,
is_success: bool,
) -> PartialVMResult<()>;
fn charge_vec_push_back(
&mut self,
ty: impl TypeView,
val: impl ValueView,
) -> PartialVMResult<()>;
fn charge_vec_pop_back(
&mut self,
ty: impl TypeView,
val: Option<impl ValueView>,
) -> PartialVMResult<()>;
// TODO(Gas): Expose the elements
fn charge_vec_unpack(
&mut self,
ty: impl TypeView,
expect_num_elements: NumArgs,
elems: impl ExactSizeIterator<Item = impl ValueView>,
) -> PartialVMResult<()>;
// TODO(Gas): Expose the two elements
fn charge_vec_swap(&mut self, ty: impl TypeView) -> PartialVMResult<()>;
fn charge_native_function(
&mut self,
amount: InternalGas,
ret_vals: Option<impl ExactSizeIterator<Item = impl ValueView>>,
) -> PartialVMResult<()>;
fn charge_native_function_before_execution(
&mut self,
ty_args: impl ExactSizeIterator<Item = impl TypeView>,
args: impl ExactSizeIterator<Item = impl ValueView>,
) -> PartialVMResult<()>;
fn charge_drop_frame(
&mut self,
locals: impl Iterator<Item = impl ValueView>,
) -> PartialVMResult<()>;
/// Returns the gas left
fn remaining_gas(&self) -> InternalGas;
fn get_profiler_mut(&mut self) -> Option<&mut GasProfiler>;
fn set_profiler(&mut self, profiler: GasProfiler);
}
*)
(*
enum ExitCode {
Return,
Call(FunctionHandleIndex),
CallGeneric(FunctionInstantiationIndex),
}
*)
Module ExitCode.
Inductive t : Set :=
| Return
| Call : FunctionHandleIndex.t -> t
| CallGeneric : FunctionInstantiationIndex.t -> t
.
End ExitCode.
(*
enum InstrRet {
Ok,
ExitCode(ExitCode),
Branch,
}
*)
Module InstrRet.
Inductive t : Set :=
| Ok
| ExitCode : ExitCode.t -> t
| Branch
.
End InstrRet.
(* // TODO Determine stack size limits based on gas limit
const OPERAND_STACK_SIZE_LIMIT: usize = 1024;
const CALL_STACK_SIZE_LIMIT: usize = 1024; *)
Definition OPERAND_STACK_SIZE_LIMIT : Z := 1024.
Definition CALL_STACK_SIZE_LIMIT : Z := 1024.
(* /// The operand stack.
struct Stack {
value: Vec<Value>,
} *)
Module Stack.
Record t := { value : list Value.t }.
(*
impl Stack {
fn last_n(&self, n: usize) -> PartialVMResult<impl ExactSizeIterator<Item = &Value>> {
if self.value.len() < n {
return Err(PartialVMError::new(StatusCode::EMPTY_VALUE_STACK)
.with_message("Failed to get last n arguments on the argument stack".to_string()));
}
Ok(self.value[(self.value.len() - n)..].iter())
}
}
*)
Module Impl_Stack.
Definition Self : Set := move_sui.simulations.move_vm_runtime.interpreter.Stack.t.
(*
/// Create a new empty operand stack.
fn new() -> Self {
Stack { value: vec![] }
}
*)
Definition new : Self := Build_t [].
(*
/// Push a `Value` on the stack if the max stack size has not been reached. Abort execution
/// otherwise.
fn push(&mut self, value: Value) -> PartialVMResult<()> {
if self.value.len() < OPERAND_STACK_SIZE_LIMIT {
self.value.push(value);
Ok(())
} else {
Err(PartialVMError::new(StatusCode::EXECUTION_STACK_OVERFLOW))
}
}
*)
Definition push (value : Value.t) : MS! Self (PartialVMResult.t unit) :=
letS! self := readS! in
let '(Build_t self_value) := self in
if (Z.of_nat $ List.length self_value) <? OPERAND_STACK_SIZE_LIMIT
then
(* We push at the end of the list *)
letS! _ := writeS! $ self <| Stack.value := List.app self_value [value] |> in
returnS! $ Result.Ok tt
else returnS! $ Result.Err $
PartialVMError.new StatusCode.EXECUTION_STACK_OVERFLOW.
(*
/// Pop a `Value` off the stack or abort execution if the stack is empty.
fn pop(&mut self) -> PartialVMResult<Value> {
self.value
.pop()
.ok_or_else(|| PartialVMError::new(StatusCode::EMPTY_VALUE_STACK))
}
*)
Definition pop : MS! Self (PartialVMResult.t Value.t) :=
letS! self := readS! in
(* We check manually if we can pop an element *)
let '(Build_t self_value) := self in
let self_value := List.rev self_value in
match self_value with
| x :: xs =>
let self_value := List.rev xs in
letS! _ := writeS! self <| Stack.value := self_value |> in
returnS! $ Result.Ok x
| _ => returnS! $ Result.Err $
PartialVMError.new StatusCode.EMPTY_VALUE_STACK
end.
(*
/// Pop a `Value` of a given type off the stack. Abort if the value is not of the given
/// type or if the stack is empty.
fn pop_as<T>(&mut self) -> PartialVMResult<T>
where
Value: VMValueCast<T>,
{
self.pop()?.value_as()
}
*)
Definition pop_as (result_type : Set)
`{!VMValueCast.Trait Value.t result_type}
: MS! Self (PartialVMResult.t result_type) :=
letS!? v := pop in
returnS! $ (VMValueCast.cast v).
(*
/// Pop n values off the stack.
fn popn(&mut self, n: u16) -> PartialVMResult<Vec<Value>> {
let remaining_stack_size = self
.value
.len()
.checked_sub(n as usize)
.ok_or_else(|| PartialVMError::new(StatusCode::EMPTY_VALUE_STACK))?;
let args = self.value.split_off(remaining_stack_size);
Ok(args)
}
*)
Definition pop_n : MS! Self (PartialVMResult.t (list Value.t)). Admitted.
End Impl_Stack.
End Stack.
(*
/// `Interpreter` instances can execute Move functions.
///
/// An `Interpreter` instance is a stand alone execution context for a function.
/// It mimics execution on a single thread, with an call stack and an operand stack.
pub(crate) struct Interpreter {
/// Operand stack, where Move `Value`s are stored for stack operations.
operand_stack: Stack,
/// The stack of active functions.
call_stack: CallStack,
/// Limits imposed at runtime
runtime_limits_config: VMRuntimeLimitsConfig,
}
*)
Module Interpreter.
Record t : Set := {
operand_stack : Stack.t;
(* call_stack : CallStack.t; *)
(* runtime_limits_config : VMRuntimeLimitsConfig.t; *)
}.
Module Lens.
Definition lens_state_self : Lens.t (Z * Locals.t * t) t :={|
Lens.read state := let '(_, _, self) := state in self;
Lens.write state self := let '(a, b, _) := state in (a, b, self);
|}.
Definition lens_self_stack : Lens.t t Stack.t := {|
Lens.read self := self.(operand_stack);
Lens.write self stack := self <| Interpreter.operand_stack := stack |>;
|}.
End Lens.
(*
/// Perform a binary operation to two values at the top of the stack.
fn binop<F, T>(&mut self, f: F) -> PartialVMResult<()>
where
Value: VMValueCast<T>,
F: FnOnce(T, T) -> PartialVMResult<Value>,
{
let rhs = self.operand_stack.pop_as::<T>()?;
let lhs = self.operand_stack.pop_as::<T>()?;
let result = f(lhs, rhs)?;
self.operand_stack.push(result)
}
*)
Definition binop {T : Set} `{VMValueCast.Trait Value.t T}
(f : T -> T -> PartialVMResult.t Value.t) :
MS! t (PartialVMResult.t unit) :=
letS!? lhs := liftS! Lens.lens_self_stack $ Stack.Impl_Stack.pop_as T in
letS!? rhs := liftS! Lens.lens_self_stack $ Stack.Impl_Stack.pop_as T in
letS!? result := returnS! $ f lhs rhs in
liftS! Lens.lens_self_stack $ Stack.Impl_Stack.push result.
(*
/// Perform a binary operation for integer values.
fn binop_int<F>(&mut self, f: F) -> PartialVMResult<()>
where
F: FnOnce(IntegerValue, IntegerValue) -> PartialVMResult<IntegerValue>,
{
self.binop(|lhs, rhs| {
Ok(match f(lhs, rhs)? {
IntegerValue::U8(x) => Value::u8(x),
IntegerValue::U16(x) => Value::u16(x),
IntegerValue::U32(x) => Value::u32(x),
IntegerValue::U64(x) => Value::u64(x),
IntegerValue::U128(x) => Value::u128(x),
IntegerValue::U256(x) => Value::u256(x),
})
})
}
*)
Definition binop_int (f : IntegerValue.t -> IntegerValue.t -> PartialVMResult.t IntegerValue.t) :
MS! t (PartialVMResult.t unit) :=
binop (fun lhs rhs =>
let? result := f lhs rhs in
match result with
| IntegerValue.U8 x => return? $ ValueImpl.U8 x
| IntegerValue.U16 x => return? $ ValueImpl.U16 x
| IntegerValue.U32 x => return? $ ValueImpl.U32 x
| IntegerValue.U64 x => return? $ ValueImpl.U64 x
| IntegerValue.U128 x => return? $ ValueImpl.U128 x
| IntegerValue.U256 x => return? $ ValueImpl.U256 x
end
).
End Interpreter.
(*
struct Frame {
pc: u16,
locals: Locals,
function: Arc<Function>,
ty_args: Vec<Type>,
}
*)
Module Frame.
Record t : Set := {
pc : Z;
locals : Locals.t;
function : Function.t;
ty_args : list _Type.t;
}.
End Frame.
(*
fn execute_instruction(
pc: &mut u16,
locals: &mut Locals,
ty_args: &[Type],
function: &Arc<Function>,
resolver: &Resolver,
interpreter: &mut Interpreter,
gas_meter: &mut impl GasMeter,
instruction: &Bytecode,
) -> PartialVMResult<InstrRet> {
use SimpleInstruction as S;
match instruction {
Bytecode::Shl => {
gas_meter.charge_simple_instr(S::Shl)?;
let rhs = interpreter.operand_stack.pop_as::<u8>()?;
let lhs = interpreter.operand_stack.pop_as::<IntegerValue>()?;
interpreter
.operand_stack
.push(lhs.shl_checked(rhs)?.into_value())?;
}
Bytecode::Shr => {
gas_meter.charge_simple_instr(S::Shr)?;
let rhs = interpreter.operand_stack.pop_as::<u8>()?;
let lhs = interpreter.operand_stack.pop_as::<IntegerValue>()?;
interpreter
.operand_stack
.push(lhs.shr_checked(rhs)?.into_value())?;
}
Bytecode::Or => {
gas_meter.charge_simple_instr(S::Or)?;
interpreter.binop_bool(|l, r| Ok(l || r))?
}
Bytecode::And => {
gas_meter.charge_simple_instr(S::And)?;
interpreter.binop_bool(|l, r| Ok(l && r))?
}
Bytecode::Lt => {
gas_meter.charge_simple_instr(S::Lt)?;
interpreter.binop_bool(IntegerValue::lt)?
}
Bytecode::Gt => {
gas_meter.charge_simple_instr(S::Gt)?;
interpreter.binop_bool(IntegerValue::gt)?
}
Bytecode::Le => {
gas_meter.charge_simple_instr(S::Le)?;
interpreter.binop_bool(IntegerValue::le)?
}
Bytecode::Ge => {
gas_meter.charge_simple_instr(S::Ge)?;
interpreter.binop_bool(IntegerValue::ge)?
}
Bytecode::Abort => {
gas_meter.charge_simple_instr(S::Abort)?;
let error_code = interpreter.operand_stack.pop_as::<u64>()?;
let error = PartialVMError::new(StatusCode::ABORTED)
.with_sub_status(error_code)
.with_message(format!("{} at offset {}", function.pretty_string(), *pc,));
return Err(error);
}
Bytecode::Eq => {
let lhs = interpreter.operand_stack.pop()?;
let rhs = interpreter.operand_stack.pop()?;
gas_meter.charge_eq(&lhs, &rhs)?;
interpreter
.operand_stack
.push(Value::bool(lhs.equals(&rhs)?))?;
}
Bytecode::Neq => {
let lhs = interpreter.operand_stack.pop()?;
let rhs = interpreter.operand_stack.pop()?;
gas_meter.charge_neq(&lhs, &rhs)?;
interpreter
.operand_stack
.push(Value::bool(!lhs.equals(&rhs)?))?;
}
Bytecode::MutBorrowGlobalDeprecated(_)
| Bytecode::ImmBorrowGlobalDeprecated(_)
| Bytecode::MutBorrowGlobalGenericDeprecated(_)
| Bytecode::ImmBorrowGlobalGenericDeprecated(_)
| Bytecode::ExistsDeprecated(_)
| Bytecode::ExistsGenericDeprecated(_)
| Bytecode::MoveFromDeprecated(_)
| Bytecode::MoveFromGenericDeprecated(_)
| Bytecode::MoveToDeprecated(_)
| Bytecode::MoveToGenericDeprecated(_) => {
unreachable!("Global bytecodes deprecated")
}
Bytecode::FreezeRef => {
gas_meter.charge_simple_instr(S::FreezeRef)?;
// FreezeRef should just be a null op as we don't distinguish between mut
// and immut ref at runtime.
}
Bytecode::Not => {
gas_meter.charge_simple_instr(S::Not)?;
let value = !interpreter.operand_stack.pop_as::<bool>()?;
interpreter.operand_stack.push(Value::bool(value))?;
}
Bytecode::Nop => {
gas_meter.charge_simple_instr(S::Nop)?;
}
Bytecode::VecPack(si, num) => {
let ty = resolver.instantiate_single_type(*si, ty_args)?; //*)
Self::check_depth_of_type(resolver, &ty)?;
gas_meter.charge_vec_pack(
make_ty!(&ty),
interpreter.operand_stack.last_n(*num as usize)?, //*)
)?;
let elements = interpreter.operand_stack.popn(*num as u16)?; //*)
let value = Vector::pack(&ty, elements)?;
interpreter.operand_stack.push(value)?;
}
Bytecode::VecLen(si) => {
let vec_ref = interpreter.operand_stack.pop_as::<VectorRef>()?;
let ty = &resolver.instantiate_single_type(*si, ty_args)?; //*)
gas_meter.charge_vec_len(TypeWithLoader {
ty,
loader: resolver.loader(),
})?;
let value = vec_ref.len(ty)?;
interpreter.operand_stack.push(value)?;
}
Bytecode::VecImmBorrow(si) => {
let idx = interpreter.operand_stack.pop_as::<u64>()? as usize;
let vec_ref = interpreter.operand_stack.pop_as::<VectorRef>()?;
let ty = resolver.instantiate_single_type(*si, ty_args)?; //*)
let res = vec_ref.borrow_elem(idx, &ty);
gas_meter.charge_vec_borrow(false, make_ty!(&ty), res.is_ok())?;
interpreter.operand_stack.push(res?)?;
}
Bytecode::VecMutBorrow(si) => {
let idx = interpreter.operand_stack.pop_as::<u64>()? as usize;
let vec_ref = interpreter.operand_stack.pop_as::<VectorRef>()?;
let ty = &resolver.instantiate_single_type(*si, ty_args)?; //*)
let res = vec_ref.borrow_elem(idx, ty);
gas_meter.charge_vec_borrow(true, make_ty!(ty), res.is_ok())?;
interpreter.operand_stack.push(res?)?;
}
Bytecode::VecPushBack(si) => {
let elem = interpreter.operand_stack.pop()?;
let vec_ref = interpreter.operand_stack.pop_as::<VectorRef>()?;
let ty = &resolver.instantiate_single_type(*si, ty_args)?; //*)
gas_meter.charge_vec_push_back(make_ty!(ty), &elem)?;
vec_ref.push_back(elem, ty, interpreter.runtime_limits_config().vector_len_max)?;
}
Bytecode::VecPopBack(si) => {
let vec_ref = interpreter.operand_stack.pop_as::<VectorRef>()?;
let ty = &resolver.instantiate_single_type(*si, ty_args)?; //*)
let res = vec_ref.pop(ty);
gas_meter.charge_vec_pop_back(make_ty!(ty), res.as_ref().ok())?;
interpreter.operand_stack.push(res?)?;
}
Bytecode::VecUnpack(si, num) => {
let vec_val = interpreter.operand_stack.pop_as::<Vector>()?;
let ty = &resolver.instantiate_single_type(*si, ty_args)?; //*)
gas_meter.charge_vec_unpack(
make_ty!(ty),
NumArgs::new(*num), //*)
vec_val.elem_views(),
)?;
let elements = vec_val.unpack(ty, *num)?;
for value in elements {
interpreter.operand_stack.push(value)?;
}
}
Bytecode::VecSwap(si) => {
let idx2 = interpreter.operand_stack.pop_as::<u64>()? as usize;
let idx1 = interpreter.operand_stack.pop_as::<u64>()? as usize;
let vec_ref = interpreter.operand_stack.pop_as::<VectorRef>()?;
let ty = &resolver.instantiate_single_type(*si, ty_args)?; //*)
gas_meter.charge_vec_swap(make_ty!(ty))?;
vec_ref.swap(idx1, idx2, ty)?;
}
}
Ok(InstrRet::Ok)
}
*)
Definition lens_state_locals : Lens.t (Z * Locals.t * Interpreter.t) Locals.t := {|
Lens.read state := let '(_, locals, _) := state in locals;
Lens.write state locals := let '(pc, _, intr) := state in (pc, locals, intr);
|}.
Definition lens_state_store_loc_state (v : Value.t)
: Lens.t (Z * Locals.t * Interpreter.t) (Locals.t * Value.t) := {|
Lens.read state := let '(_, locals, _) := state in (locals, v);
Lens.write state '(locals, v) := let '(pc, _, intr) := state in (pc, locals, intr);
|}.
(* NOTE: State designed for `execute_instruction` *)
Definition State := (Z * Locals.t * Interpreter.t).
(* NOTE: This function is for debugging purpose *)
Definition debug_execute_instruction (pc : Z)
(locals : Locals.t) (ty_args : list _Type.t)
(function : Function.t) (resolver : Resolver.t)
(interpreter : Interpreter.t) (* (gas_meter : GasMeter.t) *) (* NOTE: We ignore gas since it's never implemented *)
(instruction : Bytecode.t)
: MS! State (PartialVMResult.t InstrRet.t) :=
letS! (pc, locals, interpreter) := readS! in
match instruction with
(* fill debugging content here *)
| Bytecode.ImmBorrowField fh_idx =>
letS!? reference := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.pop_as StructRef.t) in
let offset := Resolver.Impl_Resolver.field_offset resolver in
(* TODO: Implement `borrow_field` *)
returnS! $ Result.Ok InstrRet.Ok
| _ => returnS! $ Result.Ok InstrRet.Ok
end.
(* NOTE: this function is of `impl Frame` (but doesn't involve `Frame` item?) *)
Definition execute_instruction (pc : Z)
(locals : Locals.t) (ty_args : list _Type.t)
(function : Function.t) (resolver : Resolver.t)
(interpreter : Interpreter.t) (* (gas_meter : GasMeter.t) *) (* NOTE: We ignore gas since it's never implemented *)
(instruction : Bytecode.t)
: MS! State (PartialVMResult.t InstrRet.t) :=
letS! (pc, locals, interpreter) := readS! in
(* NOTE: We ignore the macro since it' only used for charging gas
macro_rules! make_ty {
($ty: expr) => {
TypeWithLoader {
ty: $ty,
loader: resolver.loader(),
}
};
}
*)
match instruction with
(*
Bytecode::Pop => {
let popped_val = interpreter.operand_stack.pop()?;
gas_meter.charge_pop(popped_val)?;
}
*)
| Bytecode.Pop =>
letS!? popped_val := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack Stack.Impl_Stack.pop) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::Ret => {
gas_meter.charge_simple_instr(S::Ret)?;
return Ok(InstrRet::ExitCode(ExitCode::Return));
}
*)
| Bytecode.Ret => returnS! $ Result.Ok $ InstrRet.ExitCode ExitCode.Return
(*
Bytecode::BrTrue(offset) => {
gas_meter.charge_simple_instr(S::BrTrue)?;
if interpreter.operand_stack.pop_as::<bool>()? {
*pc = *offset;
return Ok(InstrRet::Branch);
}
}
*)
| Bytecode.BrTrue offset =>
letS!? popped_val := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.pop_as bool) in
letS! _ := writeS! (offset, locals, interpreter) in
returnS! $ Result.Ok InstrRet.Branch
(*
Bytecode::BrFalse(offset) => {
gas_meter.charge_simple_instr(S::BrFalse)?;
if !interpreter.operand_stack.pop_as::<bool>()? {
*pc = *offset;
return Ok(InstrRet::Branch);
}
}
*)
| Bytecode.BrFalse offset =>
letS!? popped_val := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.pop_as bool) in
letS! _ := writeS! (offset, locals, interpreter) in
returnS! $ Result.Ok InstrRet.Branch
(*
Bytecode::Branch(offset) => {
gas_meter.charge_simple_instr(S::Branch)?;
*pc = *offset;
return Ok(InstrRet::Branch);
}
*)
| Bytecode.Branch offset =>
letS! _ := writeS! (offset, locals, interpreter) in
returnS! $ Result.Ok InstrRet.Branch
(*
Bytecode::LdU8(int_const) => {
gas_meter.charge_simple_instr(S::LdU8)?;
interpreter.operand_stack.push(Value::u8(*int_const))?; //*)
}
*)
| Bytecode.LdU8 int_const =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.U8 int_const) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdU16(int_const) => {
gas_meter.charge_simple_instr(S::LdU16)?;
interpreter.operand_stack.push(Value::u16(*int_const))?; //*)
}
*)
| Bytecode.LdU16 int_const =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.U16 int_const) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdU32(int_const) => {
gas_meter.charge_simple_instr(S::LdU32)?;
interpreter.operand_stack.push(Value::u32(*int_const))?; //*)
}
*)
| Bytecode.LdU32 int_const =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.U32 int_const) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdU64(int_const) => {
gas_meter.charge_simple_instr(S::LdU64)?;
interpreter.operand_stack.push(Value::u64(*int_const))?; //*)
}
*)
| Bytecode.LdU64 int_const =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.U64 int_const) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdU128(int_const) => {
gas_meter.charge_simple_instr(S::LdU128)?;
interpreter.operand_stack.push(Value::u128(**int_const))?; //*)
}
*)
| Bytecode.LdU128 int_const =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.U128 int_const) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdU256(int_const) => {
gas_meter.charge_simple_instr(S::LdU256)?;
interpreter.operand_stack.push(Value::u256(**int_const))?; //*)
}
*)
| Bytecode.LdU256 int_const =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.U256 int_const) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdConst(idx) => {
let constant = resolver.constant_at(*idx); //*)
gas_meter.charge_ld_const(NumBytes::new(constant.data.len() as u64))?;
let val = Value::deserialize_constant(constant).ok_or_else(|| {
PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION).with_message(
"Verifier failed to verify the deserialization of constants".to_owned(),
)
})?;
gas_meter.charge_ld_const_after_deserialization(&val)?;
interpreter.operand_stack.push(val)?
}
*)
(* NOTE: paused from investigation *)
| Bytecode.LdConst idx => returnS! $ Result.Ok InstrRet.Ok
(* let constant := Resolver.Impl_Resolver.constant_at resolver idx in
(* TODO:
- resolve mutual dependency issue
- figure out the logic to load a constant *)
let val := Value.Impl_Value.deserialize_constant constant in
let val := match val with
| Some v => v
| None => PartialVMError.new StatusCode.VERIFIER_INVARIANT_VIOLATION
end in
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push val) in
returnS! $ Result.Ok InstrRet.Ok *)
(*
Bytecode::LdTrue => {
gas_meter.charge_simple_instr(S::LdTrue)?;
interpreter.operand_stack.push(Value::bool(true))?;
}
*)
| Bytecode.LdTrue =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.Bool true) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::LdFalse => {
gas_meter.charge_simple_instr(S::LdFalse)?;
interpreter.operand_stack.push(Value::bool(false))?;
}
*)
| Bytecode.LdFalse =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push $ ValueImpl.Bool false) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::CopyLoc(idx) => {
// TODO(Gas): We should charge gas before copying the value.
let local = locals.copy_loc(*idx as usize)?; //*)
gas_meter.charge_copy_loc(&local)?;
interpreter.operand_stack.push(local)?;
}
*)
| Bytecode.CopyLoc idx =>
let local := Locals.Impl_Locals.copy_loc locals idx in
match local with
| Result.Err e => returnS! $ Result.Err e
| Result.Ok local =>
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push local) in
returnS! $ Result.Ok InstrRet.Ok
end
(*
Bytecode::MoveLoc(idx) => {
let local = locals.move_loc(
*idx as usize,
resolver
.loader()
.vm_config()
.enable_invariant_violation_check_in_swap_loc,
)?;
gas_meter.charge_move_loc(&local)?;
interpreter.operand_stack.push(local)?;
}
*)
| Bytecode.MoveLoc idx =>
let config := resolver.(Resolver.loader).(Loader.vm_config)
.(VMConfig.enable_invariant_violation_check_in_swap_loc) in
letS!? local := liftS! lens_state_locals $ Locals.Impl_Locals.move_loc idx config in
letS!? _ := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.push local) in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::StLoc(idx) => {
let value_to_store = interpreter.operand_stack.pop()?;
gas_meter.charge_store_loc(&value_to_store)?;
locals.store_loc(
*idx as usize,
value_to_store,
resolver
.loader()
.vm_config()
.enable_invariant_violation_check_in_swap_loc,
)?;
}
*)
| Bytecode.StLoc idx =>
letS!? value_to_store := liftS! Interpreter.Lens.lens_state_self (
liftS! Interpreter.Lens.lens_self_stack Stack.Impl_Stack.pop) in
let config := resolver.(Resolver.loader).(Loader.vm_config)
.(VMConfig.enable_invariant_violation_check_in_swap_loc) in
letS!? local := liftS! (lens_state_store_loc_state value_to_store) $ Locals.Impl_Locals.store_loc idx config in
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::Call(idx) => {
return Ok(InstrRet::ExitCode(ExitCode::Call(*idx))); //*)
}
*)
| Bytecode.Call idx => returnS! $ Result.Ok $ InstrRet.ExitCode $ ExitCode.Call idx
(*
Bytecode::CallGeneric(idx) => {
return Ok(InstrRet::ExitCode(ExitCode::CallGeneric(*idx))); //*)
}
*)
| Bytecode.CallGeneric idx => returnS! $ Result.Ok $ InstrRet.ExitCode $ ExitCode.CallGeneric idx
(* TODO: Finish below *)
(*
Bytecode::MutBorrowLoc(idx) | Bytecode::ImmBorrowLoc(idx) => {
let instr = match instruction {
Bytecode::MutBorrowLoc(_) => S::MutBorrowLoc,
_ => S::ImmBorrowLoc,
};
gas_meter.charge_simple_instr(instr)?;
interpreter
.operand_stack
.push(locals.borrow_loc(*idx as usize)?)?; //*)
}
*)
(* NOTE: paused from investigation: mutual dependency issue for `borrow_loc` *)
| Bytecode.MutBorrowLoc idx => returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::ImmBorrowField(fh_idx) | Bytecode::MutBorrowField(fh_idx) => {
let instr = match instruction {
Bytecode::MutBorrowField(_) => S::MutBorrowField,
_ => S::ImmBorrowField,
};
gas_meter.charge_simple_instr(instr)?;
let reference = interpreter.operand_stack.pop_as::<StructRef>()?;
let offset = resolver.field_offset(*fh_idx); //*)
let field_ref = reference.borrow_field(offset)?;
interpreter.operand_stack.push(field_ref)?;
}
*)
(* NOTE: paused for mutual dependency issue *)
| Bytecode.ImmBorrowField fh_idx =>
letS!? reference := liftS! Interpreter.Lens.lens_state_self (
(* NOTE: Notice that since we identify the instance by the `ValueImpl`
item, here we have to apply the `StructRef` instance indirectly *)
liftS! Interpreter.Lens.lens_self_stack $ Stack.Impl_Stack.pop_as ContainerRef.t) in
(* NOTE: below is a test clause to show that the popped value is indeed `StructRef`
let reference : StructRef.t := reference in
*)
let offset := Resolver.Impl_Resolver.field_offset resolver in
(* TODO: Implement `borrow_field` *)
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::ImmBorrowFieldGeneric(fi_idx) | Bytecode::MutBorrowFieldGeneric(fi_idx) => {
let instr = match instruction {
Bytecode::MutBorrowField(_) => S::MutBorrowFieldGeneric,
_ => S::ImmBorrowFieldGeneric,
};
gas_meter.charge_simple_instr(instr)?;
let reference = interpreter.operand_stack.pop_as::<StructRef>()?;
let offset = resolver.field_instantiation_offset(*fi_idx); //*)
let field_ref = reference.borrow_field(offset)?;
interpreter.operand_stack.push(field_ref)?;
}
*)
(* NOTE: paused for mutual dependency issue *)
| Bytecode.ImmBorrowFieldGeneric fi_idx => returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::Pack(sd_idx) => {
let field_count = resolver.field_count(*sd_idx); //*)
let struct_type = resolver.get_struct_type(*sd_idx); //*)
Self::check_depth_of_type(resolver, &struct_type)?;
gas_meter.charge_pack(
false,
interpreter.operand_stack.last_n(field_count as usize)?,
)?;
let args = interpreter.operand_stack.popn(field_count)?;
interpreter
.operand_stack
.push(Value::struct_(Struct::pack(args)))?;
}
*)
(* NOTE: Should we ignore `check_depth_of_type`? *)
| Bytecode.Pack sd_idx =>
let field_count := Resolver.Impl_Resolver.field_count resolver sd_idx in
(* TODO: Implement pop_n *)
returnS! $ Result.Ok InstrRet.Ok
(*
Bytecode::PackGeneric(si_idx) => {
let field_count = resolver.field_instantiation_count(*si_idx); //*)
let ty = resolver.instantiate_generic_type(*si_idx, ty_args)?; //*)
Self::check_depth_of_type(resolver, &ty)?;
gas_meter.charge_pack(
true,
interpreter.operand_stack.last_n(field_count as usize)?,
)?;
let args = interpreter.operand_stack.popn(field_count)?;
interpreter
.operand_stack
.push(Value::struct_(Struct::pack(args)))?;
}
*)
| Bytecode.PackGeneric si_idx => returnS! $ Result.Ok InstrRet.Ok