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 resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> InterpResult<'tcx, 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());
45 err_unsup_format!("failed to find required Rust item: {:?}", 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 { 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: u64) -> 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; usize::try_from(len).unwrap()];
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>, fields: usize) -> InterpResult<'tcx> {
304 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
306 // With unions, we fall back to whatever the type says, to hopefully be consistent
308 // FIXME: are we consistent, and is this really the behavior we want?
309 let frozen = self.ecx.type_is_freeze(v.layout.ty);
310 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
315 /// Helper function to get a `libc` constant as a `Scalar`.
316 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
317 self.eval_context_mut()
318 .eval_path_scalar(&["libc", name])?
319 .ok_or_else(|| err_unsup_format!("Path libc::{} cannot be resolved.", name))?
323 /// Helper function to get a `libc` constant as an `i32`.
324 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
325 self.eval_libc(name)?.to_i32()
328 /// Helper function to get the `TyLayout` of a `libc` type
329 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
330 let this = self.eval_context_mut();
331 let ty = this.resolve_path(&["libc", name])?.monomorphic_ty(*this.tcx);
335 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
336 // different values into a struct.
337 fn write_packed_immediates(
339 place: MPlaceTy<'tcx, Tag>,
340 imms: &[ImmTy<'tcx, Tag>],
341 ) -> InterpResult<'tcx> {
342 let this = self.eval_context_mut();
344 let mut offset = Size::from_bytes(0);
347 this.write_immediate_to_mplace(
349 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
351 offset += imm.layout.size;
356 /// Helper function used inside the shims of foreign functions to check that isolation is
357 /// disabled. It returns an error using the `name` of the foreign function if this is not the
359 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
360 if !self.eval_context_ref().machine.communicate {
362 "`{}` not available when isolation is enabled (pass the flag `-Zmiri-disable-isolation` to disable isolation)",
368 /// Helper function used inside the shims of foreign functions to assert that the target
369 /// platform is `platform`. It panics showing a message with the `name` of the foreign function
370 /// if this is not the case.
371 fn assert_platform(&self, platform: &str, name: &str) {
373 self.eval_context_ref().tcx.sess.target.target.target_os,
375 "`{}` is only available on the `{}` platform",
381 /// Sets the last error variable.
382 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
383 let this = self.eval_context_mut();
384 let errno_place = this.machine.last_error.unwrap();
385 this.write_scalar(scalar, errno_place.into())
388 /// Gets the last error variable.
389 fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
390 let this = self.eval_context_ref();
391 let errno_place = this.machine.last_error.unwrap();
392 this.read_scalar(errno_place.into())?.not_undef()
395 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
396 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
397 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
398 use std::io::ErrorKind::*;
399 let this = self.eval_context_mut();
400 let target = &this.tcx.tcx.sess.target.target;
401 let last_error = if target.options.target_family == Some("unix".to_owned()) {
402 this.eval_libc(match e.kind() {
403 ConnectionRefused => "ECONNREFUSED",
404 ConnectionReset => "ECONNRESET",
405 PermissionDenied => "EPERM",
406 BrokenPipe => "EPIPE",
407 NotConnected => "ENOTCONN",
408 ConnectionAborted => "ECONNABORTED",
409 AddrNotAvailable => "EADDRNOTAVAIL",
410 AddrInUse => "EADDRINUSE",
411 NotFound => "ENOENT",
412 Interrupted => "EINTR",
413 InvalidInput => "EINVAL",
414 TimedOut => "ETIMEDOUT",
415 AlreadyExists => "EEXIST",
416 WouldBlock => "EWOULDBLOCK",
418 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
422 // FIXME: we have to implement the Windows equivalent of this.
424 "setting the last OS error from an io::Error is unsupported for {}.",
428 this.set_last_error(last_error)
431 /// Helper function that consumes an `std::io::Result<T>` and returns an
432 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
433 /// `Ok(-1)` and sets the last OS error accordingly.
435 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
436 /// functions return different integer types (like `read`, that returns an `i64`).
437 fn try_unwrap_io_result<T: From<i32>>(
439 result: std::io::Result<T>,
440 ) -> InterpResult<'tcx, T> {
444 self.eval_context_mut().set_last_error_from_io_error(e)?;
450 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
451 /// the Unix APIs usually handle.
452 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
457 #[cfg(target_os = "unix")]
458 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
459 Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
461 #[cfg(not(target_os = "unix"))]
462 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
463 let s = std::str::from_utf8(bytes)
464 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
468 let this = self.eval_context_ref();
469 let bytes = this.memory.read_c_str(scalar)?;
470 bytes_to_os_str(bytes)
473 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
474 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
475 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
476 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
477 /// string length returned does not include the null terminator.
478 fn write_os_str_to_c_str(
483 ) -> InterpResult<'tcx, (bool, u64)> {
484 #[cfg(target_os = "unix")]
485 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
486 std::os::unix::ffi::OsStringExt::into_bytes(os_str)
488 #[cfg(not(target_os = "unix"))]
489 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
490 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
491 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
495 .map(|s| s.as_bytes())
496 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
499 let bytes = os_str_to_bytes(os_str)?;
500 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
501 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
502 let string_length = u64::try_from(bytes.len()).unwrap();
503 if size <= string_length {
504 return Ok((false, string_length));
506 self.eval_context_mut()
508 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
509 Ok((true, string_length))
512 fn alloc_os_str_as_c_str(
515 memkind: MemoryKind<MiriMemoryKind>,
517 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
518 let this = self.eval_context_mut();
520 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
521 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
522 self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap();
523 arg_place.ptr.assert_ptr()
527 pub fn immty_from_int_checked<'tcx>(
528 int: impl Into<i128>,
529 layout: TyLayout<'tcx>,
530 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
531 let int = int.into();
532 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
533 err_unsup_format!("Signed value {:#x} does not fit in {} bits", int, layout.size.bits())
537 pub fn immty_from_uint_checked<'tcx>(
538 int: impl Into<u128>,
539 layout: TyLayout<'tcx>,
540 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
541 let int = int.into();
542 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
543 err_unsup_format!("Signed value {:#x} does not fit in {} bits", int, layout.size.bits())