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