forked from rust-lang/miri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval_context.rs
2127 lines (1885 loc) · 85.5 KB
/
eval_context.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 std::collections::{HashMap, HashSet};
use std::fmt::Write;
use rustc::hir::def_id::DefId;
use rustc::hir::map::definitions::DefPathData;
use rustc::middle::const_val::ConstVal;
use rustc::mir;
use rustc::traits::Reveal;
use rustc::ty::layout::{self, Layout, Size};
use rustc::ty::subst::{Subst, Substs, Kind};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Binder};
use rustc::traits;
use rustc_data_structures::indexed_vec::Idx;
use syntax::codemap::{self, DUMMY_SP, Span};
use syntax::ast;
use syntax::abi::Abi;
use error::{EvalError, EvalResult};
use lvalue::{Global, GlobalId, Lvalue, LvalueExtra};
use memory::{Memory, Pointer, TlsKey};
use operator;
use value::{PrimVal, PrimValKind, Value};
pub struct EvalContext<'a, 'tcx: 'a> {
/// The results of the type checker, from rustc.
pub(crate) tcx: TyCtxt<'a, 'tcx, 'tcx>,
/// The virtual memory system.
pub(crate) memory: Memory<'a, 'tcx>,
/// Precomputed statics, constants and promoteds.
pub(crate) globals: HashMap<GlobalId<'tcx>, Global<'tcx>>,
/// The virtual call stack.
pub(crate) stack: Vec<Frame<'tcx>>,
/// The maximum number of stack frames allowed
pub(crate) stack_limit: usize,
/// The maximum number of operations that may be executed.
/// This prevents infinite loops and huge computations from freezing up const eval.
/// Remove once halting problem is solved.
pub(crate) steps_remaining: u64,
/// Environment variables set by `setenv`
/// Miri does not expose env vars from the host to the emulated program
pub(crate) env_vars: HashMap<Vec<u8>, Pointer>,
}
/// A stack frame.
pub struct Frame<'tcx> {
////////////////////////////////////////////////////////////////////////////////
// Function and callsite information
////////////////////////////////////////////////////////////////////////////////
/// The MIR for the function called on this frame.
pub mir: &'tcx mir::Mir<'tcx>,
/// The def_id and substs of the current function
pub instance: ty::Instance<'tcx>,
/// The span of the call site.
pub span: codemap::Span,
////////////////////////////////////////////////////////////////////////////////
// Return lvalue and locals
////////////////////////////////////////////////////////////////////////////////
/// The block to return to when returning from the current stack frame
pub return_to_block: StackPopCleanup,
/// The location where the result of the current stack frame should be written to.
pub return_lvalue: Lvalue<'tcx>,
/// The list of locals for this stack frame, stored in order as
/// `[arguments..., variables..., temporaries...]`. The locals are stored as `Option<Value>`s.
/// `None` represents a local that is currently dead, while a live local
/// can either directly contain `PrimVal` or refer to some part of an `Allocation`.
///
/// Before being initialized, arguments are `Value::ByVal(PrimVal::Undef)` and other locals are `None`.
pub locals: Vec<Option<Value>>,
////////////////////////////////////////////////////////////////////////////////
// Current position within the function
////////////////////////////////////////////////////////////////////////////////
/// The block that is currently executed (or will be executed after the above call stacks
/// return).
pub block: mir::BasicBlock,
/// The index of the currently evaluated statment.
pub stmt: usize,
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum StackPopCleanup {
/// The stackframe existed to compute the initial value of a static/constant, make sure it
/// isn't modifyable afterwards in case of constants.
/// In case of `static mut`, mark the memory to ensure it's never marked as immutable through
/// references or deallocated
/// The bool decides whether the value is mutable (true) or not (false)
MarkStatic(bool),
/// A regular stackframe added due to a function call will need to get forwarded to the next
/// block
Goto(mir::BasicBlock),
/// After finishing a tls destructor, find the next one instead of starting from the beginning
/// and thus just rerunning the first one until its `data` argument is null
///
/// The index is the current tls destructor's index
Tls(Option<TlsKey>),
/// The main function and diverging functions have nowhere to return to
None,
}
#[derive(Copy, Clone, Debug)]
pub struct ResourceLimits {
pub memory_size: u64,
pub step_limit: u64,
pub stack_limit: usize,
}
impl Default for ResourceLimits {
fn default() -> Self {
ResourceLimits {
memory_size: 100 * 1024 * 1024, // 100 MB
step_limit: 1_000_000,
stack_limit: 100,
}
}
}
impl<'a, 'tcx> EvalContext<'a, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, limits: ResourceLimits) -> Self {
EvalContext {
tcx,
memory: Memory::new(&tcx.data_layout, limits.memory_size),
globals: HashMap::new(),
stack: Vec::new(),
stack_limit: limits.stack_limit,
steps_remaining: limits.step_limit,
env_vars: HashMap::new(),
}
}
pub fn alloc_ptr(&mut self, ty: Ty<'tcx>) -> EvalResult<'tcx, Pointer> {
let substs = self.substs();
self.alloc_ptr_with_substs(ty, substs)
}
pub fn alloc_ptr_with_substs(
&mut self,
ty: Ty<'tcx>,
substs: &'tcx Substs<'tcx>
) -> EvalResult<'tcx, Pointer> {
let size = self.type_size_with_substs(ty, substs)?.expect("cannot alloc memory for unsized type");
let align = self.type_align_with_substs(ty, substs)?;
self.memory.allocate(size, align)
}
pub fn memory(&self) -> &Memory<'a, 'tcx> {
&self.memory
}
pub fn memory_mut(&mut self) -> &mut Memory<'a, 'tcx> {
&mut self.memory
}
pub fn stack(&self) -> &[Frame<'tcx>] {
&self.stack
}
pub(crate) fn str_to_value(&mut self, s: &str) -> EvalResult<'tcx, Value> {
let ptr = self.memory.allocate_cached(s.as_bytes())?;
Ok(Value::ByValPair(PrimVal::Ptr(ptr), PrimVal::from_u128(s.len() as u128)))
}
pub(super) fn const_to_value(&mut self, const_val: &ConstVal<'tcx>) -> EvalResult<'tcx, Value> {
use rustc::middle::const_val::ConstVal::*;
use rustc_const_math::ConstFloat;
let primval = match *const_val {
Integral(const_int) => PrimVal::Bytes(const_int.to_u128_unchecked()),
Float(ConstFloat::F32(f)) => PrimVal::from_f32(f),
Float(ConstFloat::F64(f)) => PrimVal::from_f64(f),
Bool(b) => PrimVal::from_bool(b),
Char(c) => PrimVal::from_char(c),
Str(ref s) => return self.str_to_value(s),
ByteStr(ref bs) => {
let ptr = self.memory.allocate_cached(bs)?;
PrimVal::Ptr(ptr)
}
Variant(_) => unimplemented!(),
Struct(_) => unimplemented!(),
Tuple(_) => unimplemented!(),
// function items are zero sized and thus have no readable value
Function(..) => PrimVal::Undef,
Array(_) => unimplemented!(),
Repeat(_, _) => unimplemented!(),
};
Ok(Value::ByVal(primval))
}
pub(super) fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
// generics are weird, don't run this function on a generic
assert!(!ty.needs_subst());
ty.is_sized(self.tcx, ty::ParamEnv::empty(Reveal::All), DUMMY_SP)
}
pub fn load_mir(&self, instance: ty::InstanceDef<'tcx>) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
trace!("load mir {:?}", instance);
match instance {
ty::InstanceDef::Item(def_id) => self.tcx.maybe_optimized_mir(def_id).ok_or_else(|| EvalError::NoMirFor(self.tcx.item_path_str(def_id))),
_ => Ok(self.tcx.instance_mir(instance)),
}
}
pub fn monomorphize(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
// miri doesn't care about lifetimes, and will choke on some crazy ones
// let's simply get rid of them
let without_lifetimes = self.tcx.erase_regions(&ty);
let substituted = without_lifetimes.subst(self.tcx, substs);
self.tcx.normalize_associated_type(&substituted)
}
pub fn erase_lifetimes<T>(&self, value: &Binder<T>) -> T
where T : TypeFoldable<'tcx>
{
let value = self.tcx.erase_late_bound_regions(value);
self.tcx.erase_regions(&value)
}
pub(super) fn type_size(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, Option<u64>> {
self.type_size_with_substs(ty, self.substs())
}
pub(super) fn type_align(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, u64> {
self.type_align_with_substs(ty, self.substs())
}
fn type_size_with_substs(
&self,
ty: Ty<'tcx>,
substs: &'tcx Substs<'tcx>,
) -> EvalResult<'tcx, Option<u64>> {
let layout = self.type_layout_with_substs(ty, substs)?;
if layout.is_unsized() {
Ok(None)
} else {
Ok(Some(layout.size(&self.tcx.data_layout).bytes()))
}
}
fn type_align_with_substs(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, u64> {
self.type_layout_with_substs(ty, substs).map(|layout| layout.align(&self.tcx.data_layout).abi())
}
pub(super) fn type_layout(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, &'tcx Layout> {
self.type_layout_with_substs(ty, self.substs())
}
fn type_layout_with_substs(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, &'tcx Layout> {
// TODO(solson): Is this inefficient? Needs investigation.
let ty = self.monomorphize(ty, substs);
ty.layout(self.tcx, ty::ParamEnv::empty(Reveal::All)).map_err(EvalError::Layout)
}
pub fn push_stack_frame(
&mut self,
instance: ty::Instance<'tcx>,
span: codemap::Span,
mir: &'tcx mir::Mir<'tcx>,
return_lvalue: Lvalue<'tcx>,
return_to_block: StackPopCleanup,
) -> EvalResult<'tcx> {
::log_settings::settings().indentation += 1;
/// Return the set of locals that have a storage annotation anywhere
fn collect_storage_annotations<'tcx>(mir: &'tcx mir::Mir<'tcx>) -> HashSet<mir::Local> {
use rustc::mir::StatementKind::*;
let mut set = HashSet::new();
for block in mir.basic_blocks() {
for stmt in block.statements.iter() {
match stmt.kind {
StorageLive(mir::Lvalue::Local(local)) | StorageDead(mir::Lvalue::Local(local)) => {
set.insert(local);
}
_ => {}
}
}
};
set
}
// Subtract 1 because `local_decls` includes the ReturnPointer, but we don't store a local
// `Value` for that.
let annotated_locals = collect_storage_annotations(mir);
let num_locals = mir.local_decls.len() - 1;
let mut locals = vec![None; num_locals];
for i in 0..num_locals {
let local = mir::Local::new(i+1);
if !annotated_locals.contains(&local) {
locals[i] = Some(Value::ByVal(PrimVal::Undef));
}
}
self.stack.push(Frame {
mir,
block: mir::START_BLOCK,
return_to_block,
return_lvalue,
locals,
span,
instance,
stmt: 0,
});
if self.stack.len() > self.stack_limit {
Err(EvalError::StackFrameLimitReached)
} else {
Ok(())
}
}
pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
::log_settings::settings().indentation -= 1;
let frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
match frame.return_to_block {
StackPopCleanup::MarkStatic(mutable) => if let Lvalue::Global(id) = frame.return_lvalue {
let global_value = self.globals.get_mut(&id)
.expect("global should have been cached (static)");
match global_value.value {
Value::ByRef(ptr) => self.memory.mark_static_initalized(ptr.alloc_id, mutable)?,
Value::ByVal(val) => if let PrimVal::Ptr(ptr) = val {
self.memory.mark_inner_allocation(ptr.alloc_id, mutable)?;
},
Value::ByValPair(val1, val2) => {
if let PrimVal::Ptr(ptr) = val1 {
self.memory.mark_inner_allocation(ptr.alloc_id, mutable)?;
}
if let PrimVal::Ptr(ptr) = val2 {
self.memory.mark_inner_allocation(ptr.alloc_id, mutable)?;
}
},
}
// see comment on `initialized` field
assert!(!global_value.initialized);
global_value.initialized = true;
assert!(global_value.mutable);
global_value.mutable = mutable;
} else {
bug!("StackPopCleanup::MarkStatic on: {:?}", frame.return_lvalue);
},
StackPopCleanup::Goto(target) => self.goto_block(target),
StackPopCleanup::None => {},
StackPopCleanup::Tls(key) => {
// either fetch the next dtor or start new from the beginning, if any are left with a non-null data
let dtor = match self.memory.fetch_tls_dtor(key)? {
dtor @ Some(_) => dtor,
None => self.memory.fetch_tls_dtor(None)?,
};
if let Some((instance, ptr, key)) = dtor {
trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
// TODO: Potentially, this has to support all the other possible instances? See eval_fn_call in terminator/mod.rs
let mir = self.load_mir(instance.def)?;
self.push_stack_frame(
instance,
mir.span,
mir,
Lvalue::undef(),
StackPopCleanup::Tls(Some(key)),
)?;
let arg_local = self.frame().mir.args_iter().next().ok_or(EvalError::AbiViolation("TLS dtor does not take enough arguments.".to_owned()))?;
let dest = self.eval_lvalue(&mir::Lvalue::Local(arg_local))?;
let ty = self.tcx.mk_mut_ptr(self.tcx.types.u8);
self.write_primval(dest, ptr, ty)?;
}
}
}
// deallocate all locals that are backed by an allocation
for local in frame.locals {
self.deallocate_local(local)?;
}
Ok(())
}
pub fn deallocate_local(&mut self, local: Option<Value>) -> EvalResult<'tcx> {
if let Some(Value::ByRef(ptr)) = local {
trace!("deallocating local");
self.memory.dump_alloc(ptr.alloc_id);
match self.memory.deallocate(ptr) {
// We could alternatively check whether the alloc_id is static before calling
// deallocate, but this is much simpler and is probably the rare case.
Ok(()) | Err(EvalError::DeallocatedStaticMemory) => {},
other => return other,
}
};
Ok(())
}
pub fn assign_discr_and_fields<
V: IntoValTyPair<'tcx>,
J: IntoIterator<Item = V>,
>(
&mut self,
dest: Lvalue<'tcx>,
dest_ty: Ty<'tcx>,
discr_offset: u64,
operands: J,
discr_val: u128,
variant_idx: usize,
discr_size: u64,
) -> EvalResult<'tcx>
where J::IntoIter: ExactSizeIterator,
{
// FIXME(solson)
let dest_ptr = self.force_allocation(dest)?.to_ptr()?;
let discr_dest = dest_ptr.offset(discr_offset, self.memory.layout)?;
self.memory.write_uint(discr_dest, discr_val, discr_size)?;
let dest = Lvalue::Ptr {
ptr: PrimVal::Ptr(dest_ptr),
extra: LvalueExtra::DowncastVariant(variant_idx),
};
self.assign_fields(dest, dest_ty, operands)
}
pub fn assign_fields<
V: IntoValTyPair<'tcx>,
J: IntoIterator<Item = V>,
>(
&mut self,
dest: Lvalue<'tcx>,
dest_ty: Ty<'tcx>,
operands: J,
) -> EvalResult<'tcx>
where J::IntoIter: ExactSizeIterator,
{
if self.type_size(dest_ty)? == Some(0) {
// zst assigning is a nop
return Ok(());
}
if self.ty_to_primval_kind(dest_ty).is_ok() {
let mut iter = operands.into_iter();
assert_eq!(iter.len(), 1);
let (value, value_ty) = iter.next().unwrap().into_val_ty_pair(self)?;
return self.write_value(value, dest, value_ty);
}
for (field_index, operand) in operands.into_iter().enumerate() {
let (value, value_ty) = operand.into_val_ty_pair(self)?;
let field_dest = self.lvalue_field(dest, field_index, dest_ty, value_ty)?;
self.write_value(value, field_dest, value_ty)?;
}
Ok(())
}
/// Evaluate an assignment statement.
///
/// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
/// type writes its results directly into the memory specified by the lvalue.
pub(super) fn eval_rvalue_into_lvalue(
&mut self,
rvalue: &mir::Rvalue<'tcx>,
lvalue: &mir::Lvalue<'tcx>,
) -> EvalResult<'tcx> {
let dest = self.eval_lvalue(lvalue)?;
let dest_ty = self.lvalue_ty(lvalue);
let dest_layout = self.type_layout(dest_ty)?;
use rustc::mir::Rvalue::*;
match *rvalue {
Use(ref operand) => {
let value = self.eval_operand(operand)?;
self.write_value(value, dest, dest_ty)?;
}
BinaryOp(bin_op, ref left, ref right) => {
if self.intrinsic_overflowing(bin_op, left, right, dest, dest_ty)? {
// There was an overflow in an unchecked binop. Right now, we consider this an error and bail out.
// The rationale is that the reason rustc emits unchecked binops in release mode (vs. the checked binops
// it emits in debug mode) is performance, but it doesn't cost us any performance in miri.
// If, however, the compiler ever starts transforming unchecked intrinsics into unchecked binops,
// we have to go back to just ignoring the overflow here.
return Err(EvalError::OverflowingMath);
}
}
CheckedBinaryOp(bin_op, ref left, ref right) => {
self.intrinsic_with_overflow(bin_op, left, right, dest, dest_ty)?;
}
UnaryOp(un_op, ref operand) => {
let val = self.eval_operand_to_primval(operand)?;
let kind = self.ty_to_primval_kind(dest_ty)?;
self.write_primval(dest, operator::unary_op(un_op, val, kind)?, dest_ty)?;
}
// Skip everything for zsts
Aggregate(..) if self.type_size(dest_ty)? == Some(0) => {}
Aggregate(ref kind, ref operands) => {
self.inc_step_counter_and_check_limit(operands.len() as u64)?;
use rustc::ty::layout::Layout::*;
match *dest_layout {
Univariant { ref variant, .. } => {
if variant.packed {
let ptr = self.force_allocation(dest)?.to_ptr_and_extra().0.to_ptr()?;
self.memory.mark_packed(ptr, variant.stride().bytes());
}
self.assign_fields(dest, dest_ty, operands)?;
}
Array { .. } => {
self.assign_fields(dest, dest_ty, operands)?;
}
General { discr, ref variants, .. } => {
if let mir::AggregateKind::Adt(adt_def, variant, _, _) = **kind {
let discr_val = adt_def.discriminants(self.tcx)
.nth(variant)
.expect("broken mir: Adt variant id invalid")
.to_u128_unchecked();
let discr_size = discr.size().bytes();
if variants[variant].packed {
let ptr = self.force_allocation(dest)?.to_ptr_and_extra().0.to_ptr()?;
self.memory.mark_packed(ptr, variants[variant].stride().bytes());
}
self.assign_discr_and_fields(
dest,
dest_ty,
variants[variant].offsets[0].bytes(),
operands,
discr_val,
variant,
discr_size,
)?;
} else {
bug!("tried to assign {:?} to Layout::General", kind);
}
}
RawNullablePointer { nndiscr, .. } => {
if let mir::AggregateKind::Adt(_, variant, _, _) = **kind {
if nndiscr == variant as u64 {
assert_eq!(operands.len(), 1);
let operand = &operands[0];
let value = self.eval_operand(operand)?;
let value_ty = self.operand_ty(operand);
self.write_value(value, dest, value_ty)?;
} else {
if let Some(operand) = operands.get(0) {
assert_eq!(operands.len(), 1);
let operand_ty = self.operand_ty(operand);
assert_eq!(self.type_size(operand_ty)?, Some(0));
}
self.write_primval(dest, PrimVal::Bytes(0), dest_ty)?;
}
} else {
bug!("tried to assign {:?} to Layout::RawNullablePointer", kind);
}
}
StructWrappedNullablePointer { nndiscr, ref nonnull, ref discrfield, .. } => {
if let mir::AggregateKind::Adt(_, variant, _, _) = **kind {
if nonnull.packed {
let ptr = self.force_allocation(dest)?.to_ptr_and_extra().0.to_ptr()?;
self.memory.mark_packed(ptr, nonnull.stride().bytes());
}
if nndiscr == variant as u64 {
self.assign_fields(dest, dest_ty, operands)?;
} else {
for operand in operands {
let operand_ty = self.operand_ty(operand);
assert_eq!(self.type_size(operand_ty)?, Some(0));
}
let (offset, ty) = self.nonnull_offset_and_ty(dest_ty, nndiscr, discrfield)?;
// FIXME(solson)
let dest = self.force_allocation(dest)?.to_ptr()?;
let dest = dest.offset(offset.bytes(), self.memory.layout)?;
let dest_size = self.type_size(ty)?
.expect("bad StructWrappedNullablePointer discrfield");
self.memory.write_int(dest, 0, dest_size)?;
}
} else {
bug!("tried to assign {:?} to Layout::RawNullablePointer", kind);
}
}
CEnum { .. } => {
assert_eq!(operands.len(), 0);
if let mir::AggregateKind::Adt(adt_def, variant, _, _) = **kind {
let n = adt_def.discriminants(self.tcx)
.nth(variant)
.expect("broken mir: Adt variant index invalid")
.to_u128_unchecked();
self.write_primval(dest, PrimVal::Bytes(n), dest_ty)?;
} else {
bug!("tried to assign {:?} to Layout::CEnum", kind);
}
}
Vector { count, .. } => {
debug_assert_eq!(count, operands.len() as u64);
self.assign_fields(dest, dest_ty, operands)?;
}
UntaggedUnion { .. } => {
assert_eq!(operands.len(), 1);
let operand = &operands[0];
let value = self.eval_operand(operand)?;
let value_ty = self.operand_ty(operand);
self.write_value(value, dest, value_ty)?;
}
_ => {
return Err(EvalError::Unimplemented(format!(
"can't handle destination layout {:?} when assigning {:?}",
dest_layout,
kind
)));
}
}
}
Repeat(ref operand, _) => {
let (elem_ty, length) = match dest_ty.sty {
ty::TyArray(elem_ty, n) => (elem_ty, n as u64),
_ => bug!("tried to assign array-repeat to non-array type {:?}", dest_ty),
};
self.inc_step_counter_and_check_limit(length)?;
let elem_size = self.type_size(elem_ty)?
.expect("repeat element type must be sized");
let value = self.eval_operand(operand)?;
// FIXME(solson)
let dest = PrimVal::Ptr(self.force_allocation(dest)?.to_ptr()?);
for i in 0..length {
let elem_dest = dest.offset(i * elem_size, self.memory.layout)?;
self.write_value_to_ptr(value, elem_dest, elem_ty)?;
}
}
Len(ref lvalue) => {
if self.frame().const_env() {
return Err(EvalError::NeedsRfc("computing the length of arrays".to_string()));
}
let src = self.eval_lvalue(lvalue)?;
let ty = self.lvalue_ty(lvalue);
let (_, len) = src.elem_ty_and_len(ty);
self.write_primval(dest, PrimVal::from_u128(len as u128), dest_ty)?;
}
Ref(_, _, ref lvalue) => {
let src = self.eval_lvalue(lvalue)?;
let (ptr, extra) = self.force_allocation(src)?.to_ptr_and_extra();
let ty = self.lvalue_ty(lvalue);
let val = match extra {
LvalueExtra::None => Value::ByVal(ptr),
LvalueExtra::Length(len) => Value::ByValPair(ptr, PrimVal::from_u128(len as u128)),
LvalueExtra::Vtable(vtable) => Value::ByValPair(ptr, PrimVal::Ptr(vtable)),
LvalueExtra::DowncastVariant(..) =>
bug!("attempted to take a reference to an enum downcast lvalue"),
};
// Check alignment and non-NULLness.
let (_, align) = self.size_and_align_of_dst(ty, val)?;
match ptr {
PrimVal::Ptr(ptr) => {
self.memory.check_align(ptr, align, 0)?;
}
PrimVal::Bytes(bytes) => {
let v = ((bytes as u128) % (1 << self.memory.pointer_size())) as u64;
if v == 0 {
return Err(EvalError::InvalidNullPointerUsage);
}
if v % align != 0 {
return Err(EvalError::AlignmentCheckFailed {
has: v % align,
required: align,
});
}
}
PrimVal::Undef => {
return Err(EvalError::ReadUndefBytes);
}
}
self.write_value(val, dest, dest_ty)?;
}
NullaryOp(mir::NullOp::Box, ty) => {
if self.frame().const_env() {
return Err(EvalError::NeedsRfc("\"heap\" allocations".to_string()));
}
// FIXME: call the `exchange_malloc` lang item if available
if self.type_size(ty)?.expect("box only works with sized types") == 0 {
let align = self.type_align(ty)?;
self.write_primval(dest, PrimVal::Bytes(align.into()), dest_ty)?;
} else {
let ptr = self.alloc_ptr(ty)?;
self.write_primval(dest, PrimVal::Ptr(ptr), dest_ty)?;
}
}
NullaryOp(mir::NullOp::SizeOf, ty) => {
if self.frame().const_env() {
return Err(EvalError::NeedsRfc("computing the size of types (size_of)".to_string()));
}
let size = self.type_size(ty)?.expect("SizeOf nullary MIR operator called for unsized type");
self.write_primval(dest, PrimVal::from_u128(size as u128), dest_ty)?;
}
Cast(kind, ref operand, cast_ty) => {
debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest_ty);
use rustc::mir::CastKind::*;
match kind {
Unsize => {
let src = self.eval_operand(operand)?;
let src_ty = self.operand_ty(operand);
self.unsize_into(src, src_ty, dest, dest_ty)?;
}
Misc => {
let src = self.eval_operand(operand)?;
let src_ty = self.operand_ty(operand);
if self.type_is_fat_ptr(src_ty) {
match (src, self.type_is_fat_ptr(dest_ty)) {
(Value::ByRef(_), _) |
(Value::ByValPair(..), true) => {
self.write_value(src, dest, dest_ty)?;
},
(Value::ByValPair(data, _), false) => {
self.write_value(Value::ByVal(data), dest, dest_ty)?;
},
(Value::ByVal(_), _) => bug!("expected fat ptr"),
}
} else {
let src_val = self.value_to_primval(src, src_ty)?;
let dest_val = self.cast_primval(src_val, src_ty, dest_ty)?;
self.write_value(Value::ByVal(dest_val), dest, dest_ty)?;
}
}
ReifyFnPointer => match self.operand_ty(operand).sty {
ty::TyFnDef(def_id, substs, _) => {
let instance = resolve(self.tcx, def_id, substs);
let fn_ptr = self.memory.create_fn_alloc(instance);
self.write_value(Value::ByVal(PrimVal::Ptr(fn_ptr)), dest, dest_ty)?;
},
ref other => bug!("reify fn pointer on {:?}", other),
},
UnsafeFnPointer => match dest_ty.sty {
ty::TyFnPtr(_) => {
let src = self.eval_operand(operand)?;
self.write_value(src, dest, dest_ty)?;
},
ref other => bug!("fn to unsafe fn cast on {:?}", other),
},
ClosureFnPointer => match self.operand_ty(operand).sty {
ty::TyClosure(def_id, substs) => {
let instance = resolve_closure(self.tcx, def_id, substs, ty::ClosureKind::FnOnce);
let fn_ptr = self.memory.create_fn_alloc(instance);
self.write_value(Value::ByVal(PrimVal::Ptr(fn_ptr)), dest, dest_ty)?;
},
ref other => bug!("closure fn pointer on {:?}", other),
},
}
}
Discriminant(ref lvalue) => {
let lval = self.eval_lvalue(lvalue)?;
let ty = self.lvalue_ty(lvalue);
let ptr = self.force_allocation(lval)?.to_ptr()?;
let discr_val = self.read_discriminant_value(ptr, ty)?;
if let ty::TyAdt(adt_def, _) = ty.sty {
if adt_def.discriminants(self.tcx).all(|v| discr_val != v.to_u128_unchecked()) {
return Err(EvalError::InvalidDiscriminant);
}
} else {
bug!("rustc only generates Rvalue::Discriminant for enums");
}
self.write_primval(dest, PrimVal::Bytes(discr_val), dest_ty)?;
},
}
if log_enabled!(::log::LogLevel::Trace) {
self.dump_local(dest);
}
Ok(())
}
fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
match ty.sty {
ty::TyRawPtr(ref tam) |
ty::TyRef(_, ref tam) => !self.type_is_sized(tam.ty),
ty::TyAdt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
_ => false,
}
}
pub(super) fn nonnull_offset_and_ty(
&self,
ty: Ty<'tcx>,
nndiscr: u64,
discrfield: &[u32],
) -> EvalResult<'tcx, (Size, Ty<'tcx>)> {
// Skip the constant 0 at the start meant for LLVM GEP and the outer non-null variant
let path = discrfield.iter().skip(2).map(|&i| i as usize);
// Handle the field index for the outer non-null variant.
let (inner_offset, inner_ty) = match ty.sty {
ty::TyAdt(adt_def, substs) => {
let variant = &adt_def.variants[nndiscr as usize];
let index = discrfield[1];
let field = &variant.fields[index as usize];
(self.get_field_offset(ty, index as usize)?, field.ty(self.tcx, substs))
}
_ => bug!("non-enum for StructWrappedNullablePointer: {}", ty),
};
self.field_path_offset_and_ty(inner_offset, inner_ty, path)
}
fn field_path_offset_and_ty<I: Iterator<Item = usize>>(
&self,
mut offset: Size,
mut ty: Ty<'tcx>,
path: I,
) -> EvalResult<'tcx, (Size, Ty<'tcx>)> {
// Skip the initial 0 intended for LLVM GEP.
for field_index in path {
let field_offset = self.get_field_offset(ty, field_index)?;
trace!("field_path_offset_and_ty: {}, {}, {:?}, {:?}", field_index, ty, field_offset, offset);
ty = self.get_field_ty(ty, field_index)?;
offset = offset.checked_add(field_offset, &self.tcx.data_layout).unwrap();
}
Ok((offset, ty))
}
fn get_fat_field(&self, pointee_ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Ty<'tcx>> {
match (field_index, &self.tcx.struct_tail(pointee_ty).sty) {
(1, &ty::TyStr) |
(1, &ty::TySlice(_)) => Ok(self.tcx.types.usize),
(1, &ty::TyDynamic(..)) |
(0, _) => Ok(self.tcx.mk_imm_ptr(self.tcx.types.u8)),
_ => bug!("invalid fat pointee type: {}", pointee_ty),
}
}
pub fn get_field_ty(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Ty<'tcx>> {
match ty.sty {
ty::TyAdt(adt_def, _) if adt_def.is_box() => self.get_fat_field(ty.boxed_ty(), field_index),
ty::TyAdt(adt_def, substs) => {
Ok(adt_def.struct_variant().fields[field_index].ty(self.tcx, substs))
}
ty::TyTuple(fields, _) => Ok(fields[field_index]),
ty::TyRef(_, ref tam) |
ty::TyRawPtr(ref tam) => self.get_fat_field(tam.ty, field_index),
_ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}, {:?}", ty, ty.sty))),
}
}
fn get_field_offset(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Size> {
let layout = self.type_layout(ty)?;
use rustc::ty::layout::Layout::*;
match *layout {
Univariant { ref variant, .. } => {
Ok(variant.offsets[field_index])
}
FatPointer { .. } => {
let bytes = field_index as u64 * self.memory.pointer_size();
Ok(Size::from_bytes(bytes))
}
StructWrappedNullablePointer { ref nonnull, .. } => {
Ok(nonnull.offsets[field_index])
}
_ => {
let msg = format!("can't handle type: {:?}, with layout: {:?}", ty, layout);
Err(EvalError::Unimplemented(msg))
}
}
}
pub fn get_field_count(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, usize> {
let layout = self.type_layout(ty)?;
use rustc::ty::layout::Layout::*;
match *layout {
Univariant { ref variant, .. } => Ok(variant.offsets.len()),
FatPointer { .. } => Ok(2),
StructWrappedNullablePointer { ref nonnull, .. } => Ok(nonnull.offsets.len()),
_ => {
let msg = format!("can't handle type: {:?}, with layout: {:?}", ty, layout);
Err(EvalError::Unimplemented(msg))
}
}
}
pub(super) fn wrapping_pointer_offset(&self, ptr: PrimVal, pointee_ty: Ty<'tcx>, offset: i64) -> EvalResult<'tcx, PrimVal> {
// FIXME: assuming here that type size is < i64::max_value()
let pointee_size = self.type_size(pointee_ty)?.expect("cannot offset a pointer to an unsized type") as i64;
let offset = offset.overflowing_mul(pointee_size).0;
ptr.wrapping_signed_offset(offset, self.memory.layout)
}
pub(super) fn pointer_offset(&self, ptr: PrimVal, pointee_ty: Ty<'tcx>, offset: i64) -> EvalResult<'tcx, PrimVal> {
// This function raises an error if the offset moves the pointer outside of its allocation. We consider
// ZSTs their own huge allocation that doesn't overlap with anything (and nothing moves in there because the size is 0).
// We also consider the NULL pointer its own separate allocation, and all the remaining integers pointers their own
// allocation.
if ptr.is_null()? { // NULL pointers must only be offset by 0
return if offset == 0 { Ok(ptr) } else { Err(EvalError::InvalidNullPointerUsage) };
}
// FIXME: assuming here that type size is < i64::max_value()
let pointee_size = self.type_size(pointee_ty)?.expect("cannot offset a pointer to an unsized type") as i64;
return if let Some(offset) = offset.checked_mul(pointee_size) {
let ptr = ptr.signed_offset(offset, self.memory.layout)?;
// Do not do bounds-checking for integers; they can never alias a normal pointer anyway.
if let PrimVal::Ptr(ptr) = ptr {
self.memory.check_bounds(ptr, false)?;
} else if ptr.is_null()? {
// We moved *to* a NULL pointer. That seems wrong, LLVM considers the NULL pointer its own small allocation. Reject this, for now.
return Err(EvalError::InvalidNullPointerUsage);
}
Ok(ptr)
} else {
Err(EvalError::OverflowingMath)
}
}
pub(super) fn eval_operand_to_primval(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, PrimVal> {
let value = self.eval_operand(op)?;
let ty = self.operand_ty(op);
self.value_to_primval(value, ty)
}
pub(super) fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, Value> {
use rustc::mir::Operand::*;
match *op {
Consume(ref lvalue) => self.eval_and_read_lvalue(lvalue),
Constant(ref constant) => {
use rustc::mir::Literal;
let mir::Constant { ref literal, .. } = **constant;
let value = match *literal {
Literal::Value { ref value } => self.const_to_value(value)?,
Literal::Item { def_id, substs } => {
let instance = self.resolve_associated_const(def_id, substs);
let cid = GlobalId { instance, promoted: None };
self.globals.get(&cid).expect("static/const not cached").value
}
Literal::Promoted { index } => {
let cid = GlobalId {
instance: self.frame().instance,
promoted: Some(index),
};
self.globals.get(&cid).expect("promoted not cached").value
}
};
Ok(value)
}
}
}
pub(super) fn operand_ty(&self, operand: &mir::Operand<'tcx>) -> Ty<'tcx> {
self.monomorphize(operand.ty(self.mir(), self.tcx), self.substs())
}
fn copy(&mut self, src: PrimVal, dest: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx> {
let size = self.type_size(ty)?.expect("cannot copy from an unsized type");
let align = self.type_align(ty)?;
self.memory.copy(src, dest, size, align)?;
Ok(())
}