]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
Move get/set_at_offset helpers to global helpers file
[rust.git] / src / helpers.rs
1 use std::convert::{TryFrom, TryInto};
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: 'mir> 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, ScalarMaybeUninit<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: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, '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 if matches!(v.layout.fields, FieldsShape::Union(..)) {
295                     // A (non-frozen) union. We fall back to whatever the type says.
296                     (self.unsafe_cell_action)(v)
297                 } else {
298                     // We want to not actually read from memory for this visit. So, before
299                     // walking this value, we have to make sure it is not a
300                     // `Variants::Multiple`.
301                     match v.layout.variants {
302                         Variants::Multiple { .. } => {
303                             // A multi-variant enum, or generator, or so.
304                             // Treat this like a union: without reading from memory,
305                             // we cannot determine the variant we are in. Reading from
306                             // memory would be subject to Stacked Borrows rules, leading
307                             // to all sorts of "funny" recursion.
308                             // We only end up here if the type is *not* freeze, so we just call the
309                             // `UnsafeCell` action.
310                             (self.unsafe_cell_action)(v)
311                         }
312                         Variants::Single { .. } => {
313                             // Proceed further, try to find where exactly that `UnsafeCell`
314                             // is hiding.
315                             self.walk_value(v)
316                         }
317                     }
318                 }
319             }
320
321             // Make sure we visit aggregrates in increasing offset order.
322             fn visit_aggregate(
323                 &mut self,
324                 place: MPlaceTy<'tcx, Tag>,
325                 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
326             ) -> InterpResult<'tcx> {
327                 match place.layout.fields {
328                     FieldsShape::Array { .. } => {
329                         // For the array layout, we know the iterator will yield sorted elements so
330                         // we can avoid the allocation.
331                         self.walk_aggregate(place, fields)
332                     }
333                     FieldsShape::Arbitrary { .. } => {
334                         // Gather the subplaces and sort them before visiting.
335                         let mut places =
336                             fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
337                         places.sort_by_key(|place| place.ptr.assert_ptr().offset);
338                         self.walk_aggregate(place, places.into_iter().map(Ok))
339                     }
340                     FieldsShape::Union { .. } | FieldsShape::Primitive => {
341                         // Uh, what?
342                         bug!("unions/primitives are not aggregates we should ever visit")
343                     }
344                 }
345             }
346
347             fn visit_union(&mut self, _v: MPlaceTy<'tcx, Tag>, _fields: NonZeroUsize) -> InterpResult<'tcx> {
348                 bug!("we should have already handled unions in `visit_value`")
349             }
350         }
351     }
352
353     // Writes several `ImmTy`s contiguously into memory. This is useful when you have to pack
354     // different values into a struct.
355     fn write_packed_immediates(
356         &mut self,
357         place: MPlaceTy<'tcx, Tag>,
358         imms: &[ImmTy<'tcx, Tag>],
359     ) -> InterpResult<'tcx> {
360         let this = self.eval_context_mut();
361
362         let mut offset = Size::from_bytes(0);
363
364         for &imm in imms {
365             this.write_immediate_to_mplace(
366                 *imm,
367                 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
368             )?;
369             offset += imm.layout.size;
370         }
371         Ok(())
372     }
373
374     /// Helper function used inside the shims of foreign functions to check that isolation is
375     /// disabled. It returns an error using the `name` of the foreign function if this is not the
376     /// case.
377     fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
378         if !self.eval_context_ref().machine.communicate {
379             throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
380                 "`{}` not available when isolation is enabled",
381                 name,
382             )))
383         }
384         Ok(())
385     }
386     /// Helper function used inside the shims of foreign functions to assert that the target OS
387     /// is `target_os`. It panics showing a message with the `name` of the foreign function
388     /// if this is not the case.
389     fn assert_target_os(&self, target_os: &str, name: &str) {
390         assert_eq!(
391             self.eval_context_ref().tcx.sess.target.target.target_os,
392             target_os,
393             "`{}` is only available on the `{}` target OS",
394             name,
395             target_os,
396         )
397     }
398
399     /// Sets the last error variable.
400     fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
401         let this = self.eval_context_mut();
402         let errno_place = this.machine.last_error.unwrap();
403         this.write_scalar(scalar, errno_place.into())
404     }
405
406     /// Gets the last error variable.
407     fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
408         let this = self.eval_context_ref();
409         let errno_place = this.machine.last_error.unwrap();
410         this.read_scalar(errno_place.into())?.not_undef()
411     }
412
413     /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
414     /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
415     fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
416         use std::io::ErrorKind::*;
417         let this = self.eval_context_mut();
418         let target = &this.tcx.sess.target.target;
419         let target_os = &target.target_os;
420         let last_error = if target.options.target_family == Some("unix".to_owned()) {
421             this.eval_libc(match e.kind() {
422                 ConnectionRefused => "ECONNREFUSED",
423                 ConnectionReset => "ECONNRESET",
424                 PermissionDenied => "EPERM",
425                 BrokenPipe => "EPIPE",
426                 NotConnected => "ENOTCONN",
427                 ConnectionAborted => "ECONNABORTED",
428                 AddrNotAvailable => "EADDRNOTAVAIL",
429                 AddrInUse => "EADDRINUSE",
430                 NotFound => "ENOENT",
431                 Interrupted => "EINTR",
432                 InvalidInput => "EINVAL",
433                 TimedOut => "ETIMEDOUT",
434                 AlreadyExists => "EEXIST",
435                 WouldBlock => "EWOULDBLOCK",
436                 _ => {
437                     throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
438                 }
439             })?
440         } else if target_os == "windows" {
441             // FIXME: we have to finish implementing the Windows equivalent of this.
442             this.eval_windows("c", match e.kind() {
443                 NotFound => "ERROR_FILE_NOT_FOUND",
444                 _ => throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
445             })?
446         } else {
447             throw_unsup_format!("setting the last OS error from an io::Error is unsupported for {}.", target_os)
448         };
449         this.set_last_error(last_error)
450     }
451
452     /// Helper function that consumes an `std::io::Result<T>` and returns an
453     /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
454     /// `Ok(-1)` and sets the last OS error accordingly.
455     ///
456     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
457     /// functions return different integer types (like `read`, that returns an `i64`).
458     fn try_unwrap_io_result<T: From<i32>>(
459         &mut self,
460         result: std::io::Result<T>,
461     ) -> InterpResult<'tcx, T> {
462         match result {
463             Ok(ok) => Ok(ok),
464             Err(e) => {
465                 self.eval_context_mut().set_last_error_from_io_error(e)?;
466                 Ok((-1).into())
467             }
468         }
469     }
470     
471     fn read_scalar_at_offset(
472         &self,
473         op: OpTy<'tcx, Tag>,
474         offset: u64,
475         layout: TyAndLayout<'tcx>,
476     ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
477         let this = self.eval_context_ref();
478         let op_place = this.deref_operand(op)?;
479         let offset = Size::from_bytes(offset);
480         // Ensure that the following read at an offset is within bounds
481         assert!(op_place.layout.size >= offset + layout.size);
482         let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
483         this.read_scalar(value_place.into())
484     }
485
486     fn write_scalar_at_offset(
487         &mut self,
488         op: OpTy<'tcx, Tag>,
489         offset: u64,
490         value: impl Into<ScalarMaybeUninit<Tag>>,
491         layout: TyAndLayout<'tcx>,
492     ) -> InterpResult<'tcx, ()> {
493         let this = self.eval_context_mut();
494         let op_place = this.deref_operand(op)?;
495         let offset = Size::from_bytes(offset);
496         // Ensure that the following read at an offset is within bounds
497         assert!(op_place.layout.size >= offset + layout.size);
498         let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
499         this.write_scalar(value, value_place.into())
500     }
501 }
502
503 /// Check that the number of args is what we expect.
504 pub fn check_arg_count<'a, 'tcx, const N: usize>(args: &'a [OpTy<'tcx, Tag>]) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
505     where &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]> {
506     if let Ok(ops) = args.try_into() {
507         return Ok(ops);
508     }
509     throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
510 }
511
512 pub fn immty_from_int_checked<'tcx>(
513     int: impl Into<i128>,
514     layout: TyAndLayout<'tcx>,
515 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
516     let int = int.into();
517     Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
518         err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
519     })?)
520 }
521
522 pub fn immty_from_uint_checked<'tcx>(
523     int: impl Into<u128>,
524     layout: TyAndLayout<'tcx>,
525 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
526     let int = int.into();
527     Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
528         err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())
529     })?)
530 }