1 use std::convert::{TryFrom, TryInto};
3 use std::num::NonZeroUsize;
8 use rustc_middle::ty::{self, List, TyCtxt, layout::TyAndLayout};
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_target::abi::{LayoutOf, Size, FieldsShape, Variants};
16 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
18 /// Gets an instance for a path.
19 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
22 .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
24 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
25 let mut items = tcx.item_children(krate);
26 let mut path_it = path.iter().skip(1).peekable();
28 while let Some(segment) = path_it.next() {
29 for item in mem::replace(&mut items, Default::default()).iter() {
30 if item.ident.name.as_str() == *segment {
31 if path_it.peek().is_none() {
32 return Some(item.res.def_id());
35 items = tcx.item_children(item.res.def_id());
44 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
45 /// Gets an instance for a path.
46 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
47 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)
48 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path));
49 ty::Instance::mono(self.eval_context_ref().tcx.tcx, did)
52 /// Evaluates the scalar at the specified path. Returns Some(val)
53 /// if the path could be resolved, and None otherwise
57 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
58 let this = self.eval_context_mut();
59 let instance = this.resolve_path(path);
60 let cid = GlobalId { instance, promoted: None };
61 let const_val = this.const_eval_raw(cid)?;
62 let const_val = this.read_scalar(const_val.into())?;
66 /// Helper function to get a `libc` constant as a `Scalar`.
67 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
68 self.eval_context_mut()
69 .eval_path_scalar(&["libc", name])?
73 /// Helper function to get a `libc` constant as an `i32`.
74 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
75 // TODO: Cache the result.
76 self.eval_libc(name)?.to_i32()
79 /// Helper function to get a `windows` constant as a `Scalar`.
80 fn eval_windows(&mut self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
81 self.eval_context_mut()
82 .eval_path_scalar(&["std", "sys", "windows", module, name])?
86 /// Helper function to get a `windows` constant as an `u64`.
87 fn eval_windows_u64(&mut self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
88 // TODO: Cache the result.
89 self.eval_windows(module, name)?.to_u64()
92 /// Helper function to get the `TyAndLayout` of a `libc` type
93 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
94 let this = self.eval_context_mut();
95 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
99 /// Helper function to get the `TyAndLayout` of a `windows` type
100 fn windows_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
101 let this = self.eval_context_mut();
102 let ty = this.resolve_path(&["std", "sys", "windows", "c", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
106 /// Write a 0 of the appropriate size to `dest`.
107 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
108 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
111 /// Test if this immediate equals 0.
112 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
113 let this = self.eval_context_ref();
114 let null = Scalar::null_ptr(this);
115 this.ptr_eq(val, null)
118 /// Turn a Scalar into an Option<NonNullScalar>
119 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
120 let this = self.eval_context_ref();
121 Ok(if this.is_null(val)? { None } else { Some(val) })
124 /// Get the `Place` for a local
125 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
126 let this = self.eval_context_mut();
127 let place = mir::Place { local: local, projection: List::empty() };
128 this.eval_place(place)
131 /// Generate some random bytes, and write them to `dest`.
132 fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
133 // Some programs pass in a null pointer and a length of 0
134 // to their platform's random-generation function (e.g. getrandom())
135 // on Linux. For compatibility with these programs, we don't perform
136 // any additional checks - it's okay if the pointer is invalid,
137 // since we wouldn't actually be writing to it.
141 let this = self.eval_context_mut();
143 let mut data = vec![0; usize::try_from(len).unwrap()];
145 if this.machine.communicate {
146 // Fill the buffer using the host's rng.
147 getrandom::getrandom(&mut data)
148 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
150 let rng = this.memory.extra.rng.get_mut();
151 rng.fill_bytes(&mut data);
154 this.memory.write_bytes(ptr, data.iter().copied())
157 /// Call a function: Push the stack frame and pass the arguments.
158 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
161 f: ty::Instance<'tcx>,
162 args: &[Immediate<Tag>],
163 dest: Option<PlaceTy<'tcx, Tag>>,
164 stack_pop: StackPopCleanup,
165 ) -> InterpResult<'tcx> {
166 let this = self.eval_context_mut();
169 let mir = &*this.load_mir(f.def, None)?;
170 this.push_stack_frame(f, mir, dest, stack_pop)?;
172 // Initialize arguments.
173 let mut callee_args = this.frame().body.args_iter();
175 let callee_arg = this.local_place(
176 callee_args.next().expect("callee has fewer arguments than expected"),
178 this.write_immediate(*arg, callee_arg)?;
180 callee_args.next().expect_none("callee has more arguments than expected");
185 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
186 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
187 fn visit_freeze_sensitive(
189 place: MPlaceTy<'tcx, Tag>,
191 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
192 ) -> InterpResult<'tcx> {
193 let this = self.eval_context_ref();
194 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
197 this.size_and_align_of_mplace(place)?
198 .map(|(size, _)| size)
199 .unwrap_or_else(|| place.layout.size)
201 // Store how far we proceeded into the place so far. Everything to the left of
202 // this offset has already been handled, in the sense that the frozen parts
203 // have had `action` called on them.
204 let mut end_ptr = place.ptr.assert_ptr();
205 // Called when we detected an `UnsafeCell` at the given offset and size.
206 // Calls `action` and advances `end_ptr`.
207 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
208 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
209 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
210 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
211 // We assume that we are given the fields in increasing offset order,
212 // and nothing else changes.
213 let unsafe_cell_offset = unsafe_cell_ptr.offset;
214 let end_offset = end_ptr.offset;
215 assert!(unsafe_cell_offset >= end_offset);
216 let frozen_size = unsafe_cell_offset - end_offset;
217 // Everything between the end_ptr and this `UnsafeCell` is frozen.
218 if frozen_size != Size::ZERO {
219 action(end_ptr, frozen_size, /*frozen*/ true)?;
221 // This `UnsafeCell` is NOT frozen.
222 if unsafe_cell_size != Size::ZERO {
223 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
225 // Update end end_ptr.
226 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
232 let mut visitor = UnsafeCellVisitor {
234 unsafe_cell_action: |place| {
235 trace!("unsafe_cell_action on {:?}", place.ptr);
236 // We need a size to go on.
237 let unsafe_cell_size = this
238 .size_and_align_of_mplace(place)?
239 .map(|(size, _)| size)
240 // for extern types, just cover what we can
241 .unwrap_or_else(|| place.layout.size);
242 // Now handle this `UnsafeCell`, unless it is empty.
243 if unsafe_cell_size != Size::ZERO {
244 unsafe_cell_action(place.ptr, unsafe_cell_size)
250 visitor.visit_value(place)?;
252 // The part between the end_ptr and the end of the place is also frozen.
253 // So pretend there is a 0-sized `UnsafeCell` at the end.
254 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
258 /// Visiting the memory covered by a `MemPlace`, being aware of
259 /// whether we are inside an `UnsafeCell` or not.
260 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
262 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
264 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
265 unsafe_cell_action: F,
268 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
269 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
271 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
273 type V = MPlaceTy<'tcx, Tag>;
276 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
280 // Hook to detect `UnsafeCell`.
281 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
282 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
283 let is_unsafe_cell = match v.layout.ty.kind {
285 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
289 // We do not have to recurse further, this is an `UnsafeCell`.
290 (self.unsafe_cell_action)(v)
291 } else if self.ecx.type_is_freeze(v.layout.ty) {
292 // This is `Freeze`, there cannot be an `UnsafeCell`
294 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
295 // A (non-frozen) union. We fall back to whatever the type says.
296 (self.unsafe_cell_action)(v)
298 // We want to not actually read from memory for this visit. So, before
299 // walking this value, we have to make sure it is not a
300 // `Variants::Multiple`.
301 match v.layout.variants {
302 Variants::Multiple { .. } => {
303 // A multi-variant enum, or generator, or so.
304 // Treat this like a union: without reading from memory,
305 // we cannot determine the variant we are in. Reading from
306 // memory would be subject to Stacked Borrows rules, leading
307 // to all sorts of "funny" recursion.
308 // We only end up here if the type is *not* freeze, so we just call the
309 // `UnsafeCell` action.
310 (self.unsafe_cell_action)(v)
312 Variants::Single { .. } => {
313 // Proceed further, try to find where exactly that `UnsafeCell`
321 // Make sure we visit aggregrates in increasing offset order.
324 place: MPlaceTy<'tcx, Tag>,
325 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
326 ) -> InterpResult<'tcx> {
327 match place.layout.fields {
328 FieldsShape::Array { .. } => {
329 // For the array layout, we know the iterator will yield sorted elements so
330 // we can avoid the allocation.
331 self.walk_aggregate(place, fields)
333 FieldsShape::Arbitrary { .. } => {
334 // Gather the subplaces and sort them before visiting.
336 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
337 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
338 self.walk_aggregate(place, places.into_iter().map(Ok))
340 FieldsShape::Union { .. } | FieldsShape::Primitive => {
342 bug!("unions/primitives are not aggregates we should ever visit")
347 fn visit_union(&mut self, _v: MPlaceTy<'tcx, Tag>, _fields: NonZeroUsize) -> InterpResult<'tcx> {
348 bug!("we should have already handled unions in `visit_value`")
353 // Writes several `ImmTy`s contiguously into memory. This is useful when you have to pack
354 // different values into a struct.
355 fn write_packed_immediates(
357 place: MPlaceTy<'tcx, Tag>,
358 imms: &[ImmTy<'tcx, Tag>],
359 ) -> InterpResult<'tcx> {
360 let this = self.eval_context_mut();
362 let mut offset = Size::from_bytes(0);
365 this.write_immediate_to_mplace(
367 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
369 offset += imm.layout.size;
374 /// Helper function used inside the shims of foreign functions to check that isolation is
375 /// disabled. It returns an error using the `name` of the foreign function if this is not the
377 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
378 if !self.eval_context_ref().machine.communicate {
379 isolation_error(name)?;
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 /// Get last error variable as a place, lazily allocating thread-local storage for it if
399 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
400 let this = self.eval_context_mut();
401 if let Some(errno_place) = this.active_thread_ref().last_error {
404 // Allocate new place, set initial value to 0.
405 let errno_layout = this.machine.layouts.u32;
406 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into());
407 this.write_scalar(Scalar::from_u32(0), errno_place.into())?;
408 this.active_thread_mut().last_error = Some(errno_place);
413 /// Sets the last error variable.
414 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
415 let this = self.eval_context_mut();
416 let errno_place = this.last_error_place()?;
417 this.write_scalar(scalar, errno_place.into())
420 /// Gets the last error variable.
421 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
422 let this = self.eval_context_mut();
423 let errno_place = this.last_error_place()?;
424 this.read_scalar(errno_place.into())?.check_init()
427 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
428 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
429 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
430 use std::io::ErrorKind::*;
431 let this = self.eval_context_mut();
432 let target = &this.tcx.sess.target.target;
433 let target_os = &target.target_os;
434 let last_error = if target.options.target_family == Some("unix".to_owned()) {
435 this.eval_libc(match e.kind() {
436 ConnectionRefused => "ECONNREFUSED",
437 ConnectionReset => "ECONNRESET",
438 PermissionDenied => "EPERM",
439 BrokenPipe => "EPIPE",
440 NotConnected => "ENOTCONN",
441 ConnectionAborted => "ECONNABORTED",
442 AddrNotAvailable => "EADDRNOTAVAIL",
443 AddrInUse => "EADDRINUSE",
444 NotFound => "ENOENT",
445 Interrupted => "EINTR",
446 InvalidInput => "EINVAL",
447 TimedOut => "ETIMEDOUT",
448 AlreadyExists => "EEXIST",
449 WouldBlock => "EWOULDBLOCK",
451 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
454 } else if target_os == "windows" {
455 // FIXME: we have to finish implementing the Windows equivalent of this.
456 this.eval_windows("c", match e.kind() {
457 NotFound => "ERROR_FILE_NOT_FOUND",
458 _ => throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
461 throw_unsup_format!("setting the last OS error from an io::Error is unsupported for {}.", target_os)
463 this.set_last_error(last_error)
466 /// Helper function that consumes an `std::io::Result<T>` and returns an
467 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
468 /// `Ok(-1)` and sets the last OS error accordingly.
470 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
471 /// functions return different integer types (like `read`, that returns an `i64`).
472 fn try_unwrap_io_result<T: From<i32>>(
474 result: std::io::Result<T>,
475 ) -> InterpResult<'tcx, T> {
479 self.eval_context_mut().set_last_error_from_io_error(e)?;
485 fn read_scalar_at_offset(
489 layout: TyAndLayout<'tcx>,
490 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
491 let this = self.eval_context_ref();
492 let op_place = this.deref_operand(op)?;
493 let offset = Size::from_bytes(offset);
494 // Ensure that the following read at an offset is within bounds
495 assert!(op_place.layout.size >= offset + layout.size);
496 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
497 this.read_scalar(value_place.into())
500 fn write_scalar_at_offset(
504 value: impl Into<ScalarMaybeUninit<Tag>>,
505 layout: TyAndLayout<'tcx>,
506 ) -> InterpResult<'tcx, ()> {
507 let this = self.eval_context_mut();
508 let op_place = this.deref_operand(op)?;
509 let offset = Size::from_bytes(offset);
510 // Ensure that the following read at an offset is within bounds
511 assert!(op_place.layout.size >= offset + layout.size);
512 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
513 this.write_scalar(value, value_place.into())
517 /// Check that the number of args is what we expect.
518 pub fn check_arg_count<'a, 'tcx, const N: usize>(args: &'a [OpTy<'tcx, Tag>]) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
519 where &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]> {
520 if let Ok(ops) = args.try_into() {
523 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
526 pub fn isolation_error(name: &str) -> InterpResult<'static> {
527 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
528 "`{}` not available when isolation is enabled",
533 pub fn immty_from_int_checked<'tcx>(
534 int: impl Into<i128>,
535 layout: TyAndLayout<'tcx>,
536 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
537 let int = int.into();
538 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
539 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
543 pub fn immty_from_uint_checked<'tcx>(
544 int: impl Into<u128>,
545 layout: TyAndLayout<'tcx>,
546 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
547 let int = int.into();
548 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
549 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())