]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
Auto merge of #802 - RalfJung:machine, r=RalfJung
[rust.git] / src / helpers.rs
1 use std::mem;
2
3 use rustc::ty::{self, layout::{self, Size}};
4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
5
6 use crate::*;
7
8 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
9
10 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
11     /// Gets an instance for a path.
12     fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
13         let this = self.eval_context_ref();
14         this.tcx
15             .crates()
16             .iter()
17             .find(|&&krate| this.tcx.original_crate_name(krate).as_str() == path[0])
18             .and_then(|krate| {
19                 let krate = DefId {
20                     krate: *krate,
21                     index: CRATE_DEF_INDEX,
22                 };
23                 let mut items = this.tcx.item_children(krate);
24                 let mut path_it = path.iter().skip(1).peekable();
25
26                 while let Some(segment) = path_it.next() {
27                     for item in mem::replace(&mut items, Default::default()).iter() {
28                         if item.ident.name.as_str() == *segment {
29                             if path_it.peek().is_none() {
30                                 return Some(ty::Instance::mono(this.tcx.tcx, item.res.def_id()));
31                             }
32
33                             items = this.tcx.item_children(item.res.def_id());
34                             break;
35                         }
36                     }
37                 }
38                 None
39             })
40             .ok_or_else(|| {
41                 let path = path.iter().map(|&s| s.to_owned()).collect();
42                 InterpError::PathNotFound(path).into()
43             })
44     }
45
46     /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
47     /// will be true if this is frozen, false if this is in an `UnsafeCell`.
48     fn visit_freeze_sensitive(
49         &self,
50         place: MPlaceTy<'tcx, Tag>,
51         size: Size,
52         mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
53     ) -> InterpResult<'tcx> {
54         let this = self.eval_context_ref();
55         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
56         debug_assert_eq!(size,
57             this.size_and_align_of_mplace(place)?
58             .map(|(size, _)| size)
59             .unwrap_or_else(|| place.layout.size)
60         );
61         // Store how far we proceeded into the place so far. Everything to the left of
62         // this offset has already been handled, in the sense that the frozen parts
63         // have had `action` called on them.
64         let mut end_ptr = place.ptr;
65         // Called when we detected an `UnsafeCell` at the given offset and size.
66         // Calls `action` and advances `end_ptr`.
67         let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
68             if unsafe_cell_size != Size::ZERO {
69                 debug_assert_eq!(unsafe_cell_ptr.to_ptr().unwrap().alloc_id,
70                     end_ptr.to_ptr().unwrap().alloc_id);
71                 debug_assert_eq!(unsafe_cell_ptr.to_ptr().unwrap().tag,
72                     end_ptr.to_ptr().unwrap().tag);
73             }
74             // We assume that we are given the fields in increasing offset order,
75             // and nothing else changes.
76             let unsafe_cell_offset = unsafe_cell_ptr.get_ptr_offset(this);
77             let end_offset = end_ptr.get_ptr_offset(this);
78             assert!(unsafe_cell_offset >= end_offset);
79             let frozen_size = unsafe_cell_offset - end_offset;
80             // Everything between the end_ptr and this `UnsafeCell` is frozen.
81             if frozen_size != Size::ZERO {
82                 action(end_ptr.to_ptr()?, frozen_size, /*frozen*/true)?;
83             }
84             // This `UnsafeCell` is NOT frozen.
85             if unsafe_cell_size != Size::ZERO {
86                 action(unsafe_cell_ptr.to_ptr()?, unsafe_cell_size, /*frozen*/false)?;
87             }
88             // Update end end_ptr.
89             end_ptr = unsafe_cell_ptr.ptr_wrapping_offset(unsafe_cell_size, this);
90             // Done
91             Ok(())
92         };
93         // Run a visitor
94         {
95             let mut visitor = UnsafeCellVisitor {
96                 ecx: this,
97                 unsafe_cell_action: |place| {
98                     trace!("unsafe_cell_action on {:?}", place.ptr);
99                     // We need a size to go on.
100                     let unsafe_cell_size = this.size_and_align_of_mplace(place)?
101                         .map(|(size, _)| size)
102                         // for extern types, just cover what we can
103                         .unwrap_or_else(|| place.layout.size);
104                     // Now handle this `UnsafeCell`, unless it is empty.
105                     if unsafe_cell_size != Size::ZERO {
106                         unsafe_cell_action(place.ptr, unsafe_cell_size)
107                     } else {
108                         Ok(())
109                     }
110                 },
111             };
112             visitor.visit_value(place)?;
113         }
114         // The part between the end_ptr and the end of the place is also frozen.
115         // So pretend there is a 0-sized `UnsafeCell` at the end.
116         unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
117         // Done!
118         return Ok(());
119
120         /// Visiting the memory covered by a `MemPlace`, being aware of
121         /// whether we are inside an `UnsafeCell` or not.
122         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
123             where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
124         {
125             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
126             unsafe_cell_action: F,
127         }
128
129         impl<'ecx, 'mir, 'tcx, F>
130             ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
131         for
132             UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
133         where
134             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
135         {
136             type V = MPlaceTy<'tcx, Tag>;
137
138             #[inline(always)]
139             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
140                 &self.ecx
141             }
142
143             // Hook to detect `UnsafeCell`.
144             fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
145             {
146                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
147                 let is_unsafe_cell = match v.layout.ty.sty {
148                     ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
149                     _ => false,
150                 };
151                 if is_unsafe_cell {
152                     // We do not have to recurse further, this is an `UnsafeCell`.
153                     (self.unsafe_cell_action)(v)
154                 } else if self.ecx.type_is_freeze(v.layout.ty) {
155                     // This is `Freeze`, there cannot be an `UnsafeCell`
156                     Ok(())
157                 } else {
158                     // Proceed further
159                     self.walk_value(v)
160                 }
161             }
162
163             // Make sure we visit aggregrates in increasing offset order.
164             fn visit_aggregate(
165                 &mut self,
166                 place: MPlaceTy<'tcx, Tag>,
167                 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
168             ) -> InterpResult<'tcx> {
169                 match place.layout.fields {
170                     layout::FieldPlacement::Array { .. } => {
171                         // For the array layout, we know the iterator will yield sorted elements so
172                         // we can avoid the allocation.
173                         self.walk_aggregate(place, fields)
174                     }
175                     layout::FieldPlacement::Arbitrary { .. } => {
176                         // Gather the subplaces and sort them before visiting.
177                         let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
178                         places.sort_by_key(|place| place.ptr.get_ptr_offset(self.ecx()));
179                         self.walk_aggregate(place, places.into_iter().map(Ok))
180                     }
181                     layout::FieldPlacement::Union { .. } => {
182                         // Uh, what?
183                         bug!("a union is not an aggregate we should ever visit")
184                     }
185                 }
186             }
187
188             // We have to do *something* for unions.
189             fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
190             {
191                 // With unions, we fall back to whatever the type says, to hopefully be consistent
192                 // with LLVM IR.
193                 // FIXME: are we consistent, and is this really the behavior we want?
194                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
195                 if frozen {
196                     Ok(())
197                 } else {
198                     (self.unsafe_cell_action)(v)
199                 }
200             }
201
202             // We should never get to a primitive, but always short-circuit somewhere above.
203             fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
204             {
205                 bug!("we should always short-circuit before coming to a primitive")
206             }
207         }
208     }
209 }