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