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