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