]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
Rename set_last_error_from_io_result
[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         // Don't forget the bounds check.
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     /// Sets the last error variable
350     fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
351         let this = self.eval_context_mut();
352         let errno_place = this.machine.last_error.unwrap();
353         this.write_scalar(scalar, errno_place.into())
354     }
355
356     /// Gets the last error variable
357     fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
358         let this = self.eval_context_mut();
359         let errno_place = this.machine.last_error.unwrap();
360         this.read_scalar(errno_place.into())?.not_undef()
361     }
362
363     /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
364     /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
365     fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
366         use std::io::ErrorKind::*;
367         let this = self.eval_context_mut();
368         let target = &this.tcx.tcx.sess.target.target;
369         let last_error = if target.options.target_family == Some("unix".to_owned()) {
370             this.eval_libc(match e.kind() {
371                 ConnectionRefused => "ECONNREFUSED",
372                 ConnectionReset => "ECONNRESET",
373                 PermissionDenied => "EPERM",
374                 BrokenPipe => "EPIPE",
375                 NotConnected => "ENOTCONN",
376                 ConnectionAborted => "ECONNABORTED",
377                 AddrNotAvailable => "EADDRNOTAVAIL",
378                 AddrInUse => "EADDRINUSE",
379                 NotFound => "ENOENT",
380                 Interrupted => "EINTR",
381                 InvalidInput => "EINVAL",
382                 TimedOut => "ETIMEDOUT",
383                 AlreadyExists => "EEXIST",
384                 WouldBlock => "EWOULDBLOCK",
385                 _ => throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
386             })?
387         } else {
388             // FIXME: we have to implement the windows' equivalent of this.
389             throw_unsup_format!("Setting the last OS error from an io::Error is unsupported for {}.", target.target_os)
390         };
391         this.set_last_error(last_error)
392     }
393
394     /// Helper function that consumes an `std::io::Result<T>` and returns an
395     /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
396     /// `Ok(-1)` and sets the last OS error accordingly.
397     ///
398     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
399     /// functions return different integer types (like `read`, that returns an `i64`)
400     fn try_unwrap_io_result<T: From<i32>>(
401         &mut self,
402         result: std::io::Result<T>,
403     ) -> InterpResult<'tcx, T> {
404         match result {
405             Ok(ok) => Ok(ok),
406             Err(e) => {
407                 self.eval_context_mut().set_last_error_from_io_error(e)?;
408                 Ok((-1).into())
409             }
410         }
411     }
412 }