forked from lambdaclass/cairo-vm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vm_core.rs
4276 lines (3855 loc) · 138 KB
/
vm_core.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
use crate::stdlib::{any::Any, borrow::Cow, collections::HashMap, prelude::*};
use crate::{
hint_processor::hint_processor_definition::HintProcessor,
types::{
errors::math_errors::MathError,
exec_scope::ExecutionScopes,
instruction::{
is_call_instruction, ApUpdate, FpUpdate, Instruction, Opcode, PcUpdate, Res,
},
relocatable::{MaybeRelocatable, Relocatable},
},
vm::{
context::run_context::RunContext,
decoding::decoder::decode_instruction,
errors::{
exec_scope_errors::ExecScopeError, memory_errors::MemoryError,
vm_errors::VirtualMachineError,
},
runners::builtin_runner::{BuiltinRunner, RangeCheckBuiltinRunner, SignatureBuiltinRunner},
trace::trace_entry::TraceEntry,
vm_memory::memory_segments::MemorySegmentManager,
},
};
use core::cmp::Ordering;
use felt::Felt252;
use num_traits::{ToPrimitive, Zero};
use super::errors::trace_errors::TraceError;
use super::runners::builtin_runner::OUTPUT_BUILTIN_NAME;
const MAX_TRACEBACK_ENTRIES: u32 = 20;
#[derive(PartialEq, Eq, Debug)]
pub struct Operands {
dst: MaybeRelocatable,
res: Option<MaybeRelocatable>,
op0: MaybeRelocatable,
op1: MaybeRelocatable,
}
#[derive(PartialEq, Eq, Debug)]
pub struct OperandsAddresses {
dst_addr: Relocatable,
op0_addr: Relocatable,
op1_addr: Relocatable,
}
#[derive(Default, Debug, Clone, Copy)]
pub struct DeducedOperands(u8);
impl DeducedOperands {
fn set_dst(&mut self, value: bool) {
self.0 |= value as u8;
}
fn set_op0(&mut self, value: bool) {
self.0 |= (value as u8) << 1;
}
fn set_op1(&mut self, value: bool) {
self.0 |= (value as u8) << 2;
}
fn was_dest_deducted(&self) -> bool {
self.0 & 1 != 0
}
fn was_op0_deducted(&self) -> bool {
self.0 & 1 << 1 != 0
}
fn was_op1_deducted(&self) -> bool {
self.0 & 1 << 2 != 0
}
}
pub struct VirtualMachine {
pub(crate) run_context: RunContext,
pub(crate) builtin_runners: Vec<BuiltinRunner>,
pub(crate) segments: MemorySegmentManager,
pub(crate) trace: Option<Vec<TraceEntry>>,
pub(crate) current_step: usize,
pub(crate) rc_limits: Option<(isize, isize)>,
trace_relocated: bool,
skip_instruction_execution: bool,
run_finished: bool,
instruction_cache: Vec<Option<Instruction>>,
#[cfg(feature = "hooks")]
pub(crate) hooks: crate::vm::hooks::Hooks,
}
impl VirtualMachine {
pub fn new(trace_enabled: bool) -> VirtualMachine {
let run_context = RunContext {
pc: Relocatable::from((0, 0)),
ap: 0,
fp: 0,
};
let trace = if trace_enabled {
Some(Vec::<TraceEntry>::new())
} else {
None
};
VirtualMachine {
run_context,
builtin_runners: Vec::new(),
trace,
current_step: 0,
skip_instruction_execution: false,
segments: MemorySegmentManager::new(),
rc_limits: None,
run_finished: false,
trace_relocated: false,
instruction_cache: Vec::new(),
#[cfg(feature = "hooks")]
hooks: Default::default(),
}
}
pub fn compute_segments_effective_sizes(&mut self) {
self.segments.compute_effective_sizes();
}
fn update_fp(
&mut self,
instruction: &Instruction,
operands: &Operands,
) -> Result<(), VirtualMachineError> {
let new_fp_offset: usize = match instruction.fp_update {
FpUpdate::APPlus2 => self.run_context.ap + 2,
FpUpdate::Dst => match operands.dst {
MaybeRelocatable::RelocatableValue(ref rel) => rel.offset,
MaybeRelocatable::Int(ref num) => num
.to_usize()
.ok_or_else(|| MathError::Felt252ToUsizeConversion(Box::new(num.clone())))?,
},
FpUpdate::Regular => return Ok(()),
};
self.run_context.fp = new_fp_offset;
Ok(())
}
fn update_ap(
&mut self,
instruction: &Instruction,
operands: &Operands,
) -> Result<(), VirtualMachineError> {
let new_apset: usize = match instruction.ap_update {
ApUpdate::Add => match &operands.res {
Some(res) => (self.run_context.get_ap() + res)?.offset,
None => return Err(VirtualMachineError::UnconstrainedResAdd),
},
ApUpdate::Add1 => self.run_context.ap + 1,
ApUpdate::Add2 => self.run_context.ap + 2,
ApUpdate::Regular => return Ok(()),
};
self.run_context.ap = new_apset;
Ok(())
}
fn update_pc(
&mut self,
instruction: &Instruction,
operands: &Operands,
) -> Result<(), VirtualMachineError> {
let new_pc: Relocatable = match instruction.pc_update {
PcUpdate::Regular => (self.run_context.pc + instruction.size())?,
PcUpdate::Jump => match operands.res.as_ref().and_then(|x| x.get_relocatable()) {
Some(ref res) => *res,
None => return Err(VirtualMachineError::UnconstrainedResJump),
},
PcUpdate::JumpRel => match &operands.res {
Some(res) => match res {
MaybeRelocatable::Int(num_res) => (self.run_context.pc + num_res)?,
_ => return Err(VirtualMachineError::JumpRelNotInt),
},
None => return Err(VirtualMachineError::UnconstrainedResJumpRel),
},
PcUpdate::Jnz => match VirtualMachine::is_zero(&operands.dst) {
true => (self.run_context.pc + instruction.size())?,
false => (self.run_context.pc + &operands.op1)?,
},
};
self.run_context.pc = new_pc;
Ok(())
}
fn update_registers(
&mut self,
instruction: &Instruction,
operands: Operands,
) -> Result<(), VirtualMachineError> {
self.update_fp(instruction, &operands)?;
self.update_ap(instruction, &operands)?;
self.update_pc(instruction, &operands)?;
Ok(())
}
/// Returns true if the value is zero
/// Used for JNZ instructions
fn is_zero(addr: &MaybeRelocatable) -> bool {
match addr {
MaybeRelocatable::Int(num) => num.is_zero(),
_ => false,
}
}
///Returns a tuple (deduced_op0, deduced_res).
///Deduces the value of op0 if possible (based on dst and op1). Otherwise, returns None.
///If res was already deduced, returns its deduced value as well.
fn deduce_op0(
&self,
instruction: &Instruction,
dst: Option<&MaybeRelocatable>,
op1: Option<&MaybeRelocatable>,
) -> Result<(Option<MaybeRelocatable>, Option<MaybeRelocatable>), VirtualMachineError> {
match instruction.opcode {
Opcode::Call => Ok((
Some(MaybeRelocatable::from(
(self.run_context.pc + instruction.size())?,
)),
None,
)),
Opcode::AssertEq => match (&instruction.res, dst, op1) {
(Res::Add, Some(dst_addr), Some(op1_addr)) => {
Ok((Some(dst_addr.sub(op1_addr)?), dst.cloned()))
}
(
Res::Mul,
Some(MaybeRelocatable::Int(num_dst)),
Some(MaybeRelocatable::Int(num_op1)),
) if !num_op1.is_zero() => {
Ok((Some(MaybeRelocatable::Int(num_dst / num_op1)), dst.cloned()))
}
_ => Ok((None, None)),
},
_ => Ok((None, None)),
}
}
/// Returns a tuple (deduced_op1, deduced_res).
///Deduces the value of op1 if possible (based on dst and op0). Otherwise, returns None.
///If res was already deduced, returns its deduced value as well.
fn deduce_op1(
&self,
instruction: &Instruction,
dst: Option<&MaybeRelocatable>,
op0: Option<MaybeRelocatable>,
) -> Result<(Option<MaybeRelocatable>, Option<MaybeRelocatable>), VirtualMachineError> {
if let Opcode::AssertEq = instruction.opcode {
match instruction.res {
Res::Op1 => return Ok((dst.cloned(), dst.cloned())),
Res::Add => {
return Ok((
dst.zip(op0).and_then(|(dst, op0)| dst.sub(&op0).ok()),
dst.cloned(),
))
}
Res::Mul => match (dst, op0) {
(
Some(MaybeRelocatable::Int(num_dst)),
Some(MaybeRelocatable::Int(num_op0)),
) if !num_op0.is_zero() => {
return Ok((Some(MaybeRelocatable::Int(num_dst / num_op0)), dst.cloned()))
}
_ => (),
},
_ => (),
};
};
Ok((None, None))
}
fn deduce_memory_cell(
&self,
address: Relocatable,
) -> Result<Option<MaybeRelocatable>, VirtualMachineError> {
for builtin in self.builtin_runners.iter() {
if builtin.base() as isize == address.segment_index {
match builtin.deduce_memory_cell(address, &self.segments.memory) {
Ok(maybe_reloc) => return Ok(maybe_reloc),
Err(error) => return Err(VirtualMachineError::RunnerError(error)),
};
}
}
Ok(None)
}
///Computes the value of res if possible
fn compute_res(
&self,
instruction: &Instruction,
op0: &MaybeRelocatable,
op1: &MaybeRelocatable,
) -> Result<Option<MaybeRelocatable>, VirtualMachineError> {
match instruction.res {
Res::Op1 => Ok(Some(op1.clone())),
Res::Add => Ok(Some(op0.add(op1)?)),
Res::Mul => {
if let (MaybeRelocatable::Int(num_op0), MaybeRelocatable::Int(num_op1)) = (op0, op1)
{
return Ok(Some(MaybeRelocatable::Int(num_op0 * num_op1)));
}
Err(VirtualMachineError::ComputeResRelocatableMul(Box::new((
op0.clone(),
op1.clone(),
))))
}
Res::Unconstrained => Ok(None),
}
}
fn deduce_dst(
&self,
instruction: &Instruction,
res: Option<&MaybeRelocatable>,
) -> Option<MaybeRelocatable> {
match instruction.opcode {
Opcode::AssertEq => res.cloned(),
Opcode::Call => Some(self.get_fp().into()),
_ => None,
}
}
fn opcode_assertions(
&self,
instruction: &Instruction,
operands: &Operands,
) -> Result<(), VirtualMachineError> {
match instruction.opcode {
Opcode::AssertEq => match &operands.res {
None => Err(VirtualMachineError::UnconstrainedResAssertEq),
Some(res) if res != &operands.dst => Err(VirtualMachineError::DiffAssertValues(
Box::new((operands.dst.clone(), res.clone())),
)),
_ => Ok(()),
},
Opcode::Call => {
let return_pc = MaybeRelocatable::from((self.run_context.pc + instruction.size())?);
if operands.op0 != return_pc {
return Err(VirtualMachineError::CantWriteReturnPc(Box::new((
operands.op0.clone(),
return_pc,
))));
};
if MaybeRelocatable::from(self.run_context.get_fp()) != operands.dst {
return Err(VirtualMachineError::CantWriteReturnFp(Box::new((
operands.dst.clone(),
MaybeRelocatable::from(self.run_context.get_fp()),
))));
};
Ok(())
}
_ => Ok(()),
}
}
fn insert_deduced_operands(
&mut self,
deduced_operands: DeducedOperands,
operands: &Operands,
operands_addresses: &OperandsAddresses,
) -> Result<(), VirtualMachineError> {
if deduced_operands.was_op0_deducted() {
self.segments
.memory
.insert(operands_addresses.op0_addr, &operands.op0)
.map_err(VirtualMachineError::Memory)?;
}
if deduced_operands.was_op1_deducted() {
self.segments
.memory
.insert(operands_addresses.op1_addr, &operands.op1)
.map_err(VirtualMachineError::Memory)?;
}
if deduced_operands.was_dest_deducted() {
self.segments
.memory
.insert(operands_addresses.dst_addr, &operands.dst)
.map_err(VirtualMachineError::Memory)?;
}
Ok(())
}
fn run_instruction(&mut self, instruction: &Instruction) -> Result<(), VirtualMachineError> {
let (operands, operands_addresses, deduced_operands) =
self.compute_operands(instruction)?;
self.insert_deduced_operands(deduced_operands, &operands, &operands_addresses)?;
self.opcode_assertions(instruction, &operands)?;
if let Some(ref mut trace) = &mut self.trace {
trace.push(TraceEntry {
pc: self.run_context.pc.offset,
ap: self.run_context.ap,
fp: self.run_context.fp,
});
}
// Update range check limits
const OFFSET_BITS: u32 = 16;
let (off0, off1, off2) = (
instruction.off0 + (1_isize << (OFFSET_BITS - 1)),
instruction.off1 + (1_isize << (OFFSET_BITS - 1)),
instruction.off2 + (1_isize << (OFFSET_BITS - 1)),
);
self.rc_limits = Some((
[self.rc_limits.unwrap_or((off0, off0)).0, off0, off1, off2]
.into_iter()
.min()
.unwrap(),
[self.rc_limits.unwrap_or((off0, off0)).1, off0, off1, off2]
.into_iter()
.max()
.unwrap(),
));
self.segments
.memory
.mark_as_accessed(operands_addresses.dst_addr);
self.segments
.memory
.mark_as_accessed(operands_addresses.op0_addr);
self.segments
.memory
.mark_as_accessed(operands_addresses.op1_addr);
self.update_registers(instruction, operands)?;
self.current_step += 1;
Ok(())
}
fn decode_current_instruction(&self) -> Result<Instruction, VirtualMachineError> {
let instruction = self
.segments
.memory
.get_integer(self.run_context.pc)?
.to_u64()
.ok_or(VirtualMachineError::InvalidInstructionEncoding)?;
decode_instruction(instruction)
}
pub fn step_hint(
&mut self,
hint_executor: &mut dyn HintProcessor,
exec_scopes: &mut ExecutionScopes,
hint_data_dictionary: &HashMap<usize, Vec<Box<dyn Any>>>,
constants: &HashMap<String, Felt252>,
) -> Result<(), VirtualMachineError> {
if let Some(hint_list) = hint_data_dictionary.get(&self.run_context.pc.offset) {
for (hint_index, hint_data) in hint_list.iter().enumerate() {
hint_executor
.execute_hint(self, exec_scopes, hint_data, constants)
.map_err(|err| VirtualMachineError::Hint(Box::new((hint_index, err))))?
}
}
Ok(())
}
pub fn step_instruction(&mut self) -> Result<(), VirtualMachineError> {
let pc = self.run_context.pc.offset;
if self.segments.memory.data[0].len() <= pc {
return Err(MemoryError::UnknownMemoryCell(Box::new((0, pc).into())))?;
}
let mut inst_cache = core::mem::take(&mut self.instruction_cache);
inst_cache.resize((pc + 1).max(inst_cache.len()), None);
let instruction = inst_cache.get_mut(pc).unwrap();
if instruction.is_none() {
*instruction = Some(self.decode_current_instruction()?);
}
let instruction = instruction.as_ref().unwrap();
if !self.skip_instruction_execution {
self.run_instruction(instruction)?;
} else {
self.run_context.pc += instruction.size();
self.skip_instruction_execution = false;
}
self.instruction_cache = inst_cache;
Ok(())
}
pub fn step(
&mut self,
hint_executor: &mut dyn HintProcessor,
exec_scopes: &mut ExecutionScopes,
hint_data_dictionary: &HashMap<usize, Vec<Box<dyn Any>>>,
constants: &HashMap<String, Felt252>,
) -> Result<(), VirtualMachineError> {
self.step_hint(hint_executor, exec_scopes, hint_data_dictionary, constants)?;
#[cfg(feature = "hooks")]
self.execute_pre_step_instruction(
hint_executor,
exec_scopes,
hint_data_dictionary,
constants,
)?;
self.step_instruction()?;
#[cfg(feature = "hooks")]
self.execute_post_step_instruction(
hint_executor,
exec_scopes,
hint_data_dictionary,
constants,
)?;
Ok(())
}
fn compute_op0_deductions(
&self,
op0_addr: Relocatable,
res: &mut Option<MaybeRelocatable>,
instruction: &Instruction,
dst_op: &Option<MaybeRelocatable>,
op1_op: &Option<MaybeRelocatable>,
) -> Result<MaybeRelocatable, VirtualMachineError> {
let op0_op = match self.deduce_memory_cell(op0_addr)? {
None => {
let op0;
(op0, *res) = self.deduce_op0(instruction, dst_op.as_ref(), op1_op.as_ref())?;
op0
}
deduced_memory_cell => deduced_memory_cell,
};
let op0 = op0_op.ok_or_else(|| {
VirtualMachineError::FailedToComputeOperands(Box::new(("op0".to_string(), op0_addr)))
})?;
Ok(op0)
}
fn compute_op1_deductions(
&self,
op1_addr: Relocatable,
res: &mut Option<MaybeRelocatable>,
instruction: &Instruction,
dst_op: &Option<MaybeRelocatable>,
op0: &MaybeRelocatable,
) -> Result<MaybeRelocatable, VirtualMachineError> {
let op1_op = match self.deduce_memory_cell(op1_addr)? {
None => {
let (op1, deduced_res) =
self.deduce_op1(instruction, dst_op.as_ref(), Some(op0.clone()))?;
if res.is_none() {
*res = deduced_res
}
op1
}
deduced_memory_cell => deduced_memory_cell,
};
let op1 = op1_op.ok_or_else(|| {
VirtualMachineError::FailedToComputeOperands(Box::new(("op1".to_string(), op1_addr)))
})?;
Ok(op1)
}
fn compute_dst_deductions(
&self,
instruction: &Instruction,
res: &Option<MaybeRelocatable>,
) -> Result<MaybeRelocatable, VirtualMachineError> {
let dst_op = match instruction.opcode {
Opcode::AssertEq if res.is_some() => Option::clone(res),
Opcode::Call => Some(MaybeRelocatable::from(self.run_context.get_fp())),
_ => self.deduce_dst(instruction, res.as_ref()),
};
let dst = dst_op.ok_or(VirtualMachineError::NoDst)?;
Ok(dst)
}
/// Compute operands and result, trying to deduce them if normal memory access returns a None
/// value.
pub fn compute_operands(
&self,
instruction: &Instruction,
) -> Result<(Operands, OperandsAddresses, DeducedOperands), VirtualMachineError> {
//Get operands from memory
let dst_addr = self.run_context.compute_dst_addr(instruction)?;
let dst_op = self.segments.memory.get(&dst_addr).map(Cow::into_owned);
let op0_addr = self.run_context.compute_op0_addr(instruction)?;
let op0_op = self.segments.memory.get(&op0_addr).map(Cow::into_owned);
let op1_addr = self
.run_context
.compute_op1_addr(instruction, op0_op.as_ref())?;
let op1_op = self.segments.memory.get(&op1_addr).map(Cow::into_owned);
let mut res: Option<MaybeRelocatable> = None;
let mut deduced_operands = DeducedOperands::default();
//Deduce op0 if it wasnt previously computed
let op0 = match op0_op {
Some(op0) => op0,
None => {
deduced_operands.set_op0(true);
self.compute_op0_deductions(op0_addr, &mut res, instruction, &dst_op, &op1_op)?
}
};
//Deduce op1 if it wasnt previously computed
let op1 = match op1_op {
Some(op1) => op1,
None => {
deduced_operands.set_op1(true);
self.compute_op1_deductions(op1_addr, &mut res, instruction, &dst_op, &op0)?
}
};
//Compute res if it wasnt previously deduced
if res.is_none() {
res = self.compute_res(instruction, &op0, &op1)?;
}
//Deduce dst if it wasnt previously computed
let dst = match dst_op {
Some(dst) => dst,
None => {
deduced_operands.set_dst(true);
self.compute_dst_deductions(instruction, &res)?
}
};
let accessed_addresses = OperandsAddresses {
dst_addr,
op0_addr,
op1_addr,
};
Ok((
Operands { dst, op0, op1, res },
accessed_addresses,
deduced_operands,
))
}
///Makes sure that all assigned memory cells are consistent with their auto deduction rules.
pub fn verify_auto_deductions(&self) -> Result<(), VirtualMachineError> {
for builtin in self.builtin_runners.iter() {
let index: usize = builtin.base();
for (offset, value) in self.segments.memory.data[index].iter().enumerate() {
if let Some(deduced_memory_cell) = builtin
.deduce_memory_cell(
Relocatable::from((index as isize, offset)),
&self.segments.memory,
)
.map_err(VirtualMachineError::RunnerError)?
{
let value = value.as_ref().map(|x| x.get_value());
if Some(&deduced_memory_cell) != value && value.is_some() {
return Err(VirtualMachineError::InconsistentAutoDeduction(Box::new((
builtin.name(),
deduced_memory_cell,
value.cloned(),
))));
}
}
}
}
Ok(())
}
//Makes sure that the value at the given address is consistent with the auto deduction rules.
pub fn verify_auto_deductions_for_addr(
&self,
addr: Relocatable,
builtin: &BuiltinRunner,
) -> Result<(), VirtualMachineError> {
let value = match builtin.deduce_memory_cell(addr, &self.segments.memory)? {
Some(value) => value,
None => return Ok(()),
};
let current_value = match self.segments.memory.get(&addr) {
Some(value) => value.into_owned(),
None => return Ok(()),
};
if value != current_value {
return Err(VirtualMachineError::InconsistentAutoDeduction(Box::new((
builtin.name(),
value,
Some(current_value),
))));
}
Ok(())
}
pub fn end_run(&mut self, exec_scopes: &ExecutionScopes) -> Result<(), VirtualMachineError> {
self.verify_auto_deductions()?;
self.run_finished = true;
match exec_scopes.data.len() {
1 => Ok(()),
_ => Err(ExecScopeError::NoScopeError.into()),
}
}
pub fn mark_address_range_as_accessed(
&mut self,
base: Relocatable,
len: usize,
) -> Result<(), VirtualMachineError> {
if !self.run_finished {
return Err(VirtualMachineError::RunNotFinished);
}
for i in 0..len {
self.segments.memory.mark_as_accessed((base + i)?);
}
Ok(())
}
// Returns the values (fp, pc) corresponding to each call instruction in the traceback.
// Returns the most recent call last.
pub(crate) fn get_traceback_entries(&self) -> Vec<(Relocatable, Relocatable)> {
let mut entries = Vec::<(Relocatable, Relocatable)>::new();
let mut fp = Relocatable::from((1, self.run_context.fp));
// Fetch the fp and pc traceback entries
for _ in 0..MAX_TRACEBACK_ENTRIES {
// Get return pc
let ret_pc = match (fp - 1)
.ok()
.map(|r| self.segments.memory.get_relocatable(r))
{
Some(Ok(opt_pc)) => opt_pc,
_ => break,
};
// Get fp traceback
match (fp - 2)
.ok()
.map(|r| self.segments.memory.get_relocatable(r))
{
Some(Ok(opt_fp)) if opt_fp != fp => fp = opt_fp,
_ => break,
}
// Try to check if the call instruction is (instruction0, instruction1) or just
// instruction1 (with no immediate).
let call_pc = match (ret_pc - 1)
.ok()
.map(|r| self.segments.memory.get_integer(r))
{
Some(Ok(instruction1)) => {
match is_call_instruction(&instruction1) {
true => (ret_pc - 1).unwrap(), // This unwrap wont fail as it is checked before
false => {
match (ret_pc - 2)
.ok()
.map(|r| self.segments.memory.get_integer(r))
{
Some(Ok(instruction0)) => {
match is_call_instruction(&instruction0) {
true => (ret_pc - 2).unwrap(), // This unwrap wont fail as it is checked before
false => break,
}
}
_ => break,
}
}
}
}
_ => break,
};
// Append traceback entries
entries.push((fp, call_pc))
}
entries.reverse();
entries
}
///Adds a new segment and to the memory and returns its starting location as a Relocatable value.
pub fn add_memory_segment(&mut self) -> Relocatable {
self.segments.add()
}
pub fn get_ap(&self) -> Relocatable {
self.run_context.get_ap()
}
pub fn get_fp(&self) -> Relocatable {
self.run_context.get_fp()
}
pub fn get_pc(&self) -> Relocatable {
self.run_context.get_pc()
}
///Gets the integer value corresponding to the Relocatable address
pub fn get_integer(&self, key: Relocatable) -> Result<Cow<Felt252>, MemoryError> {
self.segments.memory.get_integer(key)
}
///Gets the relocatable value corresponding to the Relocatable address
pub fn get_relocatable(&self, key: Relocatable) -> Result<Relocatable, MemoryError> {
self.segments.memory.get_relocatable(key)
}
///Gets a MaybeRelocatable value from memory indicated by a generic address
pub fn get_maybe<'a, 'b: 'a, K: 'a>(&'b self, key: &'a K) -> Option<MaybeRelocatable>
where
Relocatable: TryFrom<&'a K>,
{
self.segments.memory.get(key).map(|x| x.into_owned())
}
/// Returns a reference to the vector with all builtins present in the virtual machine
pub fn get_builtin_runners(&self) -> &Vec<BuiltinRunner> {
&self.builtin_runners
}
/// Returns a mutable reference to the vector with all builtins present in the virtual machine
pub fn get_builtin_runners_as_mut(&mut self) -> &mut Vec<BuiltinRunner> {
&mut self.builtin_runners
}
///Inserts a value into a memory address given by a Relocatable value
pub fn insert_value<T: Into<MaybeRelocatable>>(
&mut self,
key: Relocatable,
val: T,
) -> Result<(), MemoryError> {
self.segments.memory.insert_value(key, val)
}
///Writes data into the memory from address ptr and returns the first address after the data.
pub fn load_data(
&mut self,
ptr: Relocatable,
data: &Vec<MaybeRelocatable>,
) -> Result<Relocatable, MemoryError> {
if ptr.segment_index == 0 {
self.instruction_cache.resize(data.len(), None);
}
self.segments.load_data(ptr, data)
}
/// Writes args into the memory from address ptr and returns the first address after the data.
pub fn write_arg(
&mut self,
ptr: Relocatable,
arg: &dyn Any,
) -> Result<MaybeRelocatable, MemoryError> {
self.segments.write_arg(ptr, arg)
}
pub fn memcmp(&self, lhs: Relocatable, rhs: Relocatable, len: usize) -> (Ordering, usize) {
self.segments.memory.memcmp(lhs, rhs, len)
}
pub fn mem_eq(&self, lhs: Relocatable, rhs: Relocatable, len: usize) -> bool {
self.segments.memory.mem_eq(lhs, rhs, len)
}
///Gets `n_ret` return values from memory
pub fn get_return_values(&self, n_ret: usize) -> Result<Vec<MaybeRelocatable>, MemoryError> {
let addr = (self.run_context.get_ap() - n_ret)
.map_err(|_| MemoryError::FailedToGetReturnValues(Box::new((n_ret, self.get_ap()))))?;
self.segments.memory.get_continuous_range(addr, n_ret)
}
///Gets n elements from memory starting from addr (n being size)
pub fn get_range(&self, addr: Relocatable, size: usize) -> Vec<Option<Cow<MaybeRelocatable>>> {
self.segments.memory.get_range(addr, size)
}
///Gets n elements from memory starting from addr (n being size)
pub fn get_continuous_range(
&self,
addr: Relocatable,
size: usize,
) -> Result<Vec<MaybeRelocatable>, MemoryError> {
self.segments.memory.get_continuous_range(addr, size)
}
///Gets n integer values from memory starting from addr (n being size),
pub fn get_integer_range(
&self,
addr: Relocatable,
size: usize,
) -> Result<Vec<Cow<Felt252>>, MemoryError> {
self.segments.memory.get_integer_range(addr, size)
}
pub fn get_range_check_builtin(&self) -> Result<&RangeCheckBuiltinRunner, VirtualMachineError> {
for builtin in &self.builtin_runners {
if let BuiltinRunner::RangeCheck(range_check_builtin) = builtin {
return Ok(range_check_builtin);
};
}
Err(VirtualMachineError::NoRangeCheckBuiltin)
}
pub fn get_signature_builtin(
&mut self,
) -> Result<&mut SignatureBuiltinRunner, VirtualMachineError> {
for builtin in self.get_builtin_runners_as_mut() {
if let BuiltinRunner::Signature(signature_builtin) = builtin {
return Ok(signature_builtin);
};
}
Err(VirtualMachineError::NoSignatureBuiltin)
}
pub fn disable_trace(&mut self) {
self.trace = None
}
#[doc(hidden)]
pub fn skip_next_instruction_execution(&mut self) {
self.skip_instruction_execution = true;
}
#[doc(hidden)]
pub fn set_ap(&mut self, ap: usize) {
self.run_context.set_ap(ap)
}
#[doc(hidden)]
pub fn set_fp(&mut self, fp: usize) {
self.run_context.set_fp(fp)
}
#[doc(hidden)]
pub fn set_pc(&mut self, pc: Relocatable) {
self.run_context.set_pc(pc)
}
pub fn get_segment_used_size(&self, index: usize) -> Option<usize> {
self.segments.get_segment_used_size(index)
}
pub fn get_segment_size(&self, index: usize) -> Option<usize> {
self.segments.get_segment_size(index)
}
pub fn add_temporary_segment(&mut self) -> Relocatable {
self.segments.add_temporary_segment()
}
/// Add a new relocation rule.
///
/// Will return an error if any of the following conditions are not met:
/// - Source address's segment must be negative (temporary).
/// - Source address's offset must be zero.
/// - There shouldn't already be relocation at the source segment.
pub fn add_relocation_rule(
&mut self,
src_ptr: Relocatable,
dst_ptr: Relocatable,
) -> Result<(), MemoryError> {
self.segments.memory.add_relocation_rule(src_ptr, dst_ptr)
}
pub fn gen_arg(&mut self, arg: &dyn Any) -> Result<MaybeRelocatable, MemoryError> {
self.segments.gen_arg(arg)
}
/// Write the values hosted in the output builtin's segment.
/// Does nothing if the output builtin is not present in the program.
pub fn write_output(
&mut self,
writer: &mut impl core::fmt::Write,
) -> Result<(), VirtualMachineError> {
let builtin = match self
.builtin_runners
.iter()
.find(|b| b.name() == OUTPUT_BUILTIN_NAME)
{
Some(x) => x,
_ => return Ok(()),
};
let segment_used_sizes = self.segments.compute_effective_sizes();
let segment_index = builtin.base();
#[allow(deprecated)]
for i in 0..segment_used_sizes[segment_index] {
let formatted_value = match self
.segments
.memory
.get(&Relocatable::from((segment_index as isize, i)))
{
Some(val) => match val.as_ref() {
MaybeRelocatable::Int(num) => format!("{}", num.to_signed_felt()),
MaybeRelocatable::RelocatableValue(rel) => format!("{}", rel),
},
_ => "<missing>".to_string(),
};
writeln!(writer, "{formatted_value}")
.map_err(|_| VirtualMachineError::FailedToWriteOutput)?;
}
Ok(())
}
///Relocates the VM's trace, turning relocatable registers to numbered ones
pub fn relocate_trace(&mut self, relocation_table: &[usize]) -> Result<(), TraceError> {
if let Some(ref mut trace) = self.trace {
if self.trace_relocated {
return Err(TraceError::AlreadyRelocated);
}