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