]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/place.rs
Rollup merge of #69810 - thekuom:test/67523-dynamic-semantics-bindings-after-at,...
[rust.git] / src / librustc_mir / interpret / place.rs
1 //! Computations on places -- field projections, going from mir::Place, and writing
2 //! into a place.
3 //! All high-level functions to write to memory work on places as destinations.
4
5 use std::convert::TryFrom;
6 use std::hash::Hash;
7
8 use rustc::mir;
9 use rustc::mir::interpret::truncate;
10 use rustc::ty::layout::{
11     self, Align, HasDataLayout, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx,
12 };
13 use rustc::ty::{self, Ty};
14 use rustc_macros::HashStable;
15
16 use super::{
17     AllocId, AllocMap, Allocation, AllocationExtra, ImmTy, Immediate, InterpCx, InterpResult,
18     LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer, PointerArithmetic, RawConst, Scalar,
19     ScalarMaybeUndef,
20 };
21
22 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
23 /// Information required for the sound usage of a `MemPlace`.
24 pub enum MemPlaceMeta<Tag = (), Id = AllocId> {
25     /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
26     Meta(Scalar<Tag, Id>),
27     /// `Sized` types or unsized `extern type`
28     None,
29     /// The address of this place may not be taken. This protects the `MemPlace` from coming from
30     /// a ZST Operand with a backing allocation and being converted to an integer address. This
31     /// should be impossible, because you can't take the address of an operand, but this is a second
32     /// protection layer ensuring that we don't mess up.
33     Poison,
34 }
35
36 impl<Tag, Id> MemPlaceMeta<Tag, Id> {
37     pub fn unwrap_meta(self) -> Scalar<Tag, Id> {
38         match self {
39             Self::Meta(s) => s,
40             Self::None | Self::Poison => {
41                 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
42             }
43         }
44     }
45     fn has_meta(self) -> bool {
46         match self {
47             Self::Meta(_) => true,
48             Self::None | Self::Poison => false,
49         }
50     }
51 }
52
53 impl<Tag> MemPlaceMeta<Tag> {
54     pub fn erase_tag(self) -> MemPlaceMeta<()> {
55         match self {
56             Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
57             Self::None => MemPlaceMeta::None,
58             Self::Poison => MemPlaceMeta::Poison,
59         }
60     }
61 }
62
63 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
64 pub struct MemPlace<Tag = (), Id = AllocId> {
65     /// A place may have an integral pointer for ZSTs, and since it might
66     /// be turned back into a reference before ever being dereferenced.
67     /// However, it may never be undef.
68     pub ptr: Scalar<Tag, Id>,
69     pub align: Align,
70     /// Metadata for unsized places. Interpretation is up to the type.
71     /// Must not be present for sized types, but can be missing for unsized types
72     /// (e.g., `extern type`).
73     pub meta: MemPlaceMeta<Tag, Id>,
74 }
75
76 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
77 pub enum Place<Tag = (), Id = AllocId> {
78     /// A place referring to a value allocated in the `Memory` system.
79     Ptr(MemPlace<Tag, Id>),
80
81     /// To support alloc-free locals, we are able to write directly to a local.
82     /// (Without that optimization, we'd just always be a `MemPlace`.)
83     Local { frame: usize, local: mir::Local },
84 }
85
86 #[derive(Copy, Clone, Debug)]
87 pub struct PlaceTy<'tcx, Tag = ()> {
88     place: Place<Tag>, // Keep this private; it helps enforce invariants.
89     pub layout: TyLayout<'tcx>,
90 }
91
92 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
93     type Target = Place<Tag>;
94     #[inline(always)]
95     fn deref(&self) -> &Place<Tag> {
96         &self.place
97     }
98 }
99
100 /// A MemPlace with its layout. Constructing it is only possible in this module.
101 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
102 pub struct MPlaceTy<'tcx, Tag = ()> {
103     mplace: MemPlace<Tag>,
104     pub layout: TyLayout<'tcx>,
105 }
106
107 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
108     type Target = MemPlace<Tag>;
109     #[inline(always)]
110     fn deref(&self) -> &MemPlace<Tag> {
111         &self.mplace
112     }
113 }
114
115 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
116     #[inline(always)]
117     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
118         PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
119     }
120 }
121
122 impl<Tag> MemPlace<Tag> {
123     /// Replace ptr tag, maintain vtable tag (if any)
124     #[inline]
125     pub fn replace_tag(self, new_tag: Tag) -> Self {
126         MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
127     }
128
129     #[inline]
130     pub fn erase_tag(self) -> MemPlace {
131         MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
132     }
133
134     #[inline(always)]
135     fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
136         MemPlace { ptr, align, meta: MemPlaceMeta::None }
137     }
138
139     /// Produces a Place that will error if attempted to be read from or written to
140     #[inline(always)]
141     fn null(cx: &impl HasDataLayout) -> Self {
142         Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
143     }
144
145     #[inline(always)]
146     pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
147         Self::from_scalar_ptr(ptr.into(), align)
148     }
149
150     /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
151     /// This is the inverse of `ref_to_mplace`.
152     #[inline(always)]
153     pub fn to_ref(self) -> Immediate<Tag> {
154         match self.meta {
155             MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
156             MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
157             MemPlaceMeta::Poison => bug!(
158                 "MPlaceTy::dangling may never be used to produce a \
159                 place that will have the address of its pointee taken"
160             ),
161         }
162     }
163
164     pub fn offset(
165         self,
166         offset: Size,
167         meta: MemPlaceMeta<Tag>,
168         cx: &impl HasDataLayout,
169     ) -> InterpResult<'tcx, Self> {
170         Ok(MemPlace {
171             ptr: self.ptr.ptr_offset(offset, cx)?,
172             align: self.align.restrict_for_offset(offset),
173             meta,
174         })
175     }
176 }
177
178 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
179     /// Produces a MemPlace that works for ZST but nothing else
180     #[inline]
181     pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
182         let align = layout.align.abi;
183         let ptr = Scalar::from_uint(align.bytes(), cx.pointer_size());
184         // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
185         MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
186     }
187
188     /// Replace ptr tag, maintain vtable tag (if any)
189     #[inline]
190     pub fn replace_tag(self, new_tag: Tag) -> Self {
191         MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
192     }
193
194     #[inline]
195     pub fn offset(
196         self,
197         offset: Size,
198         meta: MemPlaceMeta<Tag>,
199         layout: TyLayout<'tcx>,
200         cx: &impl HasDataLayout,
201     ) -> InterpResult<'tcx, Self> {
202         Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
203     }
204
205     #[inline]
206     fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
207         MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
208     }
209
210     #[inline]
211     pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
212         if self.layout.is_unsized() {
213             // We need to consult `meta` metadata
214             match self.layout.ty.kind {
215                 ty::Slice(..) | ty::Str => {
216                     return self.mplace.meta.unwrap_meta().to_machine_usize(cx);
217                 }
218                 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
219             }
220         } else {
221             // Go through the layout.  There are lots of types that support a length,
222             // e.g., SIMD types.
223             match self.layout.fields {
224                 layout::FieldPlacement::Array { count, .. } => Ok(count),
225                 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
226             }
227         }
228     }
229
230     #[inline]
231     pub(super) fn vtable(self) -> Scalar<Tag> {
232         match self.layout.ty.kind {
233             ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
234             _ => bug!("vtable not supported on type {:?}", self.layout.ty),
235         }
236     }
237 }
238
239 // These are defined here because they produce a place.
240 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
241     #[inline(always)]
242     /// Note: do not call `as_ref` on the resulting place. This function should only be used to
243     /// read from the resulting mplace, not to get its address back.
244     pub fn try_as_mplace(
245         self,
246         cx: &impl HasDataLayout,
247     ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
248         match *self {
249             Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
250             Operand::Immediate(_) if self.layout.is_zst() => {
251                 Ok(MPlaceTy::dangling(self.layout, cx))
252             }
253             Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
254         }
255     }
256
257     #[inline(always)]
258     /// Note: do not call `as_ref` on the resulting place. This function should only be used to
259     /// read from the resulting mplace, not to get its address back.
260     pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
261         self.try_as_mplace(cx).unwrap()
262     }
263 }
264
265 impl<Tag: ::std::fmt::Debug> Place<Tag> {
266     /// Produces a Place that will error if attempted to be read from or written to
267     #[inline(always)]
268     fn null(cx: &impl HasDataLayout) -> Self {
269         Place::Ptr(MemPlace::null(cx))
270     }
271
272     #[inline]
273     pub fn assert_mem_place(self) -> MemPlace<Tag> {
274         match self {
275             Place::Ptr(mplace) => mplace,
276             _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
277         }
278     }
279 }
280
281 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
282     #[inline]
283     pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
284         MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
285     }
286 }
287
288 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
289 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
290 where
291     // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
292     Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
293     M: Machine<'mir, 'tcx, PointerTag = Tag>,
294     // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
295     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
296     M::AllocExtra: AllocationExtra<Tag>,
297 {
298     /// Take a value, which represents a (thin or wide) reference, and make it a place.
299     /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
300     ///
301     /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
302     /// want to ever use the place for memory access!
303     /// Generally prefer `deref_operand`.
304     pub fn ref_to_mplace(
305         &self,
306         val: ImmTy<'tcx, M::PointerTag>,
307     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
308         let pointee_type =
309             val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
310         let layout = self.layout_of(pointee_type)?;
311         let (ptr, meta) = match *val {
312             Immediate::Scalar(ptr) => (ptr.not_undef()?, MemPlaceMeta::None),
313             Immediate::ScalarPair(ptr, meta) => {
314                 (ptr.not_undef()?, MemPlaceMeta::Meta(meta.not_undef()?))
315             }
316         };
317
318         let mplace = MemPlace {
319             ptr,
320             // We could use the run-time alignment here. For now, we do not, because
321             // the point of tracking the alignment here is to make sure that the *static*
322             // alignment information emitted with the loads is correct. The run-time
323             // alignment can only be more restrictive.
324             align: layout.align.abi,
325             meta,
326         };
327         Ok(MPlaceTy { mplace, layout })
328     }
329
330     /// Take an operand, representing a pointer, and dereference it to a place -- that
331     /// will always be a MemPlace.  Lives in `place.rs` because it creates a place.
332     pub fn deref_operand(
333         &self,
334         src: OpTy<'tcx, M::PointerTag>,
335     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
336         let val = self.read_immediate(src)?;
337         trace!("deref to {} on {:?}", val.layout.ty, *val);
338         let place = self.ref_to_mplace(val)?;
339         self.mplace_access_checked(place)
340     }
341
342     /// Check if the given place is good for memory access with the given
343     /// size, falling back to the layout's size if `None` (in the latter case,
344     /// this must be a statically sized type).
345     ///
346     /// On success, returns `None` for zero-sized accesses (where nothing else is
347     /// left to do) and a `Pointer` to use for the actual access otherwise.
348     #[inline]
349     pub(super) fn check_mplace_access(
350         &self,
351         place: MPlaceTy<'tcx, M::PointerTag>,
352         size: Option<Size>,
353     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
354         let size = size.unwrap_or_else(|| {
355             assert!(!place.layout.is_unsized());
356             assert!(!place.meta.has_meta());
357             place.layout.size
358         });
359         self.memory.check_ptr_access(place.ptr, size, place.align)
360     }
361
362     /// Return the "access-checked" version of this `MPlace`, where for non-ZST
363     /// this is definitely a `Pointer`.
364     pub fn mplace_access_checked(
365         &self,
366         mut place: MPlaceTy<'tcx, M::PointerTag>,
367     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
368         let (size, align) = self
369             .size_and_align_of_mplace(place)?
370             .unwrap_or((place.layout.size, place.layout.align.abi));
371         assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
372         place.mplace.align = align; // maximally strict checking
373         // When dereferencing a pointer, it must be non-NULL, aligned, and live.
374         if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
375             place.mplace.ptr = ptr.into();
376         }
377         Ok(place)
378     }
379
380     /// Force `place.ptr` to a `Pointer`.
381     /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
382     pub(super) fn force_mplace_ptr(
383         &self,
384         mut place: MPlaceTy<'tcx, M::PointerTag>,
385     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
386         place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
387         Ok(place)
388     }
389
390     /// Offset a pointer to project to a field. Unlike `place_field`, this is always
391     /// possible without allocating, so it can take `&self`. Also return the field's layout.
392     /// This supports both struct and array fields.
393     #[inline(always)]
394     pub fn mplace_field(
395         &self,
396         base: MPlaceTy<'tcx, M::PointerTag>,
397         field: u64,
398     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
399         // Not using the layout method because we want to compute on u64
400         let offset = match base.layout.fields {
401             layout::FieldPlacement::Arbitrary { ref offsets, .. } => {
402                 offsets[usize::try_from(field).unwrap()]
403             }
404             layout::FieldPlacement::Array { stride, .. } => {
405                 let len = base.len(self)?;
406                 if field >= len {
407                     // This can only be reached in ConstProp and non-rustc-MIR.
408                     throw_ub!(BoundsCheckFailed { len, index: field });
409                 }
410                 stride * field
411             }
412             layout::FieldPlacement::Union(count) => {
413                 // This is a narrow bug-fix for rust-lang/rust#69191: if we are
414                 // trying to access absent field of uninhabited variant, then
415                 // signal UB (but don't ICE the compiler).
416                 // FIXME temporary hack to work around incoherence between
417                 // layout computation and MIR building
418                 if field >= count as u64 && base.layout.abi == layout::Abi::Uninhabited {
419                     throw_ub!(Unreachable);
420                 }
421                 assert!(
422                     field < count as u64,
423                     "Tried to access field {} of union {:#?} with {} fields",
424                     field,
425                     base.layout,
426                     count
427                 );
428                 // Offset is always 0
429                 Size::from_bytes(0)
430             }
431         };
432         // the only way conversion can fail if is this is an array (otherwise we already panicked
433         // above). In that case, all fields are equal.
434         let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
435
436         // Offset may need adjustment for unsized fields.
437         let (meta, offset) = if field_layout.is_unsized() {
438             // Re-use parent metadata to determine dynamic field layout.
439             // With custom DSTS, this *will* execute user-defined code, but the same
440             // happens at run-time so that's okay.
441             let align = match self.size_and_align_of(base.meta, field_layout)? {
442                 Some((_, align)) => align,
443                 None if offset == Size::ZERO => {
444                     // An extern type at offset 0, we fall back to its static alignment.
445                     // FIXME: Once we have made decisions for how to handle size and alignment
446                     // of `extern type`, this should be adapted.  It is just a temporary hack
447                     // to get some code to work that probably ought to work.
448                     field_layout.align.abi
449                 }
450                 None => bug!("Cannot compute offset for extern type field at non-0 offset"),
451             };
452             (base.meta, offset.align_to(align))
453         } else {
454             // base.meta could be present; we might be accessing a sized field of an unsized
455             // struct.
456             (MemPlaceMeta::None, offset)
457         };
458
459         // We do not look at `base.layout.align` nor `field_layout.align`, unlike
460         // codegen -- mostly to see if we can get away with that
461         base.offset(offset, meta, field_layout, self)
462     }
463
464     // Iterates over all fields of an array. Much more efficient than doing the
465     // same by repeatedly calling `mplace_array`.
466     pub(super) fn mplace_array_fields(
467         &self,
468         base: MPlaceTy<'tcx, Tag>,
469     ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
470     {
471         let len = base.len(self)?; // also asserts that we have a type where this makes sense
472         let stride = match base.layout.fields {
473             layout::FieldPlacement::Array { stride, .. } => stride,
474             _ => bug!("mplace_array_fields: expected an array layout"),
475         };
476         let layout = base.layout.field(self, 0)?;
477         let dl = &self.tcx.data_layout;
478         Ok((0..len).map(move |i| base.offset(i * stride, MemPlaceMeta::None, layout, dl)))
479     }
480
481     fn mplace_subslice(
482         &self,
483         base: MPlaceTy<'tcx, M::PointerTag>,
484         from: u64,
485         to: u64,
486         from_end: bool,
487     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
488         let len = base.len(self)?; // also asserts that we have a type where this makes sense
489         let actual_to = if from_end {
490             if from + to > len {
491                 // This can only be reached in ConstProp and non-rustc-MIR.
492                 throw_ub!(BoundsCheckFailed { len: len as u64, index: from as u64 + to as u64 });
493             }
494             len - to
495         } else {
496             to
497         };
498
499         // Not using layout method because that works with usize, and does not work with slices
500         // (that have count 0 in their layout).
501         let from_offset = match base.layout.fields {
502             layout::FieldPlacement::Array { stride, .. } => stride * from,
503             _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
504         };
505
506         // Compute meta and new layout
507         let inner_len = actual_to - from;
508         let (meta, ty) = match base.layout.ty.kind {
509             // It is not nice to match on the type, but that seems to be the only way to
510             // implement this.
511             ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
512             ty::Slice(..) => {
513                 let len = Scalar::from_uint(inner_len, self.pointer_size());
514                 (MemPlaceMeta::Meta(len), base.layout.ty)
515             }
516             _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
517         };
518         let layout = self.layout_of(ty)?;
519         base.offset(from_offset, meta, layout, self)
520     }
521
522     pub(super) fn mplace_downcast(
523         &self,
524         base: MPlaceTy<'tcx, M::PointerTag>,
525         variant: VariantIdx,
526     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
527         // Downcasts only change the layout
528         assert!(!base.meta.has_meta());
529         Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
530     }
531
532     /// Project into an mplace
533     pub(super) fn mplace_projection(
534         &self,
535         base: MPlaceTy<'tcx, M::PointerTag>,
536         proj_elem: &mir::PlaceElem<'tcx>,
537     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
538         use rustc::mir::ProjectionElem::*;
539         Ok(match *proj_elem {
540             Field(field, _) => self.mplace_field(base, field.index() as u64)?,
541             Downcast(_, variant) => self.mplace_downcast(base, variant)?,
542             Deref => self.deref_operand(base.into())?,
543
544             Index(local) => {
545                 let layout = self.layout_of(self.tcx.types.usize)?;
546                 let n = self.access_local(self.frame(), local, Some(layout))?;
547                 let n = self.read_scalar(n)?;
548                 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
549                 self.mplace_field(base, u64::try_from(n).unwrap())?
550             }
551
552             ConstantIndex { offset, min_length, from_end } => {
553                 let n = base.len(self)?;
554                 if n < min_length as u64 {
555                     // This can only be reached in ConstProp and non-rustc-MIR.
556                     throw_ub!(BoundsCheckFailed { len: min_length as u64, index: n as u64 });
557                 }
558
559                 let index = if from_end {
560                     assert!(0 < offset && offset - 1 < min_length);
561                     n - u64::from(offset)
562                 } else {
563                     assert!(offset < min_length);
564                     u64::from(offset)
565                 };
566
567                 self.mplace_field(base, index)?
568             }
569
570             Subslice { from, to, from_end } => {
571                 self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
572             }
573         })
574     }
575
576     /// Gets the place of a field inside the place, and also the field's type.
577     /// Just a convenience function, but used quite a bit.
578     /// This is the only projection that might have a side-effect: We cannot project
579     /// into the field of a local `ScalarPair`, we have to first allocate it.
580     pub fn place_field(
581         &mut self,
582         base: PlaceTy<'tcx, M::PointerTag>,
583         field: u64,
584     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
585         // FIXME: We could try to be smarter and avoid allocation for fields that span the
586         // entire place.
587         let mplace = self.force_allocation(base)?;
588         Ok(self.mplace_field(mplace, field)?.into())
589     }
590
591     pub fn place_downcast(
592         &self,
593         base: PlaceTy<'tcx, M::PointerTag>,
594         variant: VariantIdx,
595     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
596         // Downcast just changes the layout
597         Ok(match base.place {
598             Place::Ptr(mplace) => {
599                 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
600             }
601             Place::Local { .. } => {
602                 let layout = base.layout.for_variant(self, variant);
603                 PlaceTy { layout, ..base }
604             }
605         })
606     }
607
608     /// Projects into a place.
609     pub fn place_projection(
610         &mut self,
611         base: PlaceTy<'tcx, M::PointerTag>,
612         proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
613     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
614         use rustc::mir::ProjectionElem::*;
615         Ok(match *proj_elem {
616             Field(field, _) => self.place_field(base, field.index() as u64)?,
617             Downcast(_, variant) => self.place_downcast(base, variant)?,
618             Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
619             // For the other variants, we have to force an allocation.
620             // This matches `operand_projection`.
621             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
622                 let mplace = self.force_allocation(base)?;
623                 self.mplace_projection(mplace, proj_elem)?.into()
624             }
625         })
626     }
627
628     /// Computes a place. You should only use this if you intend to write into this
629     /// place; for reading, a more efficient alternative is `eval_place_for_read`.
630     pub fn eval_place(
631         &mut self,
632         place: &mir::Place<'tcx>,
633     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
634         let mut place_ty = match place.local {
635             mir::RETURN_PLACE => {
636                 // `return_place` has the *caller* layout, but we want to use our
637                 // `layout to verify our assumption. The caller will validate
638                 // their layout on return.
639                 PlaceTy {
640                     place: match self.frame().return_place {
641                         Some(p) => *p,
642                         // Even if we don't have a return place, we sometimes need to
643                         // create this place, but any attempt to read from / write to it
644                         // (even a ZST read/write) needs to error, so let us make this
645                         // a NULL place.
646                         //
647                         // FIXME: Ideally we'd make sure that the place projections also
648                         // bail out.
649                         None => Place::null(&*self),
650                     },
651                     layout: self.layout_of(self.subst_from_frame_and_normalize_erasing_regions(
652                         self.frame().body.return_ty(),
653                     ))?,
654                 }
655             }
656             local => PlaceTy {
657                 // This works even for dead/uninitialized locals; we check further when writing
658                 place: Place::Local { frame: self.cur_frame(), local },
659                 layout: self.layout_of_local(self.frame(), local, None)?,
660             },
661         };
662
663         for elem in place.projection.iter() {
664             place_ty = self.place_projection(place_ty, elem)?
665         }
666
667         self.dump_place(place_ty.place);
668         Ok(place_ty)
669     }
670
671     /// Write a scalar to a place
672     #[inline(always)]
673     pub fn write_scalar(
674         &mut self,
675         val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
676         dest: PlaceTy<'tcx, M::PointerTag>,
677     ) -> InterpResult<'tcx> {
678         self.write_immediate(Immediate::Scalar(val.into()), dest)
679     }
680
681     /// Write an immediate to a place
682     #[inline(always)]
683     pub fn write_immediate(
684         &mut self,
685         src: Immediate<M::PointerTag>,
686         dest: PlaceTy<'tcx, M::PointerTag>,
687     ) -> InterpResult<'tcx> {
688         self.write_immediate_no_validate(src, dest)?;
689
690         if M::enforce_validity(self) {
691             // Data got changed, better make sure it matches the type!
692             self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
693         }
694
695         Ok(())
696     }
697
698     /// Write an `Immediate` to memory.
699     #[inline(always)]
700     pub fn write_immediate_to_mplace(
701         &mut self,
702         src: Immediate<M::PointerTag>,
703         dest: MPlaceTy<'tcx, M::PointerTag>,
704     ) -> InterpResult<'tcx> {
705         self.write_immediate_to_mplace_no_validate(src, dest)?;
706
707         if M::enforce_validity(self) {
708             // Data got changed, better make sure it matches the type!
709             self.validate_operand(dest.into(), vec![], None)?;
710         }
711
712         Ok(())
713     }
714
715     /// Write an immediate to a place.
716     /// If you use this you are responsible for validating that things got copied at the
717     /// right type.
718     fn write_immediate_no_validate(
719         &mut self,
720         src: Immediate<M::PointerTag>,
721         dest: PlaceTy<'tcx, M::PointerTag>,
722     ) -> InterpResult<'tcx> {
723         if cfg!(debug_assertions) {
724             // This is a very common path, avoid some checks in release mode
725             assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
726             match src {
727                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) => assert_eq!(
728                     self.pointer_size(),
729                     dest.layout.size,
730                     "Size mismatch when writing pointer"
731                 ),
732                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) => {
733                     assert_eq!(
734                         Size::from_bytes(size.into()),
735                         dest.layout.size,
736                         "Size mismatch when writing bits"
737                     )
738                 }
739                 Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
740                 Immediate::ScalarPair(_, _) => {
741                     // FIXME: Can we check anything here?
742                 }
743             }
744         }
745         trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
746
747         // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
748         // but not factored as a separate function.
749         let mplace = match dest.place {
750             Place::Local { frame, local } => {
751                 match self.stack[frame].locals[local].access_mut()? {
752                     Ok(local) => {
753                         // Local can be updated in-place.
754                         *local = LocalValue::Live(Operand::Immediate(src));
755                         return Ok(());
756                     }
757                     Err(mplace) => {
758                         // The local is in memory, go on below.
759                         mplace
760                     }
761                 }
762             }
763             Place::Ptr(mplace) => mplace, // already referring to memory
764         };
765         let dest = MPlaceTy { mplace, layout: dest.layout };
766
767         // This is already in memory, write there.
768         self.write_immediate_to_mplace_no_validate(src, dest)
769     }
770
771     /// Write an immediate to memory.
772     /// If you use this you are responsible for validating that things got copied at the
773     /// right type.
774     fn write_immediate_to_mplace_no_validate(
775         &mut self,
776         value: Immediate<M::PointerTag>,
777         dest: MPlaceTy<'tcx, M::PointerTag>,
778     ) -> InterpResult<'tcx> {
779         // Note that it is really important that the type here is the right one, and matches the
780         // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
781         // to handle padding properly, which is only correct if we never look at this data with the
782         // wrong type.
783
784         // Invalid places are a thing: the return place of a diverging function
785         let ptr = match self.check_mplace_access(dest, None)? {
786             Some(ptr) => ptr,
787             None => return Ok(()), // zero-sized access
788         };
789
790         let tcx = &*self.tcx;
791         // FIXME: We should check that there are dest.layout.size many bytes available in
792         // memory.  The code below is not sufficient, with enough padding it might not
793         // cover all the bytes!
794         match value {
795             Immediate::Scalar(scalar) => {
796                 match dest.layout.abi {
797                     layout::Abi::Scalar(_) => {} // fine
798                     _ => {
799                         bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
800                     }
801                 }
802                 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
803                     tcx,
804                     ptr,
805                     scalar,
806                     dest.layout.size,
807                 )
808             }
809             Immediate::ScalarPair(a_val, b_val) => {
810                 // We checked `ptr_align` above, so all fields will have the alignment they need.
811                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
812                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
813                 let (a, b) = match dest.layout.abi {
814                     layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
815                     _ => bug!(
816                         "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
817                         dest.layout
818                     ),
819                 };
820                 let (a_size, b_size) = (a.size(self), b.size(self));
821                 let b_offset = a_size.align_to(b.align(self).abi);
822                 let b_ptr = ptr.offset(b_offset, self)?;
823
824                 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
825                 // but that does not work: We could be a newtype around a pair, then the
826                 // fields do not match the `ScalarPair` components.
827
828                 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
829                 self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
830             }
831         }
832     }
833
834     /// Copies the data from an operand to a place. This does not support transmuting!
835     /// Use `copy_op_transmute` if the layouts could disagree.
836     #[inline(always)]
837     pub fn copy_op(
838         &mut self,
839         src: OpTy<'tcx, M::PointerTag>,
840         dest: PlaceTy<'tcx, M::PointerTag>,
841     ) -> InterpResult<'tcx> {
842         self.copy_op_no_validate(src, dest)?;
843
844         if M::enforce_validity(self) {
845             // Data got changed, better make sure it matches the type!
846             self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
847         }
848
849         Ok(())
850     }
851
852     /// Copies the data from an operand to a place. This does not support transmuting!
853     /// Use `copy_op_transmute` if the layouts could disagree.
854     /// Also, if you use this you are responsible for validating that things get copied at the
855     /// right type.
856     fn copy_op_no_validate(
857         &mut self,
858         src: OpTy<'tcx, M::PointerTag>,
859         dest: PlaceTy<'tcx, M::PointerTag>,
860     ) -> InterpResult<'tcx> {
861         // We do NOT compare the types for equality, because well-typed code can
862         // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
863         assert!(
864             src.layout.details == dest.layout.details,
865             "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}",
866             src,
867             dest
868         );
869
870         // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
871         let src = match self.try_read_immediate(src)? {
872             Ok(src_val) => {
873                 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
874                 // Yay, we got a value that we can write directly.
875                 // FIXME: Add a check to make sure that if `src` is indirect,
876                 // it does not overlap with `dest`.
877                 return self.write_immediate_no_validate(*src_val, dest);
878             }
879             Err(mplace) => mplace,
880         };
881         // Slow path, this does not fit into an immediate. Just memcpy.
882         trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
883
884         // This interprets `src.meta` with the `dest` local's layout, if an unsized local
885         // is being initialized!
886         let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
887         let size = size.unwrap_or_else(|| {
888             assert!(
889                 !dest.layout.is_unsized(),
890                 "Cannot copy into already initialized unsized place"
891             );
892             dest.layout.size
893         });
894         assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
895
896         let src = self
897             .check_mplace_access(src, Some(size))
898             .expect("places should be checked on creation");
899         let dest = self
900             .check_mplace_access(dest, Some(size))
901             .expect("places should be checked on creation");
902         let (src_ptr, dest_ptr) = match (src, dest) {
903             (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
904             (None, None) => return Ok(()), // zero-sized copy
905             _ => bug!("The pointers should both be Some or both None"),
906         };
907
908         self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
909     }
910
911     /// Copies the data from an operand to a place. The layouts may disagree, but they must
912     /// have the same size.
913     pub fn copy_op_transmute(
914         &mut self,
915         src: OpTy<'tcx, M::PointerTag>,
916         dest: PlaceTy<'tcx, M::PointerTag>,
917     ) -> InterpResult<'tcx> {
918         if src.layout.details == dest.layout.details {
919             // Fast path: Just use normal `copy_op`
920             return self.copy_op(src, dest);
921         }
922         // We still require the sizes to match.
923         if src.layout.size != dest.layout.size {
924             // FIXME: This should be an assert instead of an error, but if we transmute within an
925             // array length computation, `typeck` may not have yet been run and errored out. In fact
926             // most likey we *are* running `typeck` right now. Investigate whether we can bail out
927             // on `typeck_tables().has_errors` at all const eval entry points.
928             debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
929             throw_unsup!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
930         }
931         // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
932         // to avoid that here.
933         assert!(
934             !src.layout.is_unsized() && !dest.layout.is_unsized(),
935             "Cannot transmute unsized data"
936         );
937
938         // The hard case is `ScalarPair`.  `src` is already read from memory in this case,
939         // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
940         // We have to write them to `dest` at the offsets they were *read at*, which is
941         // not necessarily the same as the offsets in `dest.layout`!
942         // Hence we do the copy with the source layout on both sides.  We also make sure to write
943         // into memory, because if `dest` is a local we would not even have a way to write
944         // at the `src` offsets; the fact that we came from a different layout would
945         // just be lost.
946         let dest = self.force_allocation(dest)?;
947         self.copy_op_no_validate(
948             src,
949             PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
950         )?;
951
952         if M::enforce_validity(self) {
953             // Data got changed, better make sure it matches the type!
954             self.validate_operand(dest.into(), vec![], None)?;
955         }
956
957         Ok(())
958     }
959
960     /// Ensures that a place is in memory, and returns where it is.
961     /// If the place currently refers to a local that doesn't yet have a matching allocation,
962     /// create such an allocation.
963     /// This is essentially `force_to_memplace`.
964     ///
965     /// This supports unsized types and returns the computed size to avoid some
966     /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
967     /// version.
968     pub fn force_allocation_maybe_sized(
969         &mut self,
970         place: PlaceTy<'tcx, M::PointerTag>,
971         meta: MemPlaceMeta<M::PointerTag>,
972     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
973         let (mplace, size) = match place.place {
974             Place::Local { frame, local } => {
975                 match self.stack[frame].locals[local].access_mut()? {
976                     Ok(&mut local_val) => {
977                         // We need to make an allocation.
978
979                         // We need the layout of the local.  We can NOT use the layout we got,
980                         // that might e.g., be an inner field of a struct with `Scalar` layout,
981                         // that has different alignment than the outer field.
982                         let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
983                         // We also need to support unsized types, and hence cannot use `allocate`.
984                         let (size, align) = self
985                             .size_and_align_of(meta, local_layout)?
986                             .expect("Cannot allocate for non-dyn-sized type");
987                         let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
988                         let mplace = MemPlace { ptr: ptr.into(), align, meta };
989                         if let LocalValue::Live(Operand::Immediate(value)) = local_val {
990                             // Preserve old value.
991                             // We don't have to validate as we can assume the local
992                             // was already valid for its type.
993                             let mplace = MPlaceTy { mplace, layout: local_layout };
994                             self.write_immediate_to_mplace_no_validate(value, mplace)?;
995                         }
996                         // Now we can call `access_mut` again, asserting it goes well,
997                         // and actually overwrite things.
998                         *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
999                             LocalValue::Live(Operand::Indirect(mplace));
1000                         (mplace, Some(size))
1001                     }
1002                     Err(mplace) => (mplace, None), // this already was an indirect local
1003                 }
1004             }
1005             Place::Ptr(mplace) => (mplace, None),
1006         };
1007         // Return with the original layout, so that the caller can go on
1008         Ok((MPlaceTy { mplace, layout: place.layout }, size))
1009     }
1010
1011     #[inline(always)]
1012     pub fn force_allocation(
1013         &mut self,
1014         place: PlaceTy<'tcx, M::PointerTag>,
1015     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1016         Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
1017     }
1018
1019     pub fn allocate(
1020         &mut self,
1021         layout: TyLayout<'tcx>,
1022         kind: MemoryKind<M::MemoryKinds>,
1023     ) -> MPlaceTy<'tcx, M::PointerTag> {
1024         let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1025         MPlaceTy::from_aligned_ptr(ptr, layout)
1026     }
1027
1028     /// Returns a wide MPlace.
1029     pub fn allocate_str(
1030         &mut self,
1031         str: &str,
1032         kind: MemoryKind<M::MemoryKinds>,
1033     ) -> MPlaceTy<'tcx, M::PointerTag> {
1034         let ptr = self.memory.allocate_static_bytes(str.as_bytes(), kind);
1035         let meta = Scalar::from_uint(str.len() as u128, self.pointer_size());
1036         let mplace = MemPlace {
1037             ptr: ptr.into(),
1038             align: Align::from_bytes(1).unwrap(),
1039             meta: MemPlaceMeta::Meta(meta),
1040         };
1041
1042         let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
1043         MPlaceTy { mplace, layout }
1044     }
1045
1046     pub fn write_discriminant_index(
1047         &mut self,
1048         variant_index: VariantIdx,
1049         dest: PlaceTy<'tcx, M::PointerTag>,
1050     ) -> InterpResult<'tcx> {
1051         // Layout computation excludes uninhabited variants from consideration
1052         // therefore there's no way to represent those variants in the given layout.
1053         if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
1054             throw_ub!(Unreachable);
1055         }
1056
1057         match dest.layout.variants {
1058             layout::Variants::Single { index } => {
1059                 assert_eq!(index, variant_index);
1060             }
1061             layout::Variants::Multiple {
1062                 discr_kind: layout::DiscriminantKind::Tag,
1063                 discr: ref discr_layout,
1064                 discr_index,
1065                 ..
1066             } => {
1067                 // No need to validate that the discriminant here because the
1068                 // `TyLayout::for_variant()` call earlier already checks the variant is valid.
1069
1070                 let discr_val =
1071                     dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1072
1073                 // raw discriminants for enums are isize or bigger during
1074                 // their computation, but the in-memory tag is the smallest possible
1075                 // representation
1076                 let size = discr_layout.value.size(self);
1077                 let discr_val = truncate(discr_val, size);
1078
1079                 let discr_dest = self.place_field(dest, discr_index as u64)?;
1080                 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1081             }
1082             layout::Variants::Multiple {
1083                 discr_kind:
1084                     layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1085                 discr: ref discr_layout,
1086                 discr_index,
1087                 ..
1088             } => {
1089                 // No need to validate that the discriminant here because the
1090                 // `TyLayout::for_variant()` call earlier already checks the variant is valid.
1091
1092                 if variant_index != dataful_variant {
1093                     let variants_start = niche_variants.start().as_u32();
1094                     let variant_index_relative = variant_index
1095                         .as_u32()
1096                         .checked_sub(variants_start)
1097                         .expect("overflow computing relative variant idx");
1098                     // We need to use machine arithmetic when taking into account `niche_start`:
1099                     // discr_val = variant_index_relative + niche_start_val
1100                     let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1101                     let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1102                     let variant_index_relative_val =
1103                         ImmTy::from_uint(variant_index_relative, discr_layout);
1104                     let discr_val = self.binary_op(
1105                         mir::BinOp::Add,
1106                         variant_index_relative_val,
1107                         niche_start_val,
1108                     )?;
1109                     // Write result.
1110                     let niche_dest = self.place_field(dest, discr_index as u64)?;
1111                     self.write_immediate(*discr_val, niche_dest)?;
1112                 }
1113             }
1114         }
1115
1116         Ok(())
1117     }
1118
1119     pub fn raw_const_to_mplace(
1120         &self,
1121         raw: RawConst<'tcx>,
1122     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1123         // This must be an allocation in `tcx`
1124         assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1125         let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1126         let layout = self.layout_of(raw.ty)?;
1127         Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1128     }
1129
1130     /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1131     /// Also return some more information so drop doesn't have to run the same code twice.
1132     pub(super) fn unpack_dyn_trait(
1133         &self,
1134         mplace: MPlaceTy<'tcx, M::PointerTag>,
1135     ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1136         let vtable = mplace.vtable(); // also sanity checks the type
1137         let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1138         let layout = self.layout_of(ty)?;
1139
1140         // More sanity checks
1141         if cfg!(debug_assertions) {
1142             let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1143             assert_eq!(size, layout.size);
1144             // only ABI alignment is preserved
1145             assert_eq!(align, layout.align.abi);
1146         }
1147
1148         let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1149         Ok((instance, mplace))
1150     }
1151 }