/
smallvm.rs
2702 lines (2415 loc) · 102 KB
/
smallvm.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 log::{debug, trace, error, warn};
use num_bigint::ToBigInt;
use num_traits::{Pow, ToPrimitive};
use py27_marshal::bstr::BString;
use py27_marshal::*;
use pydis::opcode::py27::{self, Mnemonic};
use pydis::prelude::*;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::convert::{TryFrom, TryInto};
use std::io::{Cursor, Read};
use std::sync::{Arc, Mutex};
pub enum WalkerState {
/// Continue parsing normally
Continue,
/// Continue parsing and parse the next instruction even if it's already
/// been parsed before
ContinueIgnoreAnalyzedInstructions,
/// Stop parsing
Break,
/// Immediately start parsing at the given offset and continue parsing
JumpTo(u64),
/// Assume the result of the previous comparison evaluated to the given bool
/// and continue parsing
AssumeComparison(bool),
}
impl WalkerState {
/// Returns whether we need to force queue the next instruction
fn force_queue_next(&self) -> bool {
matches!(
self,
Self::ContinueIgnoreAnalyzedInstructions | Self::JumpTo(_) | Self::AssumeComparison(_)
)
}
}
/// Represents a VM variable. The value is either `Some` (something we can)
/// statically resolve or `None` (something that cannot be resolved statically)
pub type VmVar = Option<Obj>;
/// A VM variable and the data it tracks. Typically this will be a VmVarWithTracking<()>,
/// or VmVarWithTracking<usize> where the usize represents an instruction index. But,
/// this can be anything you'd like it to be within the context of how you'll be executing
/// the instruction, and what data you'd like to track across instructions that share data.
pub type VmVarWithTracking<T> = (VmVar, InstructionTracker<T>);
/// The VM's stack state.
pub type VmStack<T> = Vec<VmVarWithTracking<T>>;
/// The VM's variable table
pub type VmVars<T> = HashMap<u16, VmVarWithTracking<T>>;
/// The VM's name table
pub type VmNames<T> = HashMap<Arc<BString>, VmVarWithTracking<T>>;
/// Names that get loaded while executing the VM. These are identifiers such as
/// module names and names *from* modules.
pub type LoadedNames = Arc<Mutex<Vec<Arc<BString>>>>;
/// Implements high-level routines that are useful when performing taint tracking
/// operations
#[derive(Debug)]
pub struct InstructionTracker<T>(pub Arc<Mutex<Vec<T>>>);
/// We implement a custom Clone routine since, in some scenarios, we want to share
/// the taint tracking across multiple objects in different locations. e.g. we may
/// want to share taint tracking state between our saved objects in our tables (vm vars, names, etc.)
/// and variables on the stack.
impl<T> Clone for InstructionTracker<T>
where
T: Clone,
{
fn clone(&self) -> Self {
InstructionTracker(Arc::clone(&self.0))
}
}
impl<T> InstructionTracker<T>
where
T: Clone,
{
/// Creates a new instruction tracker with no tracked data.
pub fn new() -> InstructionTracker<T> {
InstructionTracker(Arc::new(Mutex::new(vec![])))
}
/// Performs a deep clone of this instruction tracking state
pub fn deep_clone(&self) -> InstructionTracker<T> {
InstructionTracker(Arc::new(Mutex::new(self.0.lock().unwrap().clone())))
}
/// Pushes new data into the instruction tracking vector
pub fn push(&self, data: T) {
self.0.lock().unwrap().push(data)
}
/// Extends the state of this instruction tracker by copying all items from `other`'s
/// tracked state into this.
pub fn extend(&self, other: &InstructionTracker<T>) {
self.0
.lock()
.unwrap()
.extend_from_slice(other.0.lock().unwrap().as_slice());
}
}
/// SAFETY: The data in an `InstructionTracker` is wrapped in an Arc<Mutex<T>>
unsafe impl<T: Sync + Send> Send for InstructionTracker<T> {}
/// SAFETY: The data in an `InstructionTracker` is wrapped in an Arc<Mutex<T>>
unsafe impl<T: Sync + Send> Sync for InstructionTracker<T> {}
use py27_marshal::ObjHashable;
use crate::error::Error;
pub(crate) const PYTHON27_COMPARE_OPS: [&str; 12] = [
"<",
"<=",
"==",
"!=",
">",
">=",
"in",
"not in",
"is",
"is not",
"exception match",
"BAD",
];
/// Executes an instruction, altering the input state and returning an error
/// when the instruction cannot be correctly emulated. For example, some complex
/// instructions are not currently supported at this time.
pub fn execute_instruction<O: Opcode<Mnemonic = py27::Mnemonic>, F, T>(
instr: &Instruction<O>,
code: Arc<Code>,
stack: &mut VmStack<T>,
vars: &mut VmVars<T>,
names: &mut VmNames<T>,
globals: &mut VmNames<T>,
names_loaded: LoadedNames,
mut function_callback: F,
access_tracking: T,
) -> Result<(), Error<O>>
where
F: FnMut(VmVar, Vec<VmVar>, std::collections::HashMap<Option<ObjHashable>, VmVar>) -> VmVar,
T: Clone + Copy,
{
macro_rules! apply_operator {
($operator_str:expr) => {
let (tos, tos_accesses) = stack.pop().expect("no top of stack?");
let (tos1, tos1_accesses) = stack.pop().expect("no operand");
tos_accesses.push(access_tracking);
let tos_accesses = tos_accesses.deep_clone();
tos_accesses.extend(&tos1_accesses);
let operator_str = $operator_str;
match &tos1 {
Some(Obj::Long(left)) => {
match &tos {
Some(Obj::Long(right)) => {
let value = match operator_str {
"^" => {
left.as_ref() ^ right.as_ref()
}
"|" => {
left.as_ref() | right.as_ref()
}
"&" => {
left.as_ref() & right.as_ref()
}
"%" => {
left.as_ref() % right.as_ref()
}
"-" => {
left.as_ref() - right.as_ref()
}
"+" => {
left.as_ref() + right.as_ref()
}
"*" => {
left.as_ref() * right.as_ref()
}
"/" => {
left.as_ref() / right.as_ref()
}
"//" => {
left.as_ref() / right.as_ref()
}
"**" => {
// Check if our exponent is negative
if let num_bigint::Sign::Minus = right.sign() {
let positive_exponent = (-right.as_ref()).to_u32().unwrap();
let value = left.as_ref().pow(positive_exponent);
stack.push((
Some(Obj::Float(1.0 / value.to_f64().unwrap())),
tos_accesses,
));
return Ok(());
} else {
left.as_ref().pow(right.as_ref().to_u32().unwrap_or_else(|| panic!("could not convert {:?} to u32", right)))
}
}
"///" => {
// triple division is true divide -- convert to floats
let value = left.as_ref().to_f64().unwrap() / right.as_ref().to_f64().unwrap();
stack.push((
Some(Obj::Float(value)),
tos_accesses,
));
return Ok(());
}
other => {
panic!("operator {:?} not handled for Long operands", other);
}
};
stack.push((
Some(Obj::Long(Arc::new(
value
))),
tos_accesses,
));
}
Some(Obj::Float(right)) => {
match operator_str {
"*" => {
// For longs we can just use the operator outright
let value = left.as_ref().to_f64().unwrap() * right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"/" => {
// For longs we can just use the operator outright
let value = left.as_ref().to_f64().unwrap() / right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"+" => {
// For longs we can just use the operator outright
let value = left.as_ref().to_f64().unwrap() / right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"-" => {
// For longs we can just use the operator outright
let value = left.as_ref().to_f64().unwrap() / right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
_other => panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), "Float", operator_str),
}
}
Some(right)=> panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), right.typ(), operator_str),
None => stack.push((None, tos_accesses)),
}
}
Some(Obj::Float(left)) => {
match &tos {
Some(Obj::Long(right)) => {
match operator_str {
"*" => {
// For longs we can just use the operator outright
let value = left * right.as_ref().to_f64().unwrap();
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"/" => {
// For longs we can just use the operator outright
let value = left / right.as_ref().to_f64().unwrap();
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"+" => {
// For longs we can just use the operator outright
let value = left / right.as_ref().to_f64().unwrap();
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"-" => {
// For longs we can just use the operator outright
let value = left / right.as_ref().to_f64().unwrap();
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
_other => panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), "Float", operator_str),
};
}
Some(Obj::Float(right)) => {
match operator_str {
"*" => {
// For longs we can just use the operator outright
let value = left * right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"-" => {
// For longs we can just use the operator outright
let value = left - right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"+" => {
// For longs we can just use the operator outright
let value = left + right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
"/" => {
// For longs we can just use the operator outright
let value = left + right;
stack.push((
Some(Obj::Float(
value
)),
tos_accesses,
));
}
_ => panic!("operator {:?} not handled for float", operator_str),
}
}
Some(Obj::String(right)) => {
panic!("{:?}", right);
//return Err(crate::error::ExecutionError::ComplexExpression(instr.clone(), Some(tos1.unwrap().typ())).into());
}
Some(right)=> panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), right.typ(), operator_str),
None => stack.push((None, tos_accesses)),
}
}
Some(Obj::Set(left)) => {
match &tos {
Some(Obj::Set(right)) => {
match operator_str {
"&" => {
let left_set = left.read().unwrap();
let right_set = right.read().unwrap();
let intersection = left_set.intersection(&right_set);
stack.push((
Some(Obj::Set(Arc::new(
std::sync::RwLock::new(
intersection.cloned().collect::<std::collections::HashSet<_>>()
)
))),
tos_accesses,
));
}
"|" => {
let left_set = left.read().unwrap();
let right_set = right.read().unwrap();
let union = left_set.union(&right_set);
stack.push((
Some(Obj::Set(Arc::new(
std::sync::RwLock::new(
union.cloned().collect::<std::collections::HashSet<_>>()
)
))),
tos_accesses,
));
}
other => panic!("unsupported operator `{}` for {:?}", other, "set")
}
}
Some(right)=> panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), right.typ(), operator_str),
None => stack.push((None, tos_accesses)),
}
}
Some(Obj::String(left)) => {
// special case -- this is string formatting
if operator_str == "%" {
stack.push((
Some(Obj::String(Arc::new(
left.as_ref().clone()
))),
tos_accesses,
));
return Ok(());
}
match &tos{
Some(Obj::Long(right)) => {
match operator_str {
"*" => {
let value = left.repeat(right.to_usize().unwrap());
stack.push((
Some(Obj::String(Arc::new(
BString::from(value)
))),
tos_accesses,
));
}
"+" => {
let mut value = left.clone();
unsafe { Arc::get_mut_unchecked(&mut value) }.extend_from_slice(right.to_string().as_bytes());
stack.push((
Some(Obj::String(value)),
tos_accesses,
));
}
_other => panic!("unsupported operator {:?} for LHS {:?} RHS {:?}", operator_str, tos1.unwrap().typ(), tos.unwrap().typ())
}
}
Some(Obj::String(right)) => {
match operator_str {
"+" => {
let mut value = left.clone();
unsafe { Arc::get_mut_unchecked(&mut value) }.extend_from_slice(right.as_slice());
stack.push((
Some(Obj::String(value)),
tos_accesses,
));
}
_other => {
//return Err(crate::error::ExecutionError::ComplexExpression(instr.clone(), Some(tos1.unwrap().typ())).into());
panic!("unsupported operator {:?} for LHS {:?} RHS {:?}", operator_str, tos1.unwrap().typ(), tos.unwrap().typ())
}
}
}
Some(right)=> panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), right.typ(), operator_str),
None => stack.push((None, tos_accesses)),
}
}
Some(Obj::Tuple(left)) => {
match &tos{
Some(Obj::Tuple(right)) => {
match operator_str {
"+" => {
let mut value = left.clone();
unsafe { Arc::get_mut_unchecked(&mut value) }.extend(right.iter().cloned());
stack.push((
Some(Obj::Tuple(value)),
tos_accesses,
));
}
_other => panic!("unsupported operator {:?} for LHS {:?} RHS {:?}", operator_str, tos1.unwrap().typ(), tos.unwrap().typ())
}
}
Some(right)=> panic!("unsupported RHS. left: {:?}, right: {:?}. operator: {}", tos1.unwrap().typ(), right.typ(), operator_str),
None => stack.push((None, tos_accesses)),
}
}
Some(left)=> match &tos {
Some(right) => {
panic!("unsupported LHS {:?} for operator {:?}. right was {:?}", left.typ(), operator_str, right.typ())
}
None => {
panic!("unsupported LHS {:?} for operator {:?}. right was None", left.typ(), operator_str)
}
}
None => {
stack.push((None, tos_accesses));
}
}
};
}
use num_traits::Signed;
macro_rules! apply_unary_operator {
($operator:tt) => {
let (tos, tos_accesses) = stack.pop().expect("no top of stack?");
tos_accesses.push(access_tracking);
let operator_str = stringify!($operator);
match tos {
Some(Obj::Bool(result)) => {
let val = match operator_str {
"!" => !result,
other => panic!("unexpected unary operator {:?} for bool", other),
};
stack.push((Some(Obj::Bool(val)), tos_accesses));
}
Some(Obj::Long(result)) => {
let val = match operator_str {
"!" => {
let truthy_value = *result != 0.to_bigint().unwrap();
stack.push((Some(Obj::Bool(!truthy_value)), tos_accesses));
return Ok(());
}
"-" => -&*result,
"+" => result.abs(),
"~" => !&*result,
other => panic!("unexpected unary operator {:?} for bool", other),
};
stack.push((Some(Obj::Long(Arc::new(val))), tos_accesses));
}
Some(Obj::None) => {
let val = match operator_str {
"!" => true,
other => panic!("unexpected unary operator {:?} for None", other),
};
stack.push((Some(Obj::Bool(val)), tos_accesses));
}
Some(other) => {
panic!("unexpected TOS type for condition: {:?}", other.typ());
}
None => {
stack.push((None, tos_accesses));
}
}
};
}
match instr.opcode.mnemonic() {
Mnemonic::ROT_TWO => {
let (tos, tos_accesses) = stack.pop().unwrap();
let (tos1, tos1_accesses) = stack.pop().unwrap();
tos_accesses.push(access_tracking);
tos1_accesses.push(access_tracking);
stack.push((tos1, tos1_accesses));
stack.push((tos, tos_accesses));
}
Mnemonic::ROT_THREE => {
let (tos, tos_accesses) = stack.pop().unwrap();
let (tos1, tos1_accesses) = stack.pop().unwrap();
let (tos2, tos2_accesses) = stack.pop().unwrap();
tos_accesses.push(access_tracking);
tos1_accesses.push(access_tracking);
tos2_accesses.push(access_tracking);
stack.push((tos2, tos2_accesses));
stack.push((tos1, tos1_accesses));
stack.push((tos, tos_accesses));
}
Mnemonic::DUP_TOP => {
let (var, accesses) = stack.last().unwrap();
accesses.push(access_tracking);
let new_var = (var.clone(), accesses.deep_clone());
stack.push(new_var);
}
Mnemonic::DUP_TOPX => {
let count = instr.arg.unwrap() as usize;
if count != 2 && count != 3 {
panic!("DUP_TOPX should only be called with count == 2 or 3")
}
let mut new_items = vec![];
// DUP_TOPX duplicates the top N items on the stack in exactly the order
// they appear. so e.g. if the stack is:
// [0, 1, 2]
// and we DUP_TOPX (3)...
// the stack becomes:
// [0, 1, 2, 0, 1, 2]
for i in (0..count).rev() {
let (var, accesses) = &stack[(stack.len() - 1) - i];
accesses.push(access_tracking);
let new_var = (var.clone(), accesses.deep_clone());
new_items.push(new_var);
}
stack.append(&mut new_items);
}
Mnemonic::COMPARE_OP => {
let (right, right_modifying_instrs) = stack.pop().unwrap();
let (left, left_modifying_instrs) = stack.pop().unwrap();
left_modifying_instrs.push(access_tracking);
let left_modifying_instrs = left_modifying_instrs.deep_clone();
left_modifying_instrs.extend(&right_modifying_instrs);
if right.is_none() || left.is_none() {
stack.push((None, left_modifying_instrs));
return Ok(());
}
let left = left.unwrap();
let right = right.unwrap();
let op = PYTHON27_COMPARE_OPS[instr.arg.unwrap() as usize];
match op {
"<" => match left {
Obj::Long(l) => match right {
Obj::Long(r) => stack.push((Some(Obj::Bool(l < r)), left_modifying_instrs)),
other => panic!("unsupported right-hand operand: {:?}", other.typ()),
},
Obj::String(left) => match right {
Obj::String(right) => {
for idx in 0..std::cmp::min(left.len(), right.len()) {
if left[idx] != right[idx] {
stack.push((
Some(Obj::Bool(left[idx] < right[idx])),
left_modifying_instrs,
));
return Ok(());
}
}
stack.push((
Some(Obj::Bool(left.len() < right.len())),
left_modifying_instrs,
))
}
_other => {
stack.push((Some(Obj::Bool(false)), left_modifying_instrs));
// panic!(
// "unsupported right-hand operand for string >: {:?}",
// other.typ()
// )
}
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
"<=" => match left {
Obj::Long(l) => match right {
Obj::Long(r) => {
stack.push((Some(Obj::Bool(l <= r)), left_modifying_instrs))
}
Obj::Float(r) => stack.push((
Some(Obj::Bool(l.to_f64().unwrap() <= r)),
left_modifying_instrs,
)),
other => panic!(
"unsupported right-hand operand for Long <=: {:?}",
other.typ()
),
},
Obj::Bool(l) => match right {
Obj::Long(r) => stack.push((
Some(Obj::Bool((l as u32).to_bigint().unwrap() <= *r)),
left_modifying_instrs,
)),
Obj::Float(r) => stack.push((
Some(Obj::Bool((l as u64) as f64 <= r)),
left_modifying_instrs,
)),
Obj::Bool(r) => stack
.push((Some(Obj::Bool(l as u32 <= r as u32)), left_modifying_instrs)),
other => panic!(
"unsupported right-hand operand for Long <=: {:?}",
other.typ()
),
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
"==" => match left {
Obj::Long(l) => match right {
Obj::Long(r) => {
stack.push((Some(Obj::Bool(l == r)), left_modifying_instrs))
}
other => panic!(
"unsupported right-hand operand for Long ==: {:?}",
other.typ()
),
},
Obj::Set(left_set) => match right {
Obj::Set(right_set) => {
let left_set_lock = left_set.read().unwrap();
let right_set_lock = right_set.read().unwrap();
stack.push((
Some(Obj::Bool(&*left_set_lock == &*right_set_lock)),
left_modifying_instrs,
))
}
other => panic!(
"unsupported right-hand operand for Set == : {:?}",
other.typ()
),
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
"!=" => match left {
Obj::Long(l) => match right {
Obj::Long(r) => {
stack.push((Some(Obj::Bool(l != r)), left_modifying_instrs))
}
other => panic!(
"unsupported right-hand operand for Long !=: {:?}",
other.typ()
),
},
Obj::Set(left_set) => match right {
Obj::Set(right_set) => {
let left_set_lock = left_set.read().unwrap();
let right_set_lock = right_set.read().unwrap();
stack.push((
Some(Obj::Bool(&*left_set_lock != &*right_set_lock)),
left_modifying_instrs,
))
}
other => panic!("unsupported right-hand operand for !=: {:?}", other.typ()),
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
">" => match left {
Obj::Long(l) => match right {
Obj::Long(r) => stack.push((Some(Obj::Bool(l > r)), left_modifying_instrs)),
Obj::Float(r) => stack.push((
Some(Obj::Bool(l.to_f64().unwrap() > r)),
left_modifying_instrs,
)),
other => panic!(
"unsupported right-hand operand for Long >: {:?}",
other.typ()
),
},
Obj::String(left) => match right {
Obj::String(right) => {
for idx in 0..std::cmp::min(left.len(), right.len()) {
if left[idx] != right[idx] {
stack.push((
Some(Obj::Bool(left[idx] > right[idx])),
left_modifying_instrs,
));
return Ok(());
}
}
stack.push((
Some(Obj::Bool(left.len() > right.len())),
left_modifying_instrs,
))
}
_other => {
stack.push((Some(Obj::Bool(true)), left_modifying_instrs));
// panic!(
// "unsupported right-hand operand for string >: {:?}",
// other.typ()
// )
}
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
">=" => match left {
Obj::Long(l) => match right {
Obj::Long(r) => {
stack.push((Some(Obj::Bool(l >= r)), left_modifying_instrs))
}
Obj::Float(r) => stack.push((
Some(Obj::Bool(l.to_f64().unwrap() >= r)),
left_modifying_instrs,
)),
other => {
panic!("unsupported right-hand operand for Long: {:?}", other.typ())
}
},
Obj::Float(l) => match right {
Obj::Long(r) => {
stack.push((Some(Obj::Bool(l >= r.to_f64().unwrap())), left_modifying_instrs))
}
Obj::Float(r) => stack.push((
Some(Obj::Bool(l >= r)),
left_modifying_instrs,
)),
other => {
panic!("unsupported right-hand operand for Long: {:?}", other.typ())
}
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
"is not" => match left {
Obj::Long(_left) => match right {
Obj::None => stack.push((Some(Obj::Bool(true)), left_modifying_instrs)),
other => panic!(
"unsupported right-hand operand for Long {:?}: {:?}",
op,
other.typ()
),
}
Obj::String(_left) => match right {
Obj::None => stack.push((Some(Obj::Bool(true)), left_modifying_instrs)),
other => panic!(
"unsupported right-hand operand for string {:?}: {:?}",
op,
other.typ()
),
},
Obj::None => match right {
Obj::None => stack.push((Some(Obj::Bool(false)), left_modifying_instrs)),
other => panic!(
"unsupported right-hand operand for None, operator {:?}: {:?}",
op,
other.typ()
),
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}. RHS is {:?}",
other.typ(),
op,
right.typ(),
),
},
"is" => match left {
Obj::String(_left) => match right {
// all => {
// return Err(crate::error::ExecutionError::ComplexExpression(
// instr.clone(),
// Some(all.typ()),
// )
// .into())
// }
// Obj::None => stack.push((Some(Obj::Bool(true)), left_modifying_instrs)),
other => panic!(
"unsupported right-hand operand for string {:?}: {:?}",
op,
other.typ()
),
},
Obj::None => match right {
Obj::None => {
stack.push((Some(Obj::Bool(true)), left_modifying_instrs));
}
other => panic!(
"unsupported right-hand operand for None {:?}: {:?}",
op,
other.typ()
),
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
"in" => match left {
Obj::String(left) => match right {
Obj::Dict(set) => {
let dict = set.read().unwrap();
let hashed_string = ObjHashable::String(left);
stack.push((Some(Obj::Bool(dict.contains_key(&hashed_string))), left_modifying_instrs));
}
Obj::Set(set) => {
let set = set.read().unwrap();
let hashed_string = ObjHashable::String(left);
stack.push((Some(Obj::Bool(set.contains(&hashed_string))), left_modifying_instrs));
}
Obj::List(set) => {
let list = set.read().unwrap();
let list_contains = list.iter().find(|obj| if let Obj::String(list_item) = obj {
*list_item == left
} else {
false
});
stack.push((Some(Obj::Bool(list_contains.is_some())), left_modifying_instrs));
}
other => panic!(
"unsupported right-hand operand for string operator {:?}: {:?}",
op,
other.typ()
),
},
other => panic!(
"unsupported left-hand operand: {:?} for op {}",
other.typ(),
op
),
},
other => panic!("unsupported comparison operator: {:?} (left: {:?}, right: {:?})", other, left, right),
}
}
Mnemonic::IMPORT_NAME => {
let (_fromlist, fromlist_modifying_instrs) = stack.pop().unwrap();
let (_level, level_modifying_instrs) = stack.pop().unwrap();
level_modifying_instrs.extend(&fromlist_modifying_instrs);
level_modifying_instrs.push(access_tracking);
let _name = &code.names[instr.arg.unwrap() as usize];
// println!("importing: {}", name);
stack.push((None, level_modifying_instrs));
}
Mnemonic::IMPORT_FROM => {
let (_module, accessing_instrs) = stack.last().unwrap();
accessing_instrs.push(access_tracking);
let accessing_instrs = accessing_instrs.clone();
stack.push((None, accessing_instrs));
}
Mnemonic::LOAD_ATTR => {
// we don't support attributes
let (_obj, obj_modifying_instrs) = stack.pop().unwrap();
let _name = &code.names[instr.arg.unwrap() as usize];
obj_modifying_instrs.push(access_tracking);
stack.push((None, obj_modifying_instrs));
}
Mnemonic::STORE_ATTR => {
// we don't support attributes
let (_obj, _obj_modifying_instrs) = stack.pop().unwrap();
let (_obj, _obj_modifying_instrs) = stack.pop().unwrap();
}
Mnemonic::FOR_ITER => {
// Top of stack needs to be something we can iterate over
// get the next item from our iterator
let top_of_stack_index = stack.len() - 1;
let (tos, _modifying_instrs) = &mut stack[top_of_stack_index];
let new_tos = match tos {
Some(Obj::String(s)) => {
if let Some(byte) = unsafe { Arc::get_mut_unchecked(s) }.pop() {
Some(Obj::Long(Arc::new(byte.to_bigint().unwrap())))
} else {
// iterator is empty -- return
return Ok(());
}
}
Some(other) => panic!("stack object `{:?}` is not iterable", other),
None => None,
};
// let modifying_instrs = Rc::new(RefCell::new(modifying_instrs.borrow().clone()));
// modifying_instrs.borrow_mut().push(access_tracking);
stack.push((new_tos, InstructionTracker::new()))
}
Mnemonic::STORE_FAST => {
let (tos, accessing_instrs) = stack.pop().unwrap();
accessing_instrs.push(access_tracking);
// Store TOS in a var slot
vars.insert(instr.arg.unwrap(), (tos, accessing_instrs));
}
Mnemonic::STORE_NAME => {
let (tos, accessing_instrs) = stack.pop().unwrap();
let name = &code.names[instr.arg.unwrap() as usize];
accessing_instrs.push(access_tracking);
// Store TOS in a var slot
names.insert(Arc::clone(name), (tos, accessing_instrs));
}
Mnemonic::LOAD_NAME => {
let name = &code.names[instr.arg.unwrap() as usize];
names_loaded.lock().unwrap().push(Arc::clone(name));
if let Some((val, accesses)) = names.get(name) {
accesses.push(access_tracking);
stack.push((val.clone(), accesses.clone()));
} else {
let tracking = InstructionTracker::new();
tracking.push(access_tracking);
stack.push((None, tracking));
}
}