4 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
8 layout::{self, LayoutOf, Size, TyLayout},
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 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 { 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])?.monomorphic_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, MemPlaceMeta::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.",
371 /// Helper function used inside the shims of foreign functions to check that the target
372 /// platform is `platform`. It returns an error using the `name` of the foreign function if
373 /// this is not the case.
374 fn check_platform(&mut self, platform: &str, name: &str) -> InterpResult<'tcx> {
375 if self.eval_context_mut().tcx.sess.target.target.target_os.to_lowercase() != platform {
377 "`{}` is only available in the `{}` platform",
385 /// Sets the last error variable.
386 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
387 let this = self.eval_context_mut();
388 let errno_place = this.machine.last_error.unwrap();
389 this.write_scalar(scalar, errno_place.into())
392 /// Gets the last error variable.
393 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
394 let this = self.eval_context_mut();
395 let errno_place = this.machine.last_error.unwrap();
396 this.read_scalar(errno_place.into())?.not_undef()
399 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
400 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
401 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
402 use std::io::ErrorKind::*;
403 let this = self.eval_context_mut();
404 let target = &this.tcx.tcx.sess.target.target;
405 let last_error = if target.options.target_family == Some("unix".to_owned()) {
406 this.eval_libc(match e.kind() {
407 ConnectionRefused => "ECONNREFUSED",
408 ConnectionReset => "ECONNRESET",
409 PermissionDenied => "EPERM",
410 BrokenPipe => "EPIPE",
411 NotConnected => "ENOTCONN",
412 ConnectionAborted => "ECONNABORTED",
413 AddrNotAvailable => "EADDRNOTAVAIL",
414 AddrInUse => "EADDRINUSE",
415 NotFound => "ENOENT",
416 Interrupted => "EINTR",
417 InvalidInput => "EINVAL",
418 TimedOut => "ETIMEDOUT",
419 AlreadyExists => "EEXIST",
420 WouldBlock => "EWOULDBLOCK",
422 throw_unsup_format!("The {} error cannot be transformed into a raw os error", e)
426 // FIXME: we have to implement the Windows equivalent of this.
428 "Setting the last OS error from an io::Error is unsupported for {}.",
432 this.set_last_error(last_error)
435 /// Helper function that consumes an `std::io::Result<T>` and returns an
436 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
437 /// `Ok(-1)` and sets the last OS error accordingly.
439 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
440 /// functions return different integer types (like `read`, that returns an `i64`).
441 fn try_unwrap_io_result<T: From<i32>>(
443 result: std::io::Result<T>,
444 ) -> InterpResult<'tcx, T> {
448 self.eval_context_mut().set_last_error_from_io_error(e)?;
454 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
455 /// the Unix APIs usually handle.
456 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
461 #[cfg(target_os = "unix")]
462 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
463 Ok(std::os::unix::ffi::OsStringExt::from_bytes(bytes))
465 #[cfg(not(target_os = "unix"))]
466 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
467 let s = std::str::from_utf8(bytes)
468 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
472 let this = self.eval_context_ref();
473 let bytes = this.memory.read_c_str(scalar)?;
474 bytes_to_os_str(bytes)
477 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
478 /// the Unix APIs usually handle. This function returns `Ok(false)` without trying to write if
479 /// `size` is not large enough to fit the contents of `os_string` plus a null terminator. It
480 /// returns `Ok(true)` if the writing process was successful.
481 fn write_os_str_to_c_str(
486 ) -> InterpResult<'tcx, bool> {
487 #[cfg(target_os = "unix")]
488 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
489 std::os::unix::ffi::OsStringExt::into_bytes(os_str)
491 #[cfg(not(target_os = "unix"))]
492 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
493 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
494 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
498 .map(|s| s.as_bytes())
499 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
502 let bytes = os_str_to_bytes(os_str)?;
503 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
504 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
505 if size <= bytes.len() as u64 {
508 self.eval_context_mut()
510 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
514 fn alloc_os_str_as_c_str(
517 memkind: MemoryKind<MiriMemoryKind>
519 let size = os_str.len() as u64 + 1; // Make space for `0` terminator.
520 let this = self.eval_context_mut();
522 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
523 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
524 self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap();
525 arg_place.ptr.assert_ptr()
529 pub fn immty_from_int_checked<'tcx>(
530 int: impl Into<i128>,
531 layout: TyLayout<'tcx>,
532 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
533 let int = int.into();
534 Ok(ImmTy::try_from_int(int, layout).ok_or_else(||
535 err_unsup_format!("Signed value {:#x} does not fit in {} bits", int, layout.size.bits())
539 pub fn immty_from_uint_checked<'tcx>(
540 int: impl Into<u128>,
541 layout: TyLayout<'tcx>,
542 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
543 let int = int.into();
544 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(||
545 err_unsup_format!("Signed value {:#x} does not fit in {} bits", int, layout.size.bits())