4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
8 layout::{self, LayoutOf, Size, TyLayout},
11 use syntax::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 resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> InterpResult<'tcx, 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());
44 let path = path.iter().map(|&s| s.to_owned()).collect();
45 err_unsup!(PathNotFound(path)).into()
49 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
50 /// Gets an instance for a path.
51 fn resolve_path(&self, path: &[&str]) -> InterpResult<'tcx, ty::Instance<'tcx>> {
52 Ok(ty::Instance::mono(
53 self.eval_context_ref().tcx.tcx,
54 resolve_did(self.eval_context_ref().tcx.tcx, path)?,
58 /// Write a 0 of the appropriate size to `dest`.
59 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
60 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
63 /// Test if this immediate equals 0.
64 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
65 let this = self.eval_context_ref();
66 let null = Scalar::from_int(0, this.memory.pointer_size());
67 this.ptr_eq(val, null)
70 /// Turn a Scalar into an Option<NonNullScalar>
71 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
72 let this = self.eval_context_ref();
73 Ok(if this.is_null(val)? { None } else { Some(val) })
76 /// Get the `Place` for a local
77 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
78 let this = self.eval_context_mut();
79 let place = mir::Place { base: mir::PlaceBase::Local(local), projection: List::empty() };
80 this.eval_place(&place)
83 /// Generate some random bytes, and write them to `dest`.
84 fn gen_random(&mut self, ptr: Scalar<Tag>, len: usize) -> InterpResult<'tcx> {
85 // Some programs pass in a null pointer and a length of 0
86 // to their platform's random-generation function (e.g. getrandom())
87 // on Linux. For compatibility with these programs, we don't perform
88 // any additional checks - it's okay if the pointer is invalid,
89 // since we wouldn't actually be writing to it.
93 let this = self.eval_context_mut();
95 let mut data = vec![0; len];
97 if this.machine.communicate {
98 // Fill the buffer using the host's rng.
99 getrandom::getrandom(&mut data)
100 .map_err(|err| err_unsup_format!("getrandom failed: {}", err))?;
102 let rng = this.memory.extra.rng.get_mut();
103 rng.fill_bytes(&mut data);
106 this.memory.write_bytes(ptr, data.iter().copied())
109 /// Call a function: Push the stack frame and pass the arguments.
110 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
113 f: ty::Instance<'tcx>,
114 args: &[Immediate<Tag>],
115 dest: Option<PlaceTy<'tcx, Tag>>,
116 stack_pop: StackPopCleanup,
117 ) -> InterpResult<'tcx> {
118 let this = self.eval_context_mut();
121 let mir = &*this.load_mir(f.def, None)?;
125 .and_then(Frame::current_source_info)
127 .unwrap_or(DUMMY_SP);
128 this.push_stack_frame(f, span, mir, dest, stack_pop)?;
130 // Initialize arguments.
131 let mut callee_args = this.frame().body.args_iter();
133 let callee_arg = this.local_place(
134 callee_args.next().expect("callee has fewer arguments than expected"),
136 this.write_immediate(*arg, callee_arg)?;
138 callee_args.next().expect_none("callee has more arguments than expected");
143 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
144 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
145 fn visit_freeze_sensitive(
147 place: MPlaceTy<'tcx, Tag>,
149 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
150 ) -> InterpResult<'tcx> {
151 let this = self.eval_context_ref();
152 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
155 this.size_and_align_of_mplace(place)?
156 .map(|(size, _)| size)
157 .unwrap_or_else(|| place.layout.size)
159 // Store how far we proceeded into the place so far. Everything to the left of
160 // this offset has already been handled, in the sense that the frozen parts
161 // have had `action` called on them.
162 let mut end_ptr = place.ptr.assert_ptr();
163 // Called when we detected an `UnsafeCell` at the given offset and size.
164 // Calls `action` and advances `end_ptr`.
165 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
166 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
167 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
168 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
169 // We assume that we are given the fields in increasing offset order,
170 // and nothing else changes.
171 let unsafe_cell_offset = unsafe_cell_ptr.offset;
172 let end_offset = end_ptr.offset;
173 assert!(unsafe_cell_offset >= end_offset);
174 let frozen_size = unsafe_cell_offset - end_offset;
175 // Everything between the end_ptr and this `UnsafeCell` is frozen.
176 if frozen_size != Size::ZERO {
177 action(end_ptr, frozen_size, /*frozen*/ true)?;
179 // This `UnsafeCell` is NOT frozen.
180 if unsafe_cell_size != Size::ZERO {
181 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
183 // Update end end_ptr.
184 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
190 let mut visitor = UnsafeCellVisitor {
192 unsafe_cell_action: |place| {
193 trace!("unsafe_cell_action on {:?}", place.ptr);
194 // We need a size to go on.
195 let unsafe_cell_size = this
196 .size_and_align_of_mplace(place)?
197 .map(|(size, _)| size)
198 // for extern types, just cover what we can
199 .unwrap_or_else(|| place.layout.size);
200 // Now handle this `UnsafeCell`, unless it is empty.
201 if unsafe_cell_size != Size::ZERO {
202 unsafe_cell_action(place.ptr, unsafe_cell_size)
208 visitor.visit_value(place)?;
210 // The part between the end_ptr and the end of the place is also frozen.
211 // So pretend there is a 0-sized `UnsafeCell` at the end.
212 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
216 /// Visiting the memory covered by a `MemPlace`, being aware of
217 /// whether we are inside an `UnsafeCell` or not.
218 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
220 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
222 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
223 unsafe_cell_action: F,
226 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
227 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
229 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
231 type V = MPlaceTy<'tcx, Tag>;
234 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
238 // Hook to detect `UnsafeCell`.
239 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
240 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
241 let is_unsafe_cell = match v.layout.ty.kind {
243 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
247 // We do not have to recurse further, this is an `UnsafeCell`.
248 (self.unsafe_cell_action)(v)
249 } else if self.ecx.type_is_freeze(v.layout.ty) {
250 // This is `Freeze`, there cannot be an `UnsafeCell`
253 // We want to not actually read from memory for this visit. So, before
254 // walking this value, we have to make sure it is not a
255 // `Variants::Multiple`.
256 match v.layout.variants {
257 layout::Variants::Multiple { .. } => {
258 // A multi-variant enum, or generator, or so.
259 // Treat this like a union: without reading from memory,
260 // we cannot determine the variant we are in. Reading from
261 // memory would be subject to Stacked Borrows rules, leading
262 // to all sorts of "funny" recursion.
263 // We only end up here if the type is *not* freeze, so we just call the
264 // `UnsafeCell` action.
265 (self.unsafe_cell_action)(v)
267 layout::Variants::Single { .. } => {
268 // Proceed further, try to find where exactly that `UnsafeCell`
276 // Make sure we visit aggregrates in increasing offset order.
279 place: MPlaceTy<'tcx, Tag>,
280 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
281 ) -> InterpResult<'tcx> {
282 match place.layout.fields {
283 layout::FieldPlacement::Array { .. } => {
284 // For the array layout, we know the iterator will yield sorted elements so
285 // we can avoid the allocation.
286 self.walk_aggregate(place, fields)
288 layout::FieldPlacement::Arbitrary { .. } => {
289 // Gather the subplaces and sort them before visiting.
291 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
292 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
293 self.walk_aggregate(place, places.into_iter().map(Ok))
295 layout::FieldPlacement::Union { .. } => {
297 bug!("a union is not an aggregate we should ever visit")
302 // We have to do *something* for unions.
303 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
304 // With unions, we fall back to whatever the type says, to hopefully be consistent
306 // FIXME: are we consistent, and is this really the behavior we want?
307 let frozen = self.ecx.type_is_freeze(v.layout.ty);
308 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
311 // We should never get to a primitive, but always short-circuit somewhere above.
312 fn visit_primitive(&mut self, _v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
313 bug!("we should always short-circuit before coming to a primitive")
318 /// Helper function to get a `libc` constant as a `Scalar`.
319 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
320 self.eval_context_mut()
321 .eval_path_scalar(&["libc", name])?
322 .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
326 /// Helper function to get a `libc` constant as an `i32`.
327 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
328 self.eval_libc(name)?.to_i32()
331 /// Helper function to get the `TyLayout` of a `libc` type
332 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
333 let this = self.eval_context_mut();
334 let ty = this.resolve_path(&["libc", name])?.ty(*this.tcx);
338 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
339 // different values into a struct.
340 fn write_packed_immediates(
342 place: &MPlaceTy<'tcx, Tag>,
343 imms: &[ImmTy<'tcx, Tag>],
344 ) -> InterpResult<'tcx> {
345 let this = self.eval_context_mut();
347 let mut offset = Size::from_bytes(0);
350 this.write_immediate_to_mplace(
352 place.offset(offset, None, imm.layout, &*this.tcx)?,
354 offset += imm.layout.size;
359 /// Helper function used inside the shims of foreign functions to check that isolation is
360 /// disabled. It returns an error using the `name` of the foreign function if this is not the
362 fn check_no_isolation(&mut self, name: &str) -> InterpResult<'tcx> {
363 if !self.eval_context_mut().machine.communicate {
365 "`{}` not available when isolation is enabled. Pass the flag `-Zmiri-disable-isolation` to disable it.",
372 /// Sets the last error variable.
373 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
374 let this = self.eval_context_mut();
375 let errno_place = this.machine.last_error.unwrap();
376 this.write_scalar(scalar, errno_place.into())
379 /// Gets the last error variable.
380 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
381 let this = self.eval_context_mut();
382 let errno_place = this.machine.last_error.unwrap();
383 this.read_scalar(errno_place.into())?.not_undef()
386 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
387 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
388 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
389 use std::io::ErrorKind::*;
390 let this = self.eval_context_mut();
391 let target = &this.tcx.tcx.sess.target.target;
392 let last_error = if target.options.target_family == Some("unix".to_owned()) {
393 this.eval_libc(match e.kind() {
394 ConnectionRefused => "ECONNREFUSED",
395 ConnectionReset => "ECONNRESET",
396 PermissionDenied => "EPERM",
397 BrokenPipe => "EPIPE",
398 NotConnected => "ENOTCONN",
399 ConnectionAborted => "ECONNABORTED",
400 AddrNotAvailable => "EADDRNOTAVAIL",
401 AddrInUse => "EADDRINUSE",
402 NotFound => "ENOENT",
403 Interrupted => "EINTR",
404 InvalidInput => "EINVAL",
405 TimedOut => "ETIMEDOUT",
406 AlreadyExists => "EEXIST",
407 WouldBlock => "EWOULDBLOCK",
409 throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
413 // FIXME: we have to implement the Windows equivalent of this.
415 "Setting the last OS error from an io::Error is unsupported for {}.",
419 this.set_last_error(last_error)
422 /// Helper function that consumes an `std::io::Result<T>` and returns an
423 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
424 /// `Ok(-1)` and sets the last OS error accordingly.
426 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
427 /// functions return different integer types (like `read`, that returns an `i64`).
428 fn try_unwrap_io_result<T: From<i32>>(
430 result: std::io::Result<T>,
431 ) -> InterpResult<'tcx, T> {
435 self.eval_context_mut().set_last_error_from_io_error(e)?;
441 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
442 /// the Unix APIs usually handle.
443 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
448 let this = self.eval_context_ref();
449 let bytes = this.memory.read_c_str(scalar)?;
450 bytes_to_os_str(bytes)
453 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
454 /// the Unix APIs usually handle. This function returns `Ok(false)` without trying to write if
455 /// `size` is not large enough to fit the contents of `os_string` plus a null terminator. It
456 /// returns `Ok(true)` if the writing process was successful.
457 fn write_os_str_to_c_str(
462 ) -> InterpResult<'tcx, bool> {
463 let bytes = os_str_to_bytes(os_str)?;
464 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
465 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
466 if size <= bytes.len() as u64 {
469 self.eval_context_mut()
471 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
476 #[cfg(target_os = "unix")]
477 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
478 std::os::unix::ffi::OsStringExt::into_bytes(os_str)
481 #[cfg(target_os = "unix")]
482 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
483 Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
486 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
487 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
489 #[cfg(not(target_os = "unix"))]
490 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
493 .map(|s| s.as_bytes())
494 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
497 #[cfg(not(target_os = "unix"))]
498 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
499 let s = std::str::from_utf8(bytes)
500 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
504 // FIXME: change `ImmTy::from_int` so it returns an `InterpResult` instead and remove this
506 pub fn immty_from_int_checked<'tcx>(
507 int: impl Into<i128>,
508 layout: TyLayout<'tcx>,
509 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
510 let int = int.into();
511 // If `int` does not fit in `size` bits, we error instead of letting
512 // `ImmTy::from_int` panic.
513 let size = layout.size;
514 let truncated = truncate(int as u128, size);
515 if sign_extend(truncated, size) as i128 != int {
516 throw_unsup_format!("Signed value {:#x} does not fit in {} bits", int, size.bits())
518 Ok(ImmTy::from_int(int, layout))
521 // FIXME: change `ImmTy::from_uint` so it returns an `InterpResult` instead and remove this
523 pub fn immty_from_uint_checked<'tcx>(
524 int: impl Into<u128>,
525 layout: TyLayout<'tcx>,
526 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
527 let int = int.into();
528 // If `int` does not fit in `size` bits, we error instead of letting
529 // `ImmTy::from_int` panic.
530 let size = layout.size;
531 if truncate(int, size) != int {
532 throw_unsup_format!("Unsigned value {:#x} does not fit in {} bits", int, size.bits())
534 Ok(ImmTy::from_uint(int, layout))