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