1 use std::convert::TryFrom;
7 use rustc_middle::ty::{
9 layout::{self, LayoutOf, Size, TyAndLayout},
12 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
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 // 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]).monomorphic_ty(*this.tcx);
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]).monomorphic_ty(*this.tcx);
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>,
164 args: &[Immediate<Tag>],
165 dest: Option<PlaceTy<'tcx, Tag>>,
166 stack_pop: StackPopCleanup,
167 ) -> InterpResult<'tcx> {
168 let this = self.eval_context_mut();
171 let mir = &*this.load_mir(f.def, None)?;
172 this.push_stack_frame(f, mir, dest, stack_pop)?;
174 // Initialize arguments.
175 let mut callee_args = this.frame().body.args_iter();
177 let callee_arg = this.local_place(
178 callee_args.next().expect("callee has fewer arguments than expected"),
180 this.write_immediate(*arg, callee_arg)?;
182 callee_args.next().expect_none("callee has more arguments than expected");
187 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
188 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
189 fn visit_freeze_sensitive(
191 place: MPlaceTy<'tcx, Tag>,
193 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
194 ) -> InterpResult<'tcx> {
195 let this = self.eval_context_ref();
196 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
199 this.size_and_align_of_mplace(place)?
200 .map(|(size, _)| size)
201 .unwrap_or_else(|| place.layout.size)
203 // Store how far we proceeded into the place so far. Everything to the left of
204 // this offset has already been handled, in the sense that the frozen parts
205 // have had `action` called on them.
206 let mut end_ptr = place.ptr.assert_ptr();
207 // Called when we detected an `UnsafeCell` at the given offset and size.
208 // Calls `action` and advances `end_ptr`.
209 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
210 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
211 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
212 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
213 // We assume that we are given the fields in increasing offset order,
214 // and nothing else changes.
215 let unsafe_cell_offset = unsafe_cell_ptr.offset;
216 let end_offset = end_ptr.offset;
217 assert!(unsafe_cell_offset >= end_offset);
218 let frozen_size = unsafe_cell_offset - end_offset;
219 // Everything between the end_ptr and this `UnsafeCell` is frozen.
220 if frozen_size != Size::ZERO {
221 action(end_ptr, frozen_size, /*frozen*/ true)?;
223 // This `UnsafeCell` is NOT frozen.
224 if unsafe_cell_size != Size::ZERO {
225 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
227 // Update end end_ptr.
228 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
234 let mut visitor = UnsafeCellVisitor {
236 unsafe_cell_action: |place| {
237 trace!("unsafe_cell_action on {:?}", place.ptr);
238 // We need a size to go on.
239 let unsafe_cell_size = this
240 .size_and_align_of_mplace(place)?
241 .map(|(size, _)| size)
242 // for extern types, just cover what we can
243 .unwrap_or_else(|| place.layout.size);
244 // Now handle this `UnsafeCell`, unless it is empty.
245 if unsafe_cell_size != Size::ZERO {
246 unsafe_cell_action(place.ptr, unsafe_cell_size)
252 visitor.visit_value(place)?;
254 // The part between the end_ptr and the end of the place is also frozen.
255 // So pretend there is a 0-sized `UnsafeCell` at the end.
256 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
260 /// Visiting the memory covered by a `MemPlace`, being aware of
261 /// whether we are inside an `UnsafeCell` or not.
262 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
264 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
266 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
267 unsafe_cell_action: F,
270 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
271 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
273 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
275 type V = MPlaceTy<'tcx, Tag>;
278 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
282 // Hook to detect `UnsafeCell`.
283 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
284 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
285 let is_unsafe_cell = match v.layout.ty.kind {
287 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
291 // We do not have to recurse further, this is an `UnsafeCell`.
292 (self.unsafe_cell_action)(v)
293 } else if self.ecx.type_is_freeze(v.layout.ty) {
294 // This is `Freeze`, there cannot be an `UnsafeCell`
297 // We want to not actually read from memory for this visit. So, before
298 // walking this value, we have to make sure it is not a
299 // `Variants::Multiple`.
300 match v.layout.variants {
301 layout::Variants::Multiple { .. } => {
302 // A multi-variant enum, or generator, or so.
303 // Treat this like a union: without reading from memory,
304 // we cannot determine the variant we are in. Reading from
305 // memory would be subject to Stacked Borrows rules, leading
306 // to all sorts of "funny" recursion.
307 // We only end up here if the type is *not* freeze, so we just call the
308 // `UnsafeCell` action.
309 (self.unsafe_cell_action)(v)
311 layout::Variants::Single { .. } => {
312 // Proceed further, try to find where exactly that `UnsafeCell`
320 // Make sure we visit aggregrates in increasing offset order.
323 place: MPlaceTy<'tcx, Tag>,
324 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
325 ) -> InterpResult<'tcx> {
326 match place.layout.fields {
327 layout::FieldsShape::Array { .. } => {
328 // For the array layout, we know the iterator will yield sorted elements so
329 // we can avoid the allocation.
330 self.walk_aggregate(place, fields)
332 layout::FieldsShape::Arbitrary { .. } => {
333 // Gather the subplaces and sort them before visiting.
335 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
336 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
337 self.walk_aggregate(place, places.into_iter().map(Ok))
339 layout::FieldsShape::Union { .. } => {
341 bug!("a union is not an aggregate we should ever visit")
346 // We have to do *something* for unions.
347 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>, fields: usize) -> InterpResult<'tcx> {
348 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
350 // With unions, we fall back to whatever the type says, to hopefully be consistent
352 // FIXME: are we consistent, and is this really the behavior we want?
353 let frozen = self.ecx.type_is_freeze(v.layout.ty);
354 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
359 // Writes several `ImmTy`s contiguously into memory. This is useful when you have to pack
360 // different values into a struct.
361 fn write_packed_immediates(
363 place: MPlaceTy<'tcx, Tag>,
364 imms: &[ImmTy<'tcx, Tag>],
365 ) -> InterpResult<'tcx> {
366 let this = self.eval_context_mut();
368 let mut offset = Size::from_bytes(0);
371 this.write_immediate_to_mplace(
373 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
375 offset += imm.layout.size;
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
383 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
384 if !self.eval_context_ref().machine.communicate {
385 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
386 "`{}` not available when isolation is enabled",
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.target.target_os,
399 "`{}` is only available on the `{}` target OS",
405 /// Sets the last error variable.
406 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
407 let this = self.eval_context_mut();
408 let errno_place = this.machine.last_error.unwrap();
409 this.write_scalar(scalar, errno_place.into())
412 /// Gets the last error variable.
413 fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
414 let this = self.eval_context_ref();
415 let errno_place = this.machine.last_error.unwrap();
416 this.read_scalar(errno_place.into())?.not_undef()
419 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
420 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
421 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
422 use std::io::ErrorKind::*;
423 let this = self.eval_context_mut();
424 let target = &this.tcx.sess.target.target;
425 let target_os = &target.target_os;
426 let last_error = if target.options.target_family == Some("unix".to_owned()) {
427 this.eval_libc(match e.kind() {
428 ConnectionRefused => "ECONNREFUSED",
429 ConnectionReset => "ECONNRESET",
430 PermissionDenied => "EPERM",
431 BrokenPipe => "EPIPE",
432 NotConnected => "ENOTCONN",
433 ConnectionAborted => "ECONNABORTED",
434 AddrNotAvailable => "EADDRNOTAVAIL",
435 AddrInUse => "EADDRINUSE",
436 NotFound => "ENOENT",
437 Interrupted => "EINTR",
438 InvalidInput => "EINVAL",
439 TimedOut => "ETIMEDOUT",
440 AlreadyExists => "EEXIST",
441 WouldBlock => "EWOULDBLOCK",
443 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
446 } else if target_os == "windows" {
447 // FIXME: we have to finish implementing the Windows equivalent of this.
448 this.eval_windows("c", match e.kind() {
449 NotFound => "ERROR_FILE_NOT_FOUND",
450 _ => throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
453 throw_unsup_format!("setting the last OS error from an io::Error is unsupported for {}.", target_os)
455 this.set_last_error(last_error)
458 /// Helper function that consumes an `std::io::Result<T>` and returns an
459 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
460 /// `Ok(-1)` and sets the last OS error accordingly.
462 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
463 /// functions return different integer types (like `read`, that returns an `i64`).
464 fn try_unwrap_io_result<T: From<i32>>(
466 result: std::io::Result<T>,
467 ) -> InterpResult<'tcx, T> {
471 self.eval_context_mut().set_last_error_from_io_error(e)?;
478 pub fn immty_from_int_checked<'tcx>(
479 int: impl Into<i128>,
480 layout: TyAndLayout<'tcx>,
481 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
482 let int = int.into();
483 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
484 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
488 pub fn immty_from_uint_checked<'tcx>(
489 int: impl Into<u128>,
490 layout: TyAndLayout<'tcx>,
491 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
492 let int = int.into();
493 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
494 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())