1 //! Functions concerning immediate values and operands, and reading from operands.
2 //! All high-level functions to read from memory work on operands as sources.
4 use std::convert::TryInto;
7 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx};
9 use rustc::mir::interpret::{
10 GlobalId, AllocId, CheckInAllocMsg,
11 ConstValue, Pointer, Scalar,
12 InterpResult, InterpError, InboundsCheck,
13 sign_extend, truncate,
17 MemPlace, MPlaceTy, PlaceTy, Place,
19 pub use rustc::mir::interpret::ScalarMaybeUndef;
21 /// A `Value` represents a single immediate self-contained Rust value.
23 /// For optimization of a few very common cases, there is also a representation for a pair of
24 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
25 /// operations and fat pointers. This idea was taken from rustc's codegen.
26 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
27 /// defined on `Immediate`, and do not have to work with a `Place`.
28 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
29 pub enum Immediate<Tag=(), Id=AllocId> {
30 Scalar(ScalarMaybeUndef<Tag, Id>),
31 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
34 impl<'tcx, Tag> Immediate<Tag> {
36 pub fn from_scalar(val: Scalar<Tag>) -> Self {
37 Immediate::Scalar(ScalarMaybeUndef::Scalar(val))
43 cx: &impl HasDataLayout
45 Immediate::ScalarPair(
47 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
51 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
52 Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
56 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
58 Immediate::Scalar(val) => val,
59 Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
64 pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
65 self.to_scalar_or_undef().not_undef()
69 pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
71 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
72 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
76 /// Converts the immediate into a pointer (or a pointer-sized integer).
77 /// Throws away the second half of a ScalarPair!
79 pub fn to_scalar_ptr(self) -> InterpResult<'tcx, Scalar<Tag>> {
81 Immediate::Scalar(ptr) |
82 Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
86 /// Converts the value into its metadata.
87 /// Throws away the first half of a ScalarPair!
89 pub fn to_meta(self) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
91 Immediate::Scalar(_) => None,
92 Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
97 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
98 // as input for binary and cast operations.
99 #[derive(Copy, Clone, Debug)]
100 pub struct ImmTy<'tcx, Tag=()> {
101 pub imm: Immediate<Tag>,
102 pub layout: TyLayout<'tcx>,
105 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
106 type Target = Immediate<Tag>;
108 fn deref(&self) -> &Immediate<Tag> {
113 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
114 /// or still in memory. The latter is an optimization, to delay reading that chunk of
115 /// memory and to avoid having to store arbitrary-sized data here.
116 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
117 pub enum Operand<Tag=(), Id=AllocId> {
118 Immediate(Immediate<Tag, Id>),
119 Indirect(MemPlace<Tag, Id>),
122 impl<Tag> Operand<Tag> {
124 pub fn to_mem_place(self) -> MemPlace<Tag>
125 where Tag: ::std::fmt::Debug
128 Operand::Indirect(mplace) => mplace,
129 _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
135 pub fn to_immediate(self) -> Immediate<Tag>
136 where Tag: ::std::fmt::Debug
139 Operand::Immediate(imm) => imm,
140 _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
146 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
147 pub struct OpTy<'tcx, Tag=()> {
149 pub layout: TyLayout<'tcx>,
152 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
153 type Target = Operand<Tag>;
155 fn deref(&self) -> &Operand<Tag> {
160 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
162 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
164 op: Operand::Indirect(*mplace),
165 layout: mplace.layout
170 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
172 fn from(val: ImmTy<'tcx, Tag>) -> Self {
174 op: Operand::Immediate(val.imm),
180 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag>
183 pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
184 ImmTy { imm: Immediate::from_scalar(val), layout }
188 pub fn to_bits(self) -> InterpResult<'tcx, u128> {
189 self.to_scalar()?.to_bits(self.layout.size)
193 // Use the existing layout if given (but sanity check in debug mode),
194 // or compute the layout.
196 pub(super) fn from_known_layout<'tcx>(
197 layout: Option<TyLayout<'tcx>>,
198 compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>>
199 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
203 if cfg!(debug_assertions) {
204 let layout2 = compute()?;
205 assert_eq!(layout.details, layout2.details,
206 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
207 layout.ty, layout2.ty);
214 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> InterpretCx<'a, 'mir, 'tcx, M> {
215 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
216 /// Returns `None` if the layout does not permit loading this as a value.
217 fn try_read_immediate_from_mplace(
219 mplace: MPlaceTy<'tcx, M::PointerTag>,
220 ) -> InterpResult<'tcx, Option<Immediate<M::PointerTag>>> {
221 if mplace.layout.is_unsized() {
222 // Don't touch unsized
225 let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
227 if mplace.layout.is_zst() {
228 // Not all ZSTs have a layout we would handle below, so just short-circuit them
230 self.memory.check_align(ptr, ptr_align)?;
231 return Ok(Some(Immediate::Scalar(Scalar::zst().into())));
234 // check for integer pointers before alignment to report better errors
235 let ptr = ptr.to_ptr()?;
236 self.memory.check_align(ptr.into(), ptr_align)?;
237 match mplace.layout.abi {
238 layout::Abi::Scalar(..) => {
239 let scalar = self.memory
241 .read_scalar(self, ptr, mplace.layout.size)?;
242 Ok(Some(Immediate::Scalar(scalar)))
244 layout::Abi::ScalarPair(ref a, ref b) => {
245 let (a, b) = (&a.value, &b.value);
246 let (a_size, b_size) = (a.size(self), b.size(self));
248 let b_offset = a_size.align_to(b.align(self).abi);
249 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
250 let b_ptr = ptr.offset(b_offset, self)?;
251 let a_val = self.memory
253 .read_scalar(self, a_ptr, a_size)?;
254 let b_align = ptr_align.restrict_for_offset(b_offset);
255 self.memory.check_align(b_ptr.into(), b_align)?;
256 let b_val = self.memory
258 .read_scalar(self, b_ptr, b_size)?;
259 Ok(Some(Immediate::ScalarPair(a_val, b_val)))
265 /// Try returning an immediate for the operand.
266 /// If the layout does not permit loading this as an immediate, return where in memory
267 /// we can find the data.
268 /// Note that for a given layout, this operation will either always fail or always
269 /// succeed! Whether it succeeds depends on whether the layout can be represented
270 /// in a `Immediate`, not on which data is stored there currently.
271 pub(crate) fn try_read_immediate(
273 src: OpTy<'tcx, M::PointerTag>,
274 ) -> InterpResult<'tcx, Result<Immediate<M::PointerTag>, MemPlace<M::PointerTag>>> {
275 Ok(match src.try_as_mplace() {
277 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
287 /// Read an immediate from a place, asserting that that is possible with the given layout.
289 pub fn read_immediate(
291 op: OpTy<'tcx, M::PointerTag>
292 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
293 if let Ok(imm) = self.try_read_immediate(op)? {
294 Ok(ImmTy { imm, layout: op.layout })
296 bug!("primitive read failed for type: {:?}", op.layout.ty);
300 /// Read a scalar from a place
303 op: OpTy<'tcx, M::PointerTag>
304 ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
305 Ok(self.read_immediate(op)?.to_scalar_or_undef())
308 // Turn the MPlace into a string (must already be dereferenced!)
311 mplace: MPlaceTy<'tcx, M::PointerTag>,
312 ) -> InterpResult<'tcx, &str> {
313 let len = mplace.len(self)?;
314 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
315 let str = ::std::str::from_utf8(bytes)
316 .map_err(|err| InterpError::ValidationFailure(err.to_string()))?;
320 /// Projection functions
321 pub fn operand_field(
323 op: OpTy<'tcx, M::PointerTag>,
325 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
326 let base = match op.try_as_mplace() {
329 let field = self.mplace_field(mplace, field)?;
330 return Ok(field.into());
335 let field = field.try_into().unwrap();
336 let field_layout = op.layout.field(self, field)?;
337 if field_layout.is_zst() {
338 let immediate = Immediate::Scalar(Scalar::zst().into());
339 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
341 let offset = op.layout.fields.offset(field);
342 let immediate = match base {
343 // the field covers the entire type
344 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
345 // extract fields from types with `ScalarPair` ABI
346 Immediate::ScalarPair(a, b) => {
347 let val = if offset.bytes() == 0 { a } else { b };
348 Immediate::Scalar(val)
350 Immediate::Scalar(val) =>
351 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
353 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
356 pub fn operand_downcast(
358 op: OpTy<'tcx, M::PointerTag>,
360 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
361 // Downcasts only change the layout
362 Ok(match op.try_as_mplace() {
364 self.mplace_downcast(mplace, variant)?.into()
367 let layout = op.layout.for_variant(self, variant);
368 OpTy { layout, ..op }
373 pub fn operand_projection(
375 base: OpTy<'tcx, M::PointerTag>,
376 proj_elem: &mir::PlaceElem<'tcx>,
377 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
378 use rustc::mir::ProjectionElem::*;
379 Ok(match *proj_elem {
380 Field(field, _) => self.operand_field(base, field.index() as u64)?,
381 Downcast(_, variant) => self.operand_downcast(base, variant)?,
382 Deref => self.deref_operand(base)?.into(),
383 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
385 op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
386 // the actual index doesn't matter, so we just pick a convenient one like 0
387 layout: base.layout.field(self, 0)?,
390 // The rest should only occur as mplace, we do not use Immediates for types
391 // allowing such operations. This matches place_projection forcing an allocation.
392 let mplace = base.to_mem_place();
393 self.mplace_projection(mplace, proj_elem)?.into()
398 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
401 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
403 layout: Option<TyLayout<'tcx>>,
404 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
405 assert_ne!(local, mir::RETURN_PLACE);
406 let layout = self.layout_of_local(frame, local, layout)?;
407 let op = if layout.is_zst() {
408 // Do not read from ZST, they might not be initialized
409 Operand::Immediate(Immediate::Scalar(Scalar::zst().into()))
411 frame.locals[local].access()?
413 Ok(OpTy { op, layout })
416 /// Every place can be read from, so we can turn them into an operand
420 place: PlaceTy<'tcx, M::PointerTag>
421 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
422 let op = match *place {
423 Place::Ptr(mplace) => {
424 Operand::Indirect(mplace)
426 Place::Local { frame, local } =>
427 *self.access_local(&self.stack[frame], local, None)?
429 Ok(OpTy { op, layout: place.layout })
432 // Evaluate a place with the goal of reading from it. This lets us sometimes
433 // avoid allocations.
434 pub(super) fn eval_place_to_op(
436 mir_place: &mir::Place<'tcx>,
437 layout: Option<TyLayout<'tcx>>,
438 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
439 use rustc::mir::Place;
440 use rustc::mir::PlaceBase;
442 mir_place.iterate(|place_base, place_projection| {
443 let mut op = match place_base {
444 PlaceBase::Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
445 PlaceBase::Local(local) => {
446 // FIXME use place_projection.is_empty() when is available
447 // Do not use the layout passed in as argument if the base we are looking at
448 // here is not the entire place.
449 let layout = if let Place::Base(_) = mir_place {
455 self.access_local(self.frame(), *local, layout)?
457 PlaceBase::Static(place_static) => {
458 self.eval_static_to_mplace(place_static)?.into()
462 for proj in place_projection {
463 op = self.operand_projection(op, &proj.elem)?
466 trace!("eval_place_to_op: got {:?}", *op);
471 /// Evaluate the operand, returning a place where you can then find the data.
472 /// If you already know the layout, you can save two table lookups
473 /// by passing it in here.
476 mir_op: &mir::Operand<'tcx>,
477 layout: Option<TyLayout<'tcx>>,
478 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
479 use rustc::mir::Operand::*;
480 let op = match *mir_op {
481 // FIXME: do some more logic on `move` to invalidate the old location
484 self.eval_place_to_op(place, layout)?,
486 Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?,
488 trace!("{:?}: {:?}", mir_op, *op);
492 /// Evaluate a bunch of operands at once
493 pub(super) fn eval_operands(
495 ops: &[mir::Operand<'tcx>],
496 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
498 .map(|op| self.eval_operand(op, None))
502 // Used when the miri-engine runs into a constant and for extracting information from constants
503 // in patterns via the `const_eval` module
504 crate fn eval_const_to_op(
506 val: &'tcx ty::Const<'tcx>,
507 layout: Option<TyLayout<'tcx>>,
508 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
509 let tag_scalar = |scalar| match scalar {
510 Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
511 Scalar::Raw { data, size } => Scalar::Raw { data, size },
513 // Early-return cases.
515 ConstValue::Param(_) => return err!(TooGeneric), // FIXME(oli-obk): try to monomorphize
516 ConstValue::Unevaluated(def_id, substs) => {
517 let instance = self.resolve(def_id, substs)?;
518 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
525 // Other cases need layout.
526 let layout = from_known_layout(layout, || {
527 self.layout_of(self.monomorphize(val.ty)?)
529 let op = match val.val {
530 ConstValue::ByRef(ptr, _alloc) => {
531 // We rely on mutability being set correctly in that allocation to prevent writes
532 // where none should happen.
533 let ptr = self.tag_static_base_pointer(ptr);
534 Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi))
536 ConstValue::Scalar(x) =>
537 Operand::Immediate(Immediate::Scalar(tag_scalar(x).into())),
538 ConstValue::Slice { data, start, end } => {
539 // We rely on mutability being set correctly in `data` to prevent writes
540 // where none should happen.
541 let ptr = Pointer::new(
542 self.tcx.alloc_map.lock().create_memory_alloc(data),
543 Size::from_bytes(start as u64), // offset: `start`
545 Operand::Immediate(Immediate::new_slice(
546 self.tag_static_base_pointer(ptr).into(),
547 (end - start) as u64, // len: `end - start`
551 ConstValue::Param(..) |
552 ConstValue::Infer(..) |
553 ConstValue::Placeholder(..) |
554 ConstValue::Unevaluated(..) =>
555 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
557 Ok(OpTy { op, layout })
560 /// Read discriminant, return the runtime value as well as the variant index.
561 pub fn read_discriminant(
563 rval: OpTy<'tcx, M::PointerTag>,
564 ) -> InterpResult<'tcx, (u128, VariantIdx)> {
565 trace!("read_discriminant_value {:#?}", rval.layout);
567 let (discr_kind, discr_index) = match rval.layout.variants {
568 layout::Variants::Single { index } => {
569 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
570 index.as_u32() as u128,
572 return Ok((discr_val, index));
574 layout::Variants::Multiple { ref discr_kind, discr_index, .. } =>
575 (discr_kind, discr_index),
578 // read raw discriminant value
579 let discr_op = self.operand_field(rval, discr_index as u64)?;
580 let discr_val = self.read_immediate(discr_op)?;
581 let raw_discr = discr_val.to_scalar_or_undef();
582 trace!("discr value: {:?}", raw_discr);
584 Ok(match *discr_kind {
585 layout::DiscriminantKind::Tag => {
586 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
587 Ok(raw_discr) => raw_discr,
588 Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
590 let real_discr = if discr_val.layout.ty.is_signed() {
591 // going from layout tag type to typeck discriminant type
592 // requires first sign extending with the layout discriminant
593 let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
594 // and then zeroing with the typeck discriminant type
595 let discr_ty = rval.layout.ty
596 .ty_adt_def().expect("tagged layout corresponds to adt")
599 let size = layout::Integer::from_attr(self, discr_ty).size();
600 let truncatee = sexted as u128;
601 truncate(truncatee, size)
605 // Make sure we catch invalid discriminants
606 let index = match &rval.layout.ty.sty {
607 ty::Adt(adt, _) => adt
608 .discriminants(self.tcx.tcx)
609 .find(|(_, var)| var.val == real_discr),
610 ty::Generator(def_id, substs, _) => substs
611 .discriminants(*def_id, self.tcx.tcx)
612 .find(|(_, var)| var.val == real_discr),
613 _ => bug!("tagged layout for non-adt non-generator"),
614 }.ok_or_else(|| InterpError::InvalidDiscriminant(raw_discr.erase_tag()))?;
615 (real_discr, index.0)
617 layout::DiscriminantKind::Niche {
622 let variants_start = niche_variants.start().as_u32() as u128;
623 let variants_end = niche_variants.end().as_u32() as u128;
624 let raw_discr = raw_discr.not_undef()
625 .map_err(|_| InterpError::InvalidDiscriminant(ScalarMaybeUndef::Undef))?;
626 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
628 // The niche must be just 0 (which an inbounds pointer value never is)
629 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
630 self.memory.check_bounds_ptr(ptr, InboundsCheck::MaybeDead,
631 CheckInAllocMsg::NullPointerTest).is_ok();
633 return err!(InvalidDiscriminant(raw_discr.erase_tag().into()));
635 (dataful_variant.as_u32() as u128, dataful_variant)
638 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
639 .wrapping_add(variants_start);
640 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
641 let index = adjusted_discr as usize;
642 assert_eq!(index as u128, adjusted_discr);
643 assert!(index < rval.layout.ty
645 .expect("tagged layout for non adt")
647 (adjusted_discr, VariantIdx::from_usize(index))
649 (dataful_variant.as_u32() as u128, dataful_variant)