3 use std::convert::TryFrom;
8 layout::{self, LayoutOf, Size, TyLayout},
11 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
12 use rustc_span::source_map::DUMMY_SP;
18 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
20 /// Gets an instance for a path.
21 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
24 .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
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();
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());
37 items = tcx.item_children(item.res.def_id());
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)
54 /// Evaluates the scalar at the specified path. Returns Some(val)
55 /// if the path could be resolved, and None otherwise
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())?;
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])?
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()
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);
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)
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)
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) })
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)
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.
122 let this = self.eval_context_mut();
124 let mut data = vec![0; usize::try_from(len).unwrap()];
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))?;
131 let rng = this.memory.extra.rng.get_mut();
132 rng.fill_bytes(&mut data);
135 this.memory.write_bytes(ptr, data.iter().copied())
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).
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();
150 let mir = &*this.load_mir(f.def, None)?;
154 .and_then(Frame::current_source_info)
156 .unwrap_or(DUMMY_SP);
157 this.push_stack_frame(f, span, mir, dest, stack_pop)?;
159 // Initialize arguments.
160 let mut callee_args = this.frame().body.args_iter();
162 let callee_arg = this.local_place(
163 callee_args.next().expect("callee has fewer arguments than expected"),
165 this.write_immediate(*arg, callee_arg)?;
167 callee_args.next().expect_none("callee has more arguments than expected");
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(
176 place: MPlaceTy<'tcx, Tag>,
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);
184 this.size_and_align_of_mplace(place)?
185 .map(|(size, _)| size)
186 .unwrap_or_else(|| place.layout.size)
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)?;
208 // This `UnsafeCell` is NOT frozen.
209 if unsafe_cell_size != Size::ZERO {
210 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
212 // Update end end_ptr.
213 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
219 let mut visitor = UnsafeCellVisitor {
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)
237 visitor.visit_value(place)?;
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)?;
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>
249 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
251 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
252 unsafe_cell_action: F,
255 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
256 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
258 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
260 type V = MPlaceTy<'tcx, Tag>;
263 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
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 {
272 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
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`
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)
296 layout::Variants::Single { .. } => {
297 // Proceed further, try to find where exactly that `UnsafeCell`
305 // Make sure we visit aggregrates in increasing offset order.
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)
317 layout::FieldPlacement::Arbitrary { .. } => {
318 // Gather the subplaces and sort them before visiting.
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))
324 layout::FieldPlacement::Union { .. } => {
326 bug!("a union is not an aggregate we should ever visit")
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
335 // With unions, we fall back to whatever the type says, to hopefully be consistent
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) }
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(
348 place: MPlaceTy<'tcx, Tag>,
349 imms: &[ImmTy<'tcx, Tag>],
350 ) -> InterpResult<'tcx> {
351 let this = self.eval_context_mut();
353 let mut offset = Size::from_bytes(0);
356 this.write_immediate_to_mplace(
358 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
360 offset += imm.layout.size;
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
368 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
369 if !self.eval_context_ref().machine.communicate {
371 "`{}` not available when isolation is enabled (pass the flag `-Zmiri-disable-isolation` to disable isolation)",
377 /// Helper function used inside the shims of foreign functions to assert that the target
378 /// platform is `platform`. It panics showing a message with the `name` of the foreign function
379 /// if this is not the case.
380 fn assert_platform(&self, platform: &str, name: &str) {
382 self.eval_context_ref().tcx.sess.target.target.target_os,
384 "`{}` is only available on the `{}` platform",
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())
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()
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",
427 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
431 // FIXME: we have to implement the Windows equivalent of this.
433 "setting the last OS error from an io::Error is unsupported for {}.",
437 this.set_last_error(last_error)
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.
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>>(
448 result: std::io::Result<T>,
449 ) -> InterpResult<'tcx, T> {
453 self.eval_context_mut().set_last_error_from_io_error(e)?;
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>
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))
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))?;
477 let this = self.eval_context_ref();
478 let bytes = this.memory.read_c_str(scalar)?;
479 bytes_to_os_str(bytes)
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(
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)
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
504 .map(|s| s.as_bytes())
505 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
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));
515 self.eval_context_mut()
517 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
518 Ok((true, string_length))
521 fn alloc_os_str_as_c_str(
524 memkind: MemoryKind<MiriMemoryKind>,
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();
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()
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())
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())