1 use std::convert::{TryFrom, TryInto};
3 use std::num::NonZeroUsize;
4 use std::time::Duration;
9 use rustc_middle::ty::{self, List, TyCtxt, layout::TyAndLayout};
10 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
11 use rustc_target::abi::{LayoutOf, Size, FieldsShape, Variants};
12 use rustc_target::spec::abi::Abi;
18 impl<'mir, 'tcx: 'mir> 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, ScalarMaybeUninit<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.eval_to_allocation(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 // TODO: Cache the result.
78 self.eval_libc(name)?.to_i32()
81 /// Helper function to get a `windows` constant as a `Scalar`.
82 fn eval_windows(&mut self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
83 self.eval_context_mut()
84 .eval_path_scalar(&["std", "sys", "windows", module, name])?
88 /// Helper function to get a `windows` constant as an `u64`.
89 fn eval_windows_u64(&mut self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
90 // TODO: Cache the result.
91 self.eval_windows(module, name)?.to_u64()
94 /// Helper function to get the `TyAndLayout` of a `libc` type
95 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
96 let this = self.eval_context_mut();
97 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
101 /// Helper function to get the `TyAndLayout` of a `windows` type
102 fn windows_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
103 let this = self.eval_context_mut();
104 let ty = this.resolve_path(&["std", "sys", "windows", "c", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
108 /// Write a 0 of the appropriate size to `dest`.
109 fn write_null(&mut self, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
110 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
113 /// Test if this immediate equals 0.
114 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
115 let this = self.eval_context_ref();
116 let null = Scalar::null_ptr(this);
117 this.ptr_eq(val, null)
120 /// Turn a Scalar into an Option<NonNullScalar>
121 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
122 let this = self.eval_context_ref();
123 Ok(if this.is_null(val)? { None } else { Some(val) })
126 /// Get the `Place` for a local
127 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
128 let this = self.eval_context_mut();
129 let place = mir::Place { local: local, projection: List::empty() };
130 this.eval_place(place)
133 /// Generate some random bytes, and write them to `dest`.
134 fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
135 // Some programs pass in a null pointer and a length of 0
136 // to their platform's random-generation function (e.g. getrandom())
137 // on Linux. For compatibility with these programs, we don't perform
138 // any additional checks - it's okay if the pointer is invalid,
139 // since we wouldn't actually be writing to it.
143 let this = self.eval_context_mut();
145 let mut data = vec![0; usize::try_from(len).unwrap()];
147 if this.machine.communicate {
148 // Fill the buffer using the host's rng.
149 getrandom::getrandom(&mut data)
150 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
152 let rng = this.memory.extra.rng.get_mut();
153 rng.fill_bytes(&mut data);
156 this.memory.write_bytes(ptr, data.iter().copied())
159 /// Call a function: Push the stack frame and pass the arguments.
160 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
163 f: ty::Instance<'tcx>,
165 args: &[Immediate<Tag>],
166 dest: Option<&PlaceTy<'tcx, Tag>>,
167 stack_pop: StackPopCleanup,
168 ) -> InterpResult<'tcx> {
169 let this = self.eval_context_mut();
170 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
171 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
172 if callee_abi != caller_abi {
173 throw_ub_format!("calling a function with ABI {} using caller ABI {}", callee_abi.name(), caller_abi.name())
177 let mir = &*this.load_mir(f.def, None)?;
178 this.push_stack_frame(f, mir, dest, stack_pop)?;
180 // Initialize arguments.
181 let mut callee_args = this.frame().body.args_iter();
183 let callee_arg = this.local_place(
184 callee_args.next().expect("callee has fewer arguments than expected"),
186 this.write_immediate(*arg, &callee_arg)?;
188 assert_eq!(callee_args.next(), None, "callee has more arguments than expected");
193 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
194 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
195 fn visit_freeze_sensitive(
197 place: &MPlaceTy<'tcx, Tag>,
199 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
200 ) -> InterpResult<'tcx> {
201 let this = self.eval_context_ref();
202 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
205 this.size_and_align_of_mplace(place)?
206 .map(|(size, _)| size)
207 .unwrap_or_else(|| place.layout.size)
209 // Store how far we proceeded into the place so far. Everything to the left of
210 // this offset has already been handled, in the sense that the frozen parts
211 // have had `action` called on them.
212 let mut end_ptr = place.ptr.assert_ptr();
213 // Called when we detected an `UnsafeCell` at the given offset and size.
214 // Calls `action` and advances `end_ptr`.
215 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
216 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
217 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
218 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
219 // We assume that we are given the fields in increasing offset order,
220 // and nothing else changes.
221 let unsafe_cell_offset = unsafe_cell_ptr.offset;
222 let end_offset = end_ptr.offset;
223 assert!(unsafe_cell_offset >= end_offset);
224 let frozen_size = unsafe_cell_offset - end_offset;
225 // Everything between the end_ptr and this `UnsafeCell` is frozen.
226 if frozen_size != Size::ZERO {
227 action(end_ptr, frozen_size, /*frozen*/ true)?;
229 // This `UnsafeCell` is NOT frozen.
230 if unsafe_cell_size != Size::ZERO {
231 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
233 // Update end end_ptr.
234 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
240 let mut visitor = UnsafeCellVisitor {
242 unsafe_cell_action: |place| {
243 trace!("unsafe_cell_action on {:?}", place.ptr);
244 // We need a size to go on.
245 let unsafe_cell_size = this
246 .size_and_align_of_mplace(&place)?
247 .map(|(size, _)| size)
248 // for extern types, just cover what we can
249 .unwrap_or_else(|| place.layout.size);
250 // Now handle this `UnsafeCell`, unless it is empty.
251 if unsafe_cell_size != Size::ZERO {
252 unsafe_cell_action(place.ptr, unsafe_cell_size)
258 visitor.visit_value(place)?;
260 // The part between the end_ptr and the end of the place is also frozen.
261 // So pretend there is a 0-sized `UnsafeCell` at the end.
262 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
266 /// Visiting the memory covered by a `MemPlace`, being aware of
267 /// whether we are inside an `UnsafeCell` or not.
268 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
270 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
272 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
273 unsafe_cell_action: F,
276 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
277 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
279 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
281 type V = MPlaceTy<'tcx, Tag>;
284 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
288 // Hook to detect `UnsafeCell`.
289 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
290 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
291 let is_unsafe_cell = match v.layout.ty.kind() {
293 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
297 // We do not have to recurse further, this is an `UnsafeCell`.
298 (self.unsafe_cell_action)(v)
299 } else if self.ecx.type_is_freeze(v.layout.ty) {
300 // This is `Freeze`, there cannot be an `UnsafeCell`
302 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
303 // A (non-frozen) union. We fall back to whatever the type says.
304 (self.unsafe_cell_action)(v)
306 // We want to not actually read from memory for this visit. So, before
307 // walking this value, we have to make sure it is not a
308 // `Variants::Multiple`.
309 match v.layout.variants {
310 Variants::Multiple { .. } => {
311 // A multi-variant enum, or generator, or so.
312 // Treat this like a union: without reading from memory,
313 // we cannot determine the variant we are in. Reading from
314 // memory would be subject to Stacked Borrows rules, leading
315 // to all sorts of "funny" recursion.
316 // We only end up here if the type is *not* freeze, so we just call the
317 // `UnsafeCell` action.
318 (self.unsafe_cell_action)(v)
320 Variants::Single { .. } => {
321 // Proceed further, try to find where exactly that `UnsafeCell`
329 // Make sure we visit aggregrates in increasing offset order.
332 place: &MPlaceTy<'tcx, Tag>,
333 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
334 ) -> InterpResult<'tcx> {
335 match place.layout.fields {
336 FieldsShape::Array { .. } => {
337 // For the array layout, we know the iterator will yield sorted elements so
338 // we can avoid the allocation.
339 self.walk_aggregate(place, fields)
341 FieldsShape::Arbitrary { .. } => {
342 // Gather the subplaces and sort them before visiting.
344 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
345 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
346 self.walk_aggregate(place, places.into_iter().map(Ok))
348 FieldsShape::Union { .. } | FieldsShape::Primitive => {
350 bug!("unions/primitives are not aggregates we should ever visit")
355 fn visit_union(&mut self, _v: &MPlaceTy<'tcx, Tag>, _fields: NonZeroUsize) -> InterpResult<'tcx> {
356 bug!("we should have already handled unions in `visit_value`")
361 // Writes several `ImmTy`s contiguously into memory. This is useful when you have to pack
362 // different values into a struct.
363 fn write_packed_immediates(
365 place: &MPlaceTy<'tcx, Tag>,
366 imms: &[ImmTy<'tcx, Tag>],
367 ) -> InterpResult<'tcx> {
368 let this = self.eval_context_mut();
370 let mut offset = Size::from_bytes(0);
373 this.write_immediate_to_mplace(
375 &place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
377 offset += imm.layout.size;
382 /// Helper function used inside the shims of foreign functions to check that isolation is
383 /// disabled. It returns an error using the `name` of the foreign function if this is not the
385 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
386 if !self.eval_context_ref().machine.communicate {
387 isolation_error(name)?;
392 /// Helper function used inside the shims of foreign functions to assert that the target OS
393 /// is `target_os`. It panics showing a message with the `name` of the foreign function
394 /// if this is not the case.
395 fn assert_target_os(&self, target_os: &str, name: &str) {
397 self.eval_context_ref().tcx.sess.target.os,
399 "`{}` is only available on the `{}` target OS",
405 /// Get last error variable as a place, lazily allocating thread-local storage for it if
407 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
408 let this = self.eval_context_mut();
409 if let Some(errno_place) = this.active_thread_ref().last_error {
412 // Allocate new place, set initial value to 0.
413 let errno_layout = this.machine.layouts.u32;
414 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into());
415 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
416 this.active_thread_mut().last_error = Some(errno_place);
421 /// Sets the last error variable.
422 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
423 let this = self.eval_context_mut();
424 let errno_place = this.last_error_place()?;
425 this.write_scalar(scalar, &errno_place.into())
428 /// Gets the last error variable.
429 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
430 let this = self.eval_context_mut();
431 let errno_place = this.last_error_place()?;
432 this.read_scalar(&errno_place.into())?.check_init()
435 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
436 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
437 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
438 use std::io::ErrorKind::*;
439 let this = self.eval_context_mut();
440 let target = &this.tcx.sess.target;
441 let target_os = &target.os;
442 let last_error = if target.os_family == Some("unix".to_owned()) {
443 this.eval_libc(match e.kind() {
444 ConnectionRefused => "ECONNREFUSED",
445 ConnectionReset => "ECONNRESET",
446 PermissionDenied => "EPERM",
447 BrokenPipe => "EPIPE",
448 NotConnected => "ENOTCONN",
449 ConnectionAborted => "ECONNABORTED",
450 AddrNotAvailable => "EADDRNOTAVAIL",
451 AddrInUse => "EADDRINUSE",
452 NotFound => "ENOENT",
453 Interrupted => "EINTR",
454 InvalidInput => "EINVAL",
455 TimedOut => "ETIMEDOUT",
456 AlreadyExists => "EEXIST",
457 WouldBlock => "EWOULDBLOCK",
459 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
462 } else if target_os == "windows" {
463 // FIXME: we have to finish implementing the Windows equivalent of this.
464 this.eval_windows("c", match e.kind() {
465 NotFound => "ERROR_FILE_NOT_FOUND",
466 _ => throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
469 throw_unsup_format!("setting the last OS error from an io::Error is unsupported for {}.", target_os)
471 this.set_last_error(last_error)
474 /// Helper function that consumes an `std::io::Result<T>` and returns an
475 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
476 /// `Ok(-1)` and sets the last OS error accordingly.
478 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
479 /// functions return different integer types (like `read`, that returns an `i64`).
480 fn try_unwrap_io_result<T: From<i32>>(
482 result: std::io::Result<T>,
483 ) -> InterpResult<'tcx, T> {
487 self.eval_context_mut().set_last_error_from_io_error(e)?;
493 fn read_scalar_at_offset(
495 op: &OpTy<'tcx, Tag>,
497 layout: TyAndLayout<'tcx>,
498 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
499 let this = self.eval_context_ref();
500 let op_place = this.deref_operand(op)?;
501 let offset = Size::from_bytes(offset);
502 // Ensure that the following read at an offset is within bounds
503 assert!(op_place.layout.size >= offset + layout.size);
504 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
505 this.read_scalar(&value_place.into())
508 fn write_scalar_at_offset(
510 op: &OpTy<'tcx, Tag>,
512 value: impl Into<ScalarMaybeUninit<Tag>>,
513 layout: TyAndLayout<'tcx>,
514 ) -> InterpResult<'tcx, ()> {
515 let this = self.eval_context_mut();
516 let op_place = this.deref_operand(op)?;
517 let offset = Size::from_bytes(offset);
518 // Ensure that the following read at an offset is within bounds
519 assert!(op_place.layout.size >= offset + layout.size);
520 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
521 this.write_scalar(value, &value_place.into())
524 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
525 /// if the value in the `timespec` struct is invalid. Some libc functions will return
526 /// `EINVAL` in this case.
529 timespec_ptr_op: &OpTy<'tcx, Tag>,
530 ) -> InterpResult<'tcx, Option<Duration>> {
531 let this = self.eval_context_mut();
532 let tp = this.deref_operand(timespec_ptr_op)?;
533 let seconds_place = this.mplace_field(&tp, 0)?;
534 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
535 let seconds = seconds_scalar.to_machine_isize(this)?;
536 let nanoseconds_place = this.mplace_field(&tp, 1)?;
537 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
538 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
541 // tv_sec must be non-negative.
542 let seconds: u64 = seconds.try_into().ok()?;
543 // tv_nsec must be non-negative.
544 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
545 if nanoseconds >= 1_000_000_000 {
546 // tv_nsec must not be greater than 999,999,999.
549 Duration::new(seconds, nanoseconds)
554 /// Check that the number of args is what we expect.
555 pub fn check_arg_count<'a, 'tcx, const N: usize>(args: &'a [OpTy<'tcx, Tag>]) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
556 where &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]> {
557 if let Ok(ops) = args.try_into() {
560 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
563 /// Check that the ABI is what we expect.
564 pub fn check_abi<'a>(abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
568 throw_ub_format!("calling a function with ABI {} using caller ABI {}", exp_abi.name(), abi.name())
572 pub fn isolation_error(name: &str) -> InterpResult<'static> {
573 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
574 "{} not available when isolation is enabled",
579 pub fn immty_from_int_checked<'tcx>(
580 int: impl Into<i128>,
581 layout: TyAndLayout<'tcx>,
582 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
583 let int = int.into();
584 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
585 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
589 pub fn immty_from_uint_checked<'tcx>(
590 int: impl Into<u128>,
591 layout: TyAndLayout<'tcx>,
592 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
593 let int = int.into();
594 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
595 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())