]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
b31e0a2c2eb9c39c4a6cfc570855206864b27f55
[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, 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 mut data = vec![0; len];
99
100         if this.machine.communicate {
101             // Fill the buffer using the host's rng.
102             getrandom::getrandom(&mut data)
103                 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
104         }
105         else {
106             let rng = this.memory.extra.rng.get_mut();
107             rng.fill_bytes(&mut data);
108         }
109
110         this.memory.write_bytes(ptr, data.iter().copied())
111     }
112
113     /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
114     /// will be true if this is frozen, false if this is in an `UnsafeCell`.
115     fn visit_freeze_sensitive(
116         &self,
117         place: MPlaceTy<'tcx, Tag>,
118         size: Size,
119         mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
120     ) -> InterpResult<'tcx> {
121         let this = self.eval_context_ref();
122         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
123         debug_assert_eq!(size,
124             this.size_and_align_of_mplace(place)?
125             .map(|(size, _)| size)
126             .unwrap_or_else(|| place.layout.size)
127         );
128         // Store how far we proceeded into the place so far. Everything to the left of
129         // this offset has already been handled, in the sense that the frozen parts
130         // have had `action` called on them.
131         let mut end_ptr = place.ptr.assert_ptr();
132         // Called when we detected an `UnsafeCell` at the given offset and size.
133         // Calls `action` and advances `end_ptr`.
134         let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
135             let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
136             debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
137             debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
138             // We assume that we are given the fields in increasing offset order,
139             // and nothing else changes.
140             let unsafe_cell_offset = unsafe_cell_ptr.offset;
141             let end_offset = end_ptr.offset;
142             assert!(unsafe_cell_offset >= end_offset);
143             let frozen_size = unsafe_cell_offset - end_offset;
144             // Everything between the end_ptr and this `UnsafeCell` is frozen.
145             if frozen_size != Size::ZERO {
146                 action(end_ptr, frozen_size, /*frozen*/true)?;
147             }
148             // This `UnsafeCell` is NOT frozen.
149             if unsafe_cell_size != Size::ZERO {
150                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/false)?;
151             }
152             // Update end end_ptr.
153             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
154             // Done
155             Ok(())
156         };
157         // Run a visitor
158         {
159             let mut visitor = UnsafeCellVisitor {
160                 ecx: this,
161                 unsafe_cell_action: |place| {
162                     trace!("unsafe_cell_action on {:?}", place.ptr);
163                     // We need a size to go on.
164                     let unsafe_cell_size = this.size_and_align_of_mplace(place)?
165                         .map(|(size, _)| size)
166                         // for extern types, just cover what we can
167                         .unwrap_or_else(|| place.layout.size);
168                     // Now handle this `UnsafeCell`, unless it is empty.
169                     if unsafe_cell_size != Size::ZERO {
170                         unsafe_cell_action(place.ptr, unsafe_cell_size)
171                     } else {
172                         Ok(())
173                     }
174                 },
175             };
176             visitor.visit_value(place)?;
177         }
178         // The part between the end_ptr and the end of the place is also frozen.
179         // So pretend there is a 0-sized `UnsafeCell` at the end.
180         unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
181         // Done!
182         return Ok(());
183
184         /// Visiting the memory covered by a `MemPlace`, being aware of
185         /// whether we are inside an `UnsafeCell` or not.
186         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
187             where F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
188         {
189             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
190             unsafe_cell_action: F,
191         }
192
193         impl<'ecx, 'mir, 'tcx, F>
194             ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
195         for
196             UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
197         where
198             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
199         {
200             type V = MPlaceTy<'tcx, Tag>;
201
202             #[inline(always)]
203             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
204                 &self.ecx
205             }
206
207             // Hook to detect `UnsafeCell`.
208             fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
209             {
210                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
211                 let is_unsafe_cell = match v.layout.ty.kind {
212                     ty::Adt(adt, _) => Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
213                     _ => false,
214                 };
215                 if is_unsafe_cell {
216                     // We do not have to recurse further, this is an `UnsafeCell`.
217                     (self.unsafe_cell_action)(v)
218                 } else if self.ecx.type_is_freeze(v.layout.ty) {
219                     // This is `Freeze`, there cannot be an `UnsafeCell`
220                     Ok(())
221                 } else {
222                     // We want to not actually read from memory for this visit. So, before
223                     // walking this value, we have to make sure it is not a
224                     // `Variants::Multiple`.
225                     match v.layout.variants {
226                         layout::Variants::Multiple { .. } => {
227                             // A multi-variant enum, or generator, or so.
228                             // Treat this like a union: without reading from memory,
229                             // we cannot determine the variant we are in. Reading from
230                             // memory would be subject to Stacked Borrows rules, leading
231                             // to all sorts of "funny" recursion.
232                             // We only end up here if the type is *not* freeze, so we just call the
233                             // `UnsafeCell` action.
234                             (self.unsafe_cell_action)(v)
235                         }
236                         layout::Variants::Single { .. } => {
237                             // Proceed further, try to find where exactly that `UnsafeCell`
238                             // is hiding.
239                             self.walk_value(v)
240                         }
241                     }
242                 }
243             }
244
245             // Make sure we visit aggregrates in increasing offset order.
246             fn visit_aggregate(
247                 &mut self,
248                 place: MPlaceTy<'tcx, Tag>,
249                 fields: impl Iterator<Item=InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
250             ) -> InterpResult<'tcx> {
251                 match place.layout.fields {
252                     layout::FieldPlacement::Array { .. } => {
253                         // For the array layout, we know the iterator will yield sorted elements so
254                         // we can avoid the allocation.
255                         self.walk_aggregate(place, fields)
256                     }
257                     layout::FieldPlacement::Arbitrary { .. } => {
258                         // Gather the subplaces and sort them before visiting.
259                         let mut places = fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
260                         places.sort_by_key(|place| place.ptr.assert_ptr().offset);
261                         self.walk_aggregate(place, places.into_iter().map(Ok))
262                     }
263                     layout::FieldPlacement::Union { .. } => {
264                         // Uh, what?
265                         bug!("a union is not an aggregate we should ever visit")
266                     }
267                 }
268             }
269
270             // We have to do *something* for unions.
271             fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
272             {
273                 // With unions, we fall back to whatever the type says, to hopefully be consistent
274                 // with LLVM IR.
275                 // FIXME: are we consistent, and is this really the behavior we want?
276                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
277                 if frozen {
278                     Ok(())
279                 } else {
280                     (self.unsafe_cell_action)(v)
281                 }
282             }
283
284             // We should never get to a primitive, but always short-circuit somewhere above.
285             fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>
286             {
287                 bug!("we should always short-circuit before coming to a primitive")
288             }
289         }
290     }
291
292     /// Helper function to get a `libc` constant as a `Scalar`.
293     fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
294         self.eval_context_mut()
295             .eval_path_scalar(&["libc", name])?
296             .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
297             .not_undef()
298     }
299
300     /// Helper function to get a `libc` constant as an `i32`.
301     fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
302         self.eval_libc(name)?.to_i32()
303     }
304
305     /// Helper function to get the `TyLayout` of a `libc` type
306     fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
307         let this = self.eval_context_mut();
308         let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
309         this.layout_of(ty)
310     }
311
312     // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
313     // different values into a struct.
314     fn write_packed_immediates(
315         &mut self,
316         place: &MPlaceTy<'tcx, Tag>,
317         imms: &[ImmTy<'tcx, Tag>],
318     ) -> InterpResult<'tcx> {
319         let this = self.eval_context_mut();
320
321         let mut offset = Size::from_bytes(0);
322
323         for &imm in imms {
324             this.write_immediate_to_mplace(
325                 *imm,
326                 place.offset(offset, None, imm.layout, &*this.tcx)?,
327             )?;
328             offset += imm.layout.size;
329         }
330         Ok(())
331     }
332
333     /// Helper function used inside the shims of foreign functions to check that isolation is
334     /// disabled. It returns an error using the `name` of the foreign function if this is not the
335     /// case.
336     fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
337         if !self.eval_context_mut().machine.communicate {
338             throw_unsup_format!("`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.", name)
339         }
340         Ok(())
341     }
342
343     /// Sets the last error variable.
344     fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
345         let this = self.eval_context_mut();
346         let errno_place = this.machine.last_error.unwrap();
347         this.write_scalar(scalar, errno_place.into())
348     }
349
350     /// Gets the last error variable.
351     fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
352         let this = self.eval_context_mut();
353         let errno_place = this.machine.last_error.unwrap();
354         this.read_scalar(errno_place.into())?.not_undef()
355     }
356
357     /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
358     /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
359     fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
360         use std::io::ErrorKind::*;
361         let this = self.eval_context_mut();
362         let target = &this.tcx.tcx.sess.target.target;
363         let last_error = if target.options.target_family == Some("unix".to_owned()) {
364             this.eval_libc(match e.kind() {
365                 ConnectionRefused => "ECONNREFUSED",
366                 ConnectionReset => "ECONNRESET",
367                 PermissionDenied => "EPERM",
368                 BrokenPipe => "EPIPE",
369                 NotConnected => "ENOTCONN",
370                 ConnectionAborted => "ECONNABORTED",
371                 AddrNotAvailable => "EADDRNOTAVAIL",
372                 AddrInUse => "EADDRINUSE",
373                 NotFound => "ENOENT",
374                 Interrupted => "EINTR",
375                 InvalidInput => "EINVAL",
376                 TimedOut => "ETIMEDOUT",
377                 AlreadyExists => "EEXIST",
378                 WouldBlock => "EWOULDBLOCK",
379                 _ => throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
380             })?
381         } else {
382             // FIXME: we have to implement the windows' equivalent of this.
383             throw_unsup_format!("Setting the last OS error from an io::Error is unsupported for {}.", target.target_os)
384         };
385         this.set_last_error(last_error)
386     }
387
388     /// Helper function that consumes an `std::io::Result<T>` and returns an
389     /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
390     /// `Ok(-1)` and sets the last OS error accordingly.
391     ///
392     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
393     /// functions return different integer types (like `read`, that returns an `i64`)
394     fn try_unwrap_io_result<T: From<i32>>(
395         &mut self,
396         result: std::io::Result<T>,
397     ) -> InterpResult<'tcx, T> {
398         match result {
399             Ok(ok) => Ok(ok),
400             Err(e) => {
401                 self.eval_context_mut().set_last_error_from_io_error(e)?;
402                 Ok((-1).into())
403             }
404         }
405     }
406
407     /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
408     /// the Unix APIs usually handle.
409     fn read_os_string_from_c_string(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString> {
410         let bytes = self.eval_context_mut().memory.read_c_str(scalar)?;
411         Ok(bytes_to_os_str(bytes)?.into())
412     }
413
414     /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
415     /// the Unix APIs usually handle.
416     fn write_os_str_to_c_string(&mut self, os_str: &OsStr, scalar: Scalar<Tag>, size: u64) -> InterpResult<'tcx> {
417         let bytes = os_str_to_bytes(os_str)?;
418         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
419         // terminator to memory using the `ptr` pointer would cause an overflow.
420         if size <= bytes.len() as u64 {
421             throw_unsup_format!("OsString of length {} is too large for destination buffer of size {}", bytes.len(), size)
422         }
423         // FIXME: We should use `Iterator::chain` instead when rust-lang/rust#65704 lands.
424         self.eval_context_mut().memory.write_bytes(scalar, [bytes, &[0]].concat())
425     }
426 }
427
428 #[cfg(target_os = "unix")]
429 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
430     std::os::unix::ffi::OsStringExt::into_bytes(os_str)
431 }
432
433 #[cfg(target_os = "unix")]
434 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a[u8]) -> InterpResult<'tcx, &'a OsStr> {
435     Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
436 }
437
438 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
439 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
440 // valid.
441 #[cfg(not(target_os = "unix"))]
442 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
443     os_str
444         .to_str()
445         .map(|s| s.as_bytes())
446         .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
447 }
448
449 #[cfg(not(target_os = "unix"))]
450 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a[u8]) -> InterpResult<'tcx, &'a OsStr> {
451     let s = std::str::from_utf8(bytes)
452         .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
453     Ok(&OsStr::new(s))
454 }