]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
3503af43690f996fc3e02ba57dfe51840bac2153
[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     /// Write a 0 of the appropriate size to `dest`.
47     fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
48         self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
49     }
50
51     /// Test if this immediate equals 0.
52     fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
53         let this = self.eval_context_ref();
54         let null = Scalar::from_int(0, this.memory().pointer_size());
55         this.ptr_eq(val, null)
56     }
57
58     /// Turn a Scalar into an Option<NonNullScalar>
59     fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
60         let this = self.eval_context_ref();
61         Ok(if this.is_null(val)? {
62             None
63         } else {
64             Some(val)
65         })
66     }
67
68     /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
69     /// will be true if this is frozen, false if this is in an `UnsafeCell`.
70     fn visit_freeze_sensitive(
71         &self,
72         place: MPlaceTy<'tcx, Tag>,
73         size: Size,
74         mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
75     ) -> InterpResult<'tcx> {
76         let this = self.eval_context_ref();
77         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
78         debug_assert_eq!(size,
79             this.size_and_align_of_mplace(place)?
80             .map(|(size, _)| size)
81             .unwrap_or_else(|| place.layout.size)
82         );
83         assert!(size.bytes() > 0);
84         // Store how far we proceeded into the place so far. Everything to the left of
85         // this offset has already been handled, in the sense that the frozen parts
86         // have had `action` called on them.
87         let mut end_ptr = place.ptr;
88         // Called when we detected an `UnsafeCell` at the given offset and size.
89         // Calls `action` and advances `end_ptr`.
90         let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
91             if unsafe_cell_size != Size::ZERO {
92                 debug_assert_eq!(unsafe_cell_ptr.to_ptr().unwrap().alloc_id,
93                     end_ptr.to_ptr().unwrap().alloc_id);
94                 debug_assert_eq!(unsafe_cell_ptr.to_ptr().unwrap().tag,
95                     end_ptr.to_ptr().unwrap().tag);
96             }
97             // We assume that we are given the fields in increasing offset order,
98             // and nothing else changes.
99             let unsafe_cell_offset = unsafe_cell_ptr.get_ptr_offset(this);
100             let end_offset = end_ptr.get_ptr_offset(this);
101             assert!(unsafe_cell_offset >= end_offset);
102             let frozen_size = unsafe_cell_offset - end_offset;
103             // Everything between the end_ptr and this `UnsafeCell` is frozen.
104             if frozen_size != Size::ZERO {
105                 action(end_ptr.to_ptr()?, frozen_size, /*frozen*/true)?;
106             }
107             // This `UnsafeCell` is NOT frozen.
108             if unsafe_cell_size != Size::ZERO {
109                 action(unsafe_cell_ptr.to_ptr()?, unsafe_cell_size, /*frozen*/false)?;
110             }
111             // Update end end_ptr.
112             end_ptr = unsafe_cell_ptr.ptr_wrapping_offset(unsafe_cell_size, this);
113             // Done
114             Ok(())
115         };
116         // Run a visitor
117         {
118             let mut visitor = UnsafeCellVisitor {
119                 ecx: this,
120                 unsafe_cell_action: |place| {
121                     trace!("unsafe_cell_action on {:?}", place.ptr);
122                     // We need a size to go on.
123                     let unsafe_cell_size = this.size_and_align_of_mplace(place)?
124                         .map(|(size, _)| size)
125                         // for extern types, just cover what we can
126                         .unwrap_or_else(|| place.layout.size);
127                     // Now handle this `UnsafeCell`, unless it is empty.
128                     if unsafe_cell_size != Size::ZERO {
129                         unsafe_cell_action(place.ptr, unsafe_cell_size)
130                     } else {
131                         Ok(())
132                     }
133                 },
134             };
135             visitor.visit_value(place)?;
136         }
137         // The part between the end_ptr and the end of the place is also frozen.
138         // So pretend there is a 0-sized `UnsafeCell` at the end.
139         unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
140         // Done!
141         return Ok(());
142
143         /// Visiting the memory covered by a `MemPlace`, being aware of
144         /// whether we are inside an `UnsafeCell` or not.
145         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
146             where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
147         {
148             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
149             unsafe_cell_action: F,
150         }
151
152         impl<'ecx, 'mir, 'tcx, F>
153             ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
154         for
155             UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
156         where
157             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
158         {
159             type V = MPlaceTy<'tcx, Tag>;
160
161             #[inline(always)]
162             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
163                 &self.ecx
164             }
165
166             // Hook to detect `UnsafeCell`.
167             fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
168             {
169                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
170                 let is_unsafe_cell = match v.layout.ty.sty {
171                     ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
172                     _ => false,
173                 };
174                 if is_unsafe_cell {
175                     // We do not have to recurse further, this is an `UnsafeCell`.
176                     (self.unsafe_cell_action)(v)
177                 } else if self.ecx.type_is_freeze(v.layout.ty) {
178                     // This is `Freeze`, there cannot be an `UnsafeCell`
179                     Ok(())
180                 } else {
181                     // Proceed further
182                     self.walk_value(v)
183                 }
184             }
185
186             // Make sure we visit aggregrates in increasing offset order.
187             fn visit_aggregate(
188                 &mut self,
189                 place: MPlaceTy<'tcx, Tag>,
190                 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
191             ) -> InterpResult<'tcx> {
192                 match place.layout.fields {
193                     layout::FieldPlacement::Array { .. } => {
194                         // For the array layout, we know the iterator will yield sorted elements so
195                         // we can avoid the allocation.
196                         self.walk_aggregate(place, fields)
197                     }
198                     layout::FieldPlacement::Arbitrary { .. } => {
199                         // Gather the subplaces and sort them before visiting.
200                         let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
201                         places.sort_by_key(|place| place.ptr.get_ptr_offset(self.ecx()));
202                         self.walk_aggregate(place, places.into_iter().map(Ok))
203                     }
204                     layout::FieldPlacement::Union { .. } => {
205                         // Uh, what?
206                         bug!("a union is not an aggregate we should ever visit")
207                     }
208                 }
209             }
210
211             // We have to do *something* for unions.
212             fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
213             {
214                 // With unions, we fall back to whatever the type says, to hopefully be consistent
215                 // with LLVM IR.
216                 // FIXME: are we consistent, and is this really the behavior we want?
217                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
218                 if frozen {
219                     Ok(())
220                 } else {
221                     (self.unsafe_cell_action)(v)
222                 }
223             }
224
225             // We should never get to a primitive, but always short-circuit somewhere above.
226             fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
227             {
228                 bug!("we should always short-circuit before coming to a primitive")
229             }
230         }
231     }
232 }