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