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