]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
start messages in lower-case
[rust.git] / src / helpers.rs
1 use std::ffi::OsStr;
2 use std::{iter, mem};
3 use std::convert::TryFrom;
4
5 use rustc::mir;
6 use rustc::ty::{
7     self,
8     layout::{self, LayoutOf, Size, TyLayout},
9     List, TyCtxt,
10 };
11 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
12 use rustc_span::source_map::DUMMY_SP;
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.crates()
23         .iter()
24         .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
25         .and_then(|krate| {
26             let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
27             let mut items = tcx.item_children(krate);
28             let mut path_it = path.iter().skip(1).peekable();
29
30             while let Some(segment) = path_it.next() {
31                 for item in mem::replace(&mut items, Default::default()).iter() {
32                     if item.ident.name.as_str() == *segment {
33                         if path_it.peek().is_none() {
34                             return Some(item.res.def_id());
35                         }
36
37                         items = tcx.item_children(item.res.def_id());
38                         break;
39                     }
40                 }
41             }
42             None
43         })
44         .ok_or_else(|| {
45             err_unsup_format!("failed to find required Rust item: {:?}", 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: u64) -> 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; usize::try_from(len).unwrap()];
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>, fields: usize) -> InterpResult<'tcx> {
304                 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
305
306                 // With unions, we fall back to whatever the type says, to hopefully be consistent
307                 // with LLVM IR.
308                 // FIXME: are we consistent, and is this really the behavior we want?
309                 let frozen = self.ecx.type_is_freeze(v.layout.ty);
310                 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
311             }
312         }
313     }
314
315     /// Helper function to get a `libc` constant as a `Scalar`.
316     fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
317         self.eval_context_mut()
318             .eval_path_scalar(&["libc", name])?
319             .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
320             .not_undef()
321     }
322
323     /// Helper function to get a `libc` constant as an `i32`.
324     fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
325         self.eval_libc(name)?.to_i32()
326     }
327
328     /// Helper function to get the `TyLayout` of a `libc` type
329     fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
330         let this = self.eval_context_mut();
331         let ty = this.resolve_path(&["libc", name])?.monomorphic_ty(*this.tcx);
332         this.layout_of(ty)
333     }
334
335     // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
336     // different values into a struct.
337     fn write_packed_immediates(
338         &mut self,
339         place: MPlaceTy<'tcx, Tag>,
340         imms: &[ImmTy<'tcx, Tag>],
341     ) -> InterpResult<'tcx> {
342         let this = self.eval_context_mut();
343
344         let mut offset = Size::from_bytes(0);
345
346         for &imm in imms {
347             this.write_immediate_to_mplace(
348                 *imm,
349                 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
350             )?;
351             offset += imm.layout.size;
352         }
353         Ok(())
354     }
355
356     /// Helper function used inside the shims of foreign functions to check that isolation is
357     /// disabled. It returns an error using the `name` of the foreign function if this is not the
358     /// case.
359     fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
360         if !self.eval_context_ref().machine.communicate {
361             throw_unsup_format!(
362                 "`{}` not available when isolation is enabled (pass the flag `-Zmiri-disable-isolation` to disable isolation)",
363                 name,
364             )
365         }
366         Ok(())
367     }
368     /// Helper function used inside the shims of foreign functions to assert that the target
369     /// platform is `platform`. It panics showing a message with the `name` of the foreign function
370     /// if this is not the case.
371     fn assert_platform(&self, platform: &str, name: &str) {
372         assert_eq!(
373             self.eval_context_ref().tcx.sess.target.target.target_os,
374             platform,
375             "`{}` is only available on the `{}` platform",
376             name,
377             platform,
378         )
379     }
380
381     /// Sets the last error variable.
382     fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
383         let this = self.eval_context_mut();
384         let errno_place = this.machine.last_error.unwrap();
385         this.write_scalar(scalar, errno_place.into())
386     }
387
388     /// Gets the last error variable.
389     fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
390         let this = self.eval_context_ref();
391         let errno_place = this.machine.last_error.unwrap();
392         this.read_scalar(errno_place.into())?.not_undef()
393     }
394
395     /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
396     /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
397     fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
398         use std::io::ErrorKind::*;
399         let this = self.eval_context_mut();
400         let target = &this.tcx.tcx.sess.target.target;
401         let last_error = if target.options.target_family == Some("unix".to_owned()) {
402             this.eval_libc(match e.kind() {
403                 ConnectionRefused => "ECONNREFUSED",
404                 ConnectionReset => "ECONNRESET",
405                 PermissionDenied => "EPERM",
406                 BrokenPipe => "EPIPE",
407                 NotConnected => "ENOTCONN",
408                 ConnectionAborted => "ECONNABORTED",
409                 AddrNotAvailable => "EADDRNOTAVAIL",
410                 AddrInUse => "EADDRINUSE",
411                 NotFound => "ENOENT",
412                 Interrupted => "EINTR",
413                 InvalidInput => "EINVAL",
414                 TimedOut => "ETIMEDOUT",
415                 AlreadyExists => "EEXIST",
416                 WouldBlock => "EWOULDBLOCK",
417                 _ => {
418                     throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
419                 }
420             })?
421         } else {
422             // FIXME: we have to implement the Windows equivalent of this.
423             throw_unsup_format!(
424                 "setting the last OS error from an io::Error is unsupported for {}.",
425                 target.target_os
426             )
427         };
428         this.set_last_error(last_error)
429     }
430
431     /// Helper function that consumes an `std::io::Result<T>` and returns an
432     /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
433     /// `Ok(-1)` and sets the last OS error accordingly.
434     ///
435     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
436     /// functions return different integer types (like `read`, that returns an `i64`).
437     fn try_unwrap_io_result<T: From<i32>>(
438         &mut self,
439         result: std::io::Result<T>,
440     ) -> InterpResult<'tcx, T> {
441         match result {
442             Ok(ok) => Ok(ok),
443             Err(e) => {
444                 self.eval_context_mut().set_last_error_from_io_error(e)?;
445                 Ok((-1).into())
446             }
447         }
448     }
449
450     /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
451     /// the Unix APIs usually handle.
452     fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
453     where
454         'tcx: 'a,
455         'mir: 'a,
456     {
457         #[cfg(target_os = "unix")]
458         fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
459             Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
460         }
461         #[cfg(not(target_os = "unix"))]
462         fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
463             let s = std::str::from_utf8(bytes)
464                 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
465             Ok(&OsStr::new(s))
466         }
467
468         let this = self.eval_context_ref();
469         let bytes = this.memory.read_c_str(scalar)?;
470         bytes_to_os_str(bytes)
471     }
472
473     /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
474     /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
475     /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
476     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
477     /// string length returned does not include the null terminator.
478     fn write_os_str_to_c_str(
479         &mut self,
480         os_str: &OsStr,
481         scalar: Scalar<Tag>,
482         size: u64,
483     ) -> InterpResult<'tcx, (bool, u64)> {
484         #[cfg(target_os = "unix")]
485         fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
486             std::os::unix::ffi::OsStringExt::into_bytes(os_str)
487         }
488         #[cfg(not(target_os = "unix"))]
489         fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
490             // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
491             // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
492             // valid.
493             os_str
494                 .to_str()
495                 .map(|s| s.as_bytes())
496                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
497         }
498
499         let bytes = os_str_to_bytes(os_str)?;
500         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
501         // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
502         let string_length = u64::try_from(bytes.len()).unwrap();
503         if size <= string_length {
504             return Ok((false, string_length));
505         }
506         self.eval_context_mut()
507             .memory
508             .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
509         Ok((true, string_length))
510     }
511
512     fn alloc_os_str_as_c_str(
513         &mut self,
514         os_str: &OsStr,
515         memkind: MemoryKind<MiriMemoryKind>,
516     ) -> Pointer<Tag> {
517         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
518         let this = self.eval_context_mut();
519
520         let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
521         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
522         self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap();
523         arg_place.ptr.assert_ptr()
524     }
525 }
526
527 pub fn immty_from_int_checked<'tcx>(
528     int: impl Into<i128>,
529     layout: TyLayout<'tcx>,
530 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
531     let int = int.into();
532     Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
533         err_unsup_format!("Signed value {:#x} does not fit in {} bits", int, layout.size.bits())
534     })?)
535 }
536
537 pub fn immty_from_uint_checked<'tcx>(
538     int: impl Into<u128>,
539     layout: TyLayout<'tcx>,
540 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
541     let int = int.into();
542     Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
543         err_unsup_format!("Signed value {:#x} does not fit in {} bits", int, layout.size.bits())
544     })?)
545 }