]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
c09d5c823e1bb214f306223ea9dfb7978a65c02a
[rust.git] / src / helpers.rs
1 use std::mem;
2
3 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
4 use rustc::mir;
5 use rustc::ty::{
6     self,
7     layout::{self, Align, LayoutOf, Size, TyLayout},
8 };
9
10 use rand::RngCore;
11
12 use crate::*;
13
14 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
15
16 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
17     /// Gets an instance for a path.
18     fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
19         let this = self.eval_context_ref();
20         this.tcx
21             .crates()
22             .iter()
23             .find(|&&krate| this.tcx.original_crate_name(krate).as_str() == path[0])
24             .and_then(|krate| {
25                 let krate = DefId {
26                     krate: *krate,
27                     index: CRATE_DEF_INDEX,
28                 };
29                 let mut items = this.tcx.item_children(krate);
30                 let mut path_it = path.iter().skip(1).peekable();
31
32                 while let Some(segment) = path_it.next() {
33                     for item in mem::replace(&mut items, Default::default()).iter() {
34                         if item.ident.name.as_str() == *segment {
35                             if path_it.peek().is_none() {
36                                 return Some(ty::Instance::mono(this.tcx.tcx, item.res.def_id()));
37                             }
38
39                             items = this.tcx.item_children(item.res.def_id());
40                             break;
41                         }
42                     }
43                 }
44                 None
45             })
46             .ok_or_else(|| {
47                 let path = path.iter().map(|&s| s.to_owned()).collect();
48                 err_unsup!(PathNotFound(path)).into()
49             })
50     }
51
52     /// Write a 0 of the appropriate size to `dest`.
53     fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
54         self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
55     }
56
57     /// Test if this immediate equals 0.
58     fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
59         let this = self.eval_context_ref();
60         let null = Scalar::from_int(0, this.memory.pointer_size());
61         this.ptr_eq(val, null)
62     }
63
64     /// Turn a Scalar into an Option<NonNullScalar>
65     fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
66         let this = self.eval_context_ref();
67         Ok(if this.is_null(val)? {
68             None
69         } else {
70             Some(val)
71         })
72     }
73
74     /// Get the `Place` for a local
75     fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
76         let this = self.eval_context_mut();
77         let place = mir::Place { base: mir::PlaceBase::Local(local), projection: Box::new([]) };
78         this.eval_place(&place)
79     }
80
81     /// Generate some random bytes, and write them to `dest`.
82     fn gen_random(
83         &mut self,
84         ptr: Scalar<Tag>,
85         len: usize,
86     ) -> InterpResult<'tcx>  {
87         // Some programs pass in a null pointer and a length of 0
88         // to their platform's random-generation function (e.g. getrandom())
89         // on Linux. For compatibility with these programs, we don't perform
90         // any additional checks - it's okay if the pointer is invalid,
91         // since we wouldn't actually be writing to it.
92         if len == 0 {
93             return Ok(());
94         }
95         let this = self.eval_context_mut();
96
97         let ptr = this.memory.check_ptr_access(
98             ptr,
99             Size::from_bytes(len as u64),
100             Align::from_bytes(1).unwrap()
101         )?.expect("we already checked for size 0");
102
103         let mut data = vec![0; len];
104
105         if this.machine.communicate {
106             // Fill the buffer using the host's rng.
107             getrandom::getrandom(&mut data)
108                 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
109         }
110         else {
111             let rng = this.memory.extra.rng.get_mut();
112             rng.fill_bytes(&mut data);
113         }
114
115         this.memory.get_mut(ptr.alloc_id)?.write_bytes(&*this.tcx, ptr, &data)
116     }
117
118     /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
119     /// will be true if this is frozen, false if this is in an `UnsafeCell`.
120     fn visit_freeze_sensitive(
121         &self,
122         place: MPlaceTy<'tcx, Tag>,
123         size: Size,
124         mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
125     ) -> InterpResult<'tcx> {
126         let this = self.eval_context_ref();
127         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
128         debug_assert_eq!(size,
129             this.size_and_align_of_mplace(place)?
130             .map(|(size, _)| size)
131             .unwrap_or_else(|| place.layout.size)
132         );
133         // Store how far we proceeded into the place so far. Everything to the left of
134         // this offset has already been handled, in the sense that the frozen parts
135         // have had `action` called on them.
136         let mut end_ptr = place.ptr.assert_ptr();
137         // Called when we detected an `UnsafeCell` at the given offset and size.
138         // Calls `action` and advances `end_ptr`.
139         let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
140             let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
141             debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
142             debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
143             // We assume that we are given the fields in increasing offset order,
144             // and nothing else changes.
145             let unsafe_cell_offset = unsafe_cell_ptr.offset;
146             let end_offset = end_ptr.offset;
147             assert!(unsafe_cell_offset >= end_offset);
148             let frozen_size = unsafe_cell_offset - end_offset;
149             // Everything between the end_ptr and this `UnsafeCell` is frozen.
150             if frozen_size != Size::ZERO {
151                 action(end_ptr, frozen_size, /*frozen*/true)?;
152             }
153             // This `UnsafeCell` is NOT frozen.
154             if unsafe_cell_size != Size::ZERO {
155                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
156             }
157             // Update end end_ptr.
158             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
159             // Done
160             Ok(())
161         };
162         // Run a visitor
163         {
164             let mut visitor = UnsafeCellVisitor {
165                 ecx: this,
166                 unsafe_cell_action: |place| {
167                     trace!("unsafe_cell_action on {:?}", place.ptr);
168                     // We need a size to go on.
169                     let unsafe_cell_size = this.size_and_align_of_mplace(place)?
170                         .map(|(size, _)| size)
171                         // for extern types, just cover what we can
172                         .unwrap_or_else(|| place.layout.size);
173                     // Now handle this `UnsafeCell`, unless it is empty.
174                     if unsafe_cell_size != Size::ZERO {
175                         unsafe_cell_action(place.ptr, unsafe_cell_size)
176                     } else {
177                         Ok(())
178                     }
179                 },
180             };
181             visitor.visit_value(place)?;
182         }
183         // The part between the end_ptr and the end of the place is also frozen.
184         // So pretend there is a 0-sized `UnsafeCell` at the end.
185         unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
186         // Done!
187         return Ok(());
188
189         /// Visiting the memory covered by a `MemPlace`, being aware of
190         /// whether we are inside an `UnsafeCell` or not.
191         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
192             where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
193         {
194             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
195             unsafe_cell_action: F,
196         }
197
198         impl<'ecx, 'mir, 'tcx, F>
199             ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
200         for
201             UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
202         where
203             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
204         {
205             type V = MPlaceTy<'tcx, Tag>;
206
207             #[inline(always)]
208             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
209                 &self.ecx
210             }
211
212             // Hook to detect `UnsafeCell`.
213             fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
214             {
215                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
216                 let is_unsafe_cell = match v.layout.ty.kind {
217                     ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
218                     _ => false,
219                 };
220                 if is_unsafe_cell {
221                     // We do not have to recurse further, this is an `UnsafeCell`.
222                     (self.unsafe_cell_action)(v)
223                 } else if self.ecx.type_is_freeze(v.layout.ty) {
224                     // This is `Freeze`, there cannot be an `UnsafeCell`
225                     Ok(())
226                 } else {
227                     // We want to not actually read from memory for this visit. So, before
228                     // walking this value, we have to make sure it is not a
229                     // `Variants::Multiple`.
230                     match v.layout.variants {
231                         layout::Variants::Multiple { .. } => {
232                             // A multi-variant enum, or generator, or so.
233                             // Treat this like a union: without reading from memory,
234                             // we cannot determine the variant we are in. Reading from
235                             // memory would be subject to Stacked Borrows rules, leading
236                             // to all sorts of "funny" recursion.
237                             // We only end up here if the type is *not* freeze, so we just call the
238                             // `UnsafeCell` action.
239                             (self.unsafe_cell_action)(v)
240                         }
241                         layout::Variants::Single { .. } => {
242                             // Proceed further, try to find where exactly that `UnsafeCell`
243                             // is hiding.
244                             self.walk_value(v)
245                         }
246                     }
247                 }
248             }
249
250             // Make sure we visit aggregrates in increasing offset order.
251             fn visit_aggregate(
252                 &mut self,
253                 place: MPlaceTy<'tcx, Tag>,
254                 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
255             ) -> InterpResult<'tcx> {
256                 match place.layout.fields {
257                     layout::FieldPlacement::Array { .. } => {
258                         // For the array layout, we know the iterator will yield sorted elements so
259                         // we can avoid the allocation.
260                         self.walk_aggregate(place, fields)
261                     }
262                     layout::FieldPlacement::Arbitrary { .. } => {
263                         // Gather the subplaces and sort them before visiting.
264                         let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
265                         places.sort_by_key(|place| place.ptr.assert_ptr().offset);
266                         self.walk_aggregate(place, places.into_iter().map(Ok))
267                     }
268                     layout::FieldPlacement::Union { .. } => {
269                         // Uh, what?
270                         bug!("a union is not an aggregate we should ever visit")
271                     }
272                 }
273             }
274
275             // We have to do *something* for unions.
276             fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
277             {
278                 // With unions, we fall back to whatever the type says, to hopefully be consistent
279                 // with LLVM IR.
280                 // FIXME: are we consistent, and is this really the behavior we want?
281                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
282                 if frozen {
283                     Ok(())
284                 } else {
285                     (self.unsafe_cell_action)(v)
286                 }
287             }
288
289             // We should never get to a primitive, but always short-circuit somewhere above.
290             fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
291             {
292                 bug!("we should always short-circuit before coming to a primitive")
293             }
294         }
295     }
296
297     /// Helper function to get a `libc` constant as a `Scalar`.
298     fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
299         self.eval_context_mut()
300             .eval_path_scalar(&["libc", name])?
301             .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
302             .not_undef()
303     }
304
305     /// Helper function to get a `libc` constant as an `i32`.
306     fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
307         self.eval_libc(name)?.to_i32()
308     }
309
310     /// Helper function to get the `TyLayout` of a `libc` type
311     fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
312         let this = self.eval_context_mut();
313         let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
314         this.layout_of(ty)
315     }
316
317     // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
318     // different values into a struct.
319     fn write_packed_immediates(
320         &mut self,
321         place: &MPlaceTy<'tcx, Tag>,
322         imms: &[ImmTy<'tcx, Tag>],
323     ) -> InterpResult<'tcx> {
324         let this = self.eval_context_mut();
325
326         let mut offset = Size::from_bytes(0);
327
328         for &imm in imms {
329             this.write_immediate_to_mplace(
330                 *imm,
331                 place.offset(offset, None, imm.layout, &*this.tcx)?,
332             )?;
333             offset += imm.layout.size;
334         }
335         Ok(())
336     }
337
338     /// Helper function used inside the shims of foreign functions to check that isolation is
339     /// disabled. It returns an error using the `name` of the foreign function if this is not the
340     /// case.
341     fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
342         if !self.eval_context_mut().machine.communicate {
343             throw_unsup_format!("`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.", name)
344         }
345         Ok(())
346     }
347 }