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