1 use std::convert::TryFrom;
7 layout::{self, LayoutOf, Size, TyAndLayout},
10 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
11 use rustc_span::source_map::DUMMY_SP;
17 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
19 /// Gets an instance for a path.
20 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
23 .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
25 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
26 let mut items = tcx.item_children(krate);
27 let mut path_it = path.iter().skip(1).peekable();
29 while let Some(segment) = path_it.next() {
30 for item in mem::replace(&mut items, Default::default()).iter() {
31 if item.ident.name.as_str() == *segment {
32 if path_it.peek().is_none() {
33 return Some(item.res.def_id());
36 items = tcx.item_children(item.res.def_id());
45 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
46 /// Gets an instance for a path.
47 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
48 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)
49 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path));
50 ty::Instance::mono(self.eval_context_ref().tcx.tcx, did)
53 /// Evaluates the scalar at the specified path. Returns Some(val)
54 /// if the path could be resolved, and None otherwise
58 ) -> InterpResult<'tcx, ScalarMaybeUndef<Tag>> {
59 let this = self.eval_context_mut();
60 let instance = this.resolve_path(path);
61 let cid = GlobalId { instance, promoted: None };
62 let const_val = this.const_eval_raw(cid)?;
63 let const_val = this.read_scalar(const_val.into())?;
67 /// Helper function to get a `libc` constant as a `Scalar`.
68 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
69 self.eval_context_mut()
70 .eval_path_scalar(&["libc", name])?
74 /// Helper function to get a `windows` constant as a `Scalar`.
75 fn eval_windows(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
76 self.eval_context_mut()
77 .eval_path_scalar(&["std", "sys", "windows", "c", name])?
81 /// Helper function to get a `libc` constant as an `i32`.
82 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
83 // TODO: Cache the result.
84 self.eval_libc(name)?.to_i32()
87 /// Helper function to get the `TyAndLayout` of a `libc` type
88 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
89 let this = self.eval_context_mut();
90 let ty = this.resolve_path(&["libc", name]).monomorphic_ty(*this.tcx);
94 /// Write a 0 of the appropriate size to `dest`.
95 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
96 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
99 /// Test if this immediate equals 0.
100 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
101 let this = self.eval_context_ref();
102 let null = Scalar::null_ptr(this);
103 this.ptr_eq(val, null)
106 /// Turn a Scalar into an Option<NonNullScalar>
107 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
108 let this = self.eval_context_ref();
109 Ok(if this.is_null(val)? { None } else { Some(val) })
112 /// Get the `Place` for a local
113 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
114 let this = self.eval_context_mut();
115 let place = mir::Place { local: local, projection: List::empty() };
116 this.eval_place(&place)
119 /// Generate some random bytes, and write them to `dest`.
120 fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
121 // Some programs pass in a null pointer and a length of 0
122 // to their platform's random-generation function (e.g. getrandom())
123 // on Linux. For compatibility with these programs, we don't perform
124 // any additional checks - it's okay if the pointer is invalid,
125 // since we wouldn't actually be writing to it.
129 let this = self.eval_context_mut();
131 let mut data = vec![0; usize::try_from(len).unwrap()];
133 if this.machine.communicate {
134 // Fill the buffer using the host's rng.
135 getrandom::getrandom(&mut data)
136 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
138 let rng = this.memory.extra.rng.get_mut();
139 rng.fill_bytes(&mut data);
142 this.memory.write_bytes(ptr, data.iter().copied())
145 /// Call a function: Push the stack frame and pass the arguments.
146 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
149 f: ty::Instance<'tcx>,
150 args: &[Immediate<Tag>],
151 dest: Option<PlaceTy<'tcx, Tag>>,
152 stack_pop: StackPopCleanup,
153 ) -> InterpResult<'tcx> {
154 let this = self.eval_context_mut();
157 let mir = &*this.load_mir(f.def, None)?;
161 .and_then(Frame::current_source_info)
163 .unwrap_or(DUMMY_SP);
164 this.push_stack_frame(f, span, mir, dest, stack_pop)?;
166 // Initialize arguments.
167 let mut callee_args = this.frame().body.args_iter();
169 let callee_arg = this.local_place(
170 callee_args.next().expect("callee has fewer arguments than expected"),
172 this.write_immediate(*arg, callee_arg)?;
174 callee_args.next().expect_none("callee has more arguments than expected");
179 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
180 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
181 fn visit_freeze_sensitive(
183 place: MPlaceTy<'tcx, Tag>,
185 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
186 ) -> InterpResult<'tcx> {
187 let this = self.eval_context_ref();
188 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
191 this.size_and_align_of_mplace(place)?
192 .map(|(size, _)| size)
193 .unwrap_or_else(|| place.layout.size)
195 // Store how far we proceeded into the place so far. Everything to the left of
196 // this offset has already been handled, in the sense that the frozen parts
197 // have had `action` called on them.
198 let mut end_ptr = place.ptr.assert_ptr();
199 // Called when we detected an `UnsafeCell` at the given offset and size.
200 // Calls `action` and advances `end_ptr`.
201 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
202 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
203 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
204 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
205 // We assume that we are given the fields in increasing offset order,
206 // and nothing else changes.
207 let unsafe_cell_offset = unsafe_cell_ptr.offset;
208 let end_offset = end_ptr.offset;
209 assert!(unsafe_cell_offset >= end_offset);
210 let frozen_size = unsafe_cell_offset - end_offset;
211 // Everything between the end_ptr and this `UnsafeCell` is frozen.
212 if frozen_size != Size::ZERO {
213 action(end_ptr, frozen_size, /*frozen*/ true)?;
215 // This `UnsafeCell` is NOT frozen.
216 if unsafe_cell_size != Size::ZERO {
217 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
219 // Update end end_ptr.
220 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
226 let mut visitor = UnsafeCellVisitor {
228 unsafe_cell_action: |place| {
229 trace!("unsafe_cell_action on {:?}", place.ptr);
230 // We need a size to go on.
231 let unsafe_cell_size = this
232 .size_and_align_of_mplace(place)?
233 .map(|(size, _)| size)
234 // for extern types, just cover what we can
235 .unwrap_or_else(|| place.layout.size);
236 // Now handle this `UnsafeCell`, unless it is empty.
237 if unsafe_cell_size != Size::ZERO {
238 unsafe_cell_action(place.ptr, unsafe_cell_size)
244 visitor.visit_value(place)?;
246 // The part between the end_ptr and the end of the place is also frozen.
247 // So pretend there is a 0-sized `UnsafeCell` at the end.
248 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
252 /// Visiting the memory covered by a `MemPlace`, being aware of
253 /// whether we are inside an `UnsafeCell` or not.
254 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
256 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
258 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
259 unsafe_cell_action: F,
262 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
263 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
265 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
267 type V = MPlaceTy<'tcx, Tag>;
270 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
274 // Hook to detect `UnsafeCell`.
275 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
276 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
277 let is_unsafe_cell = match v.layout.ty.kind {
279 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
283 // We do not have to recurse further, this is an `UnsafeCell`.
284 (self.unsafe_cell_action)(v)
285 } else if self.ecx.type_is_freeze(v.layout.ty) {
286 // This is `Freeze`, there cannot be an `UnsafeCell`
289 // We want to not actually read from memory for this visit. So, before
290 // walking this value, we have to make sure it is not a
291 // `Variants::Multiple`.
292 match v.layout.variants {
293 layout::Variants::Multiple { .. } => {
294 // A multi-variant enum, or generator, or so.
295 // Treat this like a union: without reading from memory,
296 // we cannot determine the variant we are in. Reading from
297 // memory would be subject to Stacked Borrows rules, leading
298 // to all sorts of "funny" recursion.
299 // We only end up here if the type is *not* freeze, so we just call the
300 // `UnsafeCell` action.
301 (self.unsafe_cell_action)(v)
303 layout::Variants::Single { .. } => {
304 // Proceed further, try to find where exactly that `UnsafeCell`
312 // Make sure we visit aggregrates in increasing offset order.
315 place: MPlaceTy<'tcx, Tag>,
316 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
317 ) -> InterpResult<'tcx> {
318 match place.layout.fields {
319 layout::FieldPlacement::Array { .. } => {
320 // For the array layout, we know the iterator will yield sorted elements so
321 // we can avoid the allocation.
322 self.walk_aggregate(place, fields)
324 layout::FieldPlacement::Arbitrary { .. } => {
325 // Gather the subplaces and sort them before visiting.
327 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
328 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
329 self.walk_aggregate(place, places.into_iter().map(Ok))
331 layout::FieldPlacement::Union { .. } => {
333 bug!("a union is not an aggregate we should ever visit")
338 // We have to do *something* for unions.
339 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>, fields: usize) -> InterpResult<'tcx> {
340 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
342 // With unions, we fall back to whatever the type says, to hopefully be consistent
344 // FIXME: are we consistent, and is this really the behavior we want?
345 let frozen = self.ecx.type_is_freeze(v.layout.ty);
346 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
351 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
352 // different values into a struct.
353 fn write_packed_immediates(
355 place: MPlaceTy<'tcx, Tag>,
356 imms: &[ImmTy<'tcx, Tag>],
357 ) -> InterpResult<'tcx> {
358 let this = self.eval_context_mut();
360 let mut offset = Size::from_bytes(0);
363 this.write_immediate_to_mplace(
365 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
367 offset += imm.layout.size;
372 /// Helper function used inside the shims of foreign functions to check that isolation is
373 /// disabled. It returns an error using the `name` of the foreign function if this is not the
375 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
376 if !self.eval_context_ref().machine.communicate {
377 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
378 "`{}` not available when isolation is enabled",
384 /// Helper function used inside the shims of foreign functions to assert that the target OS
385 /// is `target_os`. It panics showing a message with the `name` of the foreign function
386 /// if this is not the case.
387 fn assert_target_os(&self, target_os: &str, name: &str) {
389 self.eval_context_ref().tcx.sess.target.target.target_os,
391 "`{}` is only available on the `{}` target OS",
397 /// Sets the last error variable.
398 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
399 let this = self.eval_context_mut();
400 let errno_place = this.machine.last_error.unwrap();
401 this.write_scalar(scalar, errno_place.into())
404 /// Gets the last error variable.
405 fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
406 let this = self.eval_context_ref();
407 let errno_place = this.machine.last_error.unwrap();
408 this.read_scalar(errno_place.into())?.not_undef()
411 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
412 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
413 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
414 use std::io::ErrorKind::*;
415 let this = self.eval_context_mut();
416 let target = &this.tcx.sess.target.target;
417 let target_os = &target.target_os;
418 let last_error = if target.options.target_family == Some("unix".to_owned()) {
419 this.eval_libc(match e.kind() {
420 ConnectionRefused => "ECONNREFUSED",
421 ConnectionReset => "ECONNRESET",
422 PermissionDenied => "EPERM",
423 BrokenPipe => "EPIPE",
424 NotConnected => "ENOTCONN",
425 ConnectionAborted => "ECONNABORTED",
426 AddrNotAvailable => "EADDRNOTAVAIL",
427 AddrInUse => "EADDRINUSE",
428 NotFound => "ENOENT",
429 Interrupted => "EINTR",
430 InvalidInput => "EINVAL",
431 TimedOut => "ETIMEDOUT",
432 AlreadyExists => "EEXIST",
433 WouldBlock => "EWOULDBLOCK",
435 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
438 } else if target_os == "windows" {
439 // FIXME: we have to finish implementing the Windows equivalent of this.
440 this.eval_windows(match e.kind() {
441 NotFound => "ERROR_FILE_NOT_FOUND",
442 _ => throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
445 throw_unsup_format!("setting the last OS error from an io::Error is unsupported for {}.", target_os)
447 this.set_last_error(last_error)
450 /// Helper function that consumes an `std::io::Result<T>` and returns an
451 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
452 /// `Ok(-1)` and sets the last OS error accordingly.
454 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
455 /// functions return different integer types (like `read`, that returns an `i64`).
456 fn try_unwrap_io_result<T: From<i32>>(
458 result: std::io::Result<T>,
459 ) -> InterpResult<'tcx, T> {
463 self.eval_context_mut().set_last_error_from_io_error(e)?;
470 pub fn immty_from_int_checked<'tcx>(
471 int: impl Into<i128>,
472 layout: TyAndLayout<'tcx>,
473 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
474 let int = int.into();
475 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
476 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
480 pub fn immty_from_uint_checked<'tcx>(
481 int: impl Into<u128>,
482 layout: TyAndLayout<'tcx>,
483 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
484 let int = int.into();
485 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
486 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())