5 use std::num::NonZeroUsize;
6 use std::time::Duration;
10 use rustc_hir::def::{DefKind, Namespace};
11 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
12 use rustc_middle::mir;
13 use rustc_middle::ty::{
15 layout::{LayoutOf, TyAndLayout},
18 use rustc_span::{def_id::CrateNum, sym, Span, Symbol};
19 use rustc_target::abi::{Align, FieldsShape, Size, Variants};
20 use rustc_target::spec::abi::Abi;
26 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
28 // This mapping should match `decode_error_kind` in
29 // <https://github.com/rust-lang/rust/blob/master/library/std/src/sys/unix/mod.rs>.
30 const UNIX_IO_ERROR_TABLE: &[(&str, std::io::ErrorKind)] = {
31 use std::io::ErrorKind::*;
33 ("E2BIG", ArgumentListTooLong),
34 ("EADDRINUSE", AddrInUse),
35 ("EADDRNOTAVAIL", AddrNotAvailable),
36 ("EBUSY", ResourceBusy),
37 ("ECONNABORTED", ConnectionAborted),
38 ("ECONNREFUSED", ConnectionRefused),
39 ("ECONNRESET", ConnectionReset),
40 ("EDEADLK", Deadlock),
41 ("EDQUOT", FilesystemQuotaExceeded),
42 ("EEXIST", AlreadyExists),
43 ("EFBIG", FileTooLarge),
44 ("EHOSTUNREACH", HostUnreachable),
45 ("EINTR", Interrupted),
46 ("EINVAL", InvalidInput),
47 ("EISDIR", IsADirectory),
48 ("ELOOP", FilesystemLoop),
50 ("ENOMEM", OutOfMemory),
51 ("ENOSPC", StorageFull),
52 ("ENOSYS", Unsupported),
53 ("EMLINK", TooManyLinks),
54 ("ENAMETOOLONG", InvalidFilename),
55 ("ENETDOWN", NetworkDown),
56 ("ENETUNREACH", NetworkUnreachable),
57 ("ENOTCONN", NotConnected),
58 ("ENOTDIR", NotADirectory),
59 ("ENOTEMPTY", DirectoryNotEmpty),
60 ("EPIPE", BrokenPipe),
61 ("EROFS", ReadOnlyFilesystem),
62 ("ESPIPE", NotSeekable),
63 ("ESTALE", StaleNetworkFileHandle),
64 ("ETIMEDOUT", TimedOut),
65 ("ETXTBSY", ExecutableFileBusy),
66 ("EXDEV", CrossesDevices),
67 // The following have two valid options. We have both for the forwards mapping; only the
68 // first one will be used for the backwards mapping.
69 ("EPERM", PermissionDenied),
70 ("EACCES", PermissionDenied),
71 ("EWOULDBLOCK", WouldBlock),
72 ("EAGAIN", WouldBlock),
76 /// Gets an instance for a path.
78 /// A `None` namespace indicates we are looking for a module.
79 fn try_resolve_did(tcx: TyCtxt<'_>, path: &[&str], namespace: Option<Namespace>) -> Option<DefId> {
80 /// Yield all children of the given item, that have the given name.
81 fn find_children<'tcx: 'a, 'a>(
85 ) -> impl Iterator<Item = DefId> + 'a {
86 tcx.module_children(item)
88 .filter(move |item| item.ident.name.as_str() == name)
89 .map(move |item| item.res.def_id())
92 // Take apart the path: leading crate, a sequence of modules, and potentially a final item.
93 let (&crate_name, path) = path.split_first().expect("paths must have at least one segment");
94 let (modules, item) = if let Some(namespace) = namespace {
95 let (&item_name, modules) =
96 path.split_last().expect("non-module paths must have at least 2 segments");
97 (modules, Some((item_name, namespace)))
102 // First find the crate.
104 tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == crate_name)?;
105 let mut cur_item = DefId { krate: *krate, index: CRATE_DEF_INDEX };
106 // Then go over the modules.
107 for &segment in modules {
108 cur_item = find_children(tcx, cur_item, segment)
109 .find(|item| tcx.def_kind(item) == DefKind::Mod)?;
111 // Finally, look up the desired item in this module, if any.
113 Some((item_name, namespace)) =>
115 find_children(tcx, cur_item, item_name)
116 .find(|item| tcx.def_kind(item).ns() == Some(namespace))?,
118 None => Some(cur_item),
122 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
123 /// Checks if the given crate/module exists.
124 fn have_module(&self, path: &[&str]) -> bool {
125 try_resolve_did(*self.eval_context_ref().tcx, path, None).is_some()
128 /// Gets an instance for a path; fails gracefully if the path does not exist.
129 fn try_resolve_path(&self, path: &[&str], namespace: Namespace) -> Option<ty::Instance<'tcx>> {
130 let tcx = self.eval_context_ref().tcx.tcx;
131 let did = try_resolve_did(tcx, path, Some(namespace))?;
132 Some(ty::Instance::mono(tcx, did))
135 /// Gets an instance for a path.
136 fn resolve_path(&self, path: &[&str], namespace: Namespace) -> ty::Instance<'tcx> {
137 self.try_resolve_path(path, namespace)
138 .unwrap_or_else(|| panic!("failed to find required Rust item: {path:?}"))
141 /// Evaluates the scalar at the specified path. Returns Some(val)
142 /// if the path could be resolved, and None otherwise
143 fn eval_path_scalar(&self, path: &[&str]) -> InterpResult<'tcx, Scalar<Provenance>> {
144 let this = self.eval_context_ref();
145 let instance = this.resolve_path(path, Namespace::ValueNS);
146 let cid = GlobalId { instance, promoted: None };
147 // We don't give a span -- this isn't actually used directly by the program anyway.
148 let const_val = this.eval_global(cid, None)?;
149 this.read_scalar(&const_val.into())
152 /// Helper function to get a `libc` constant as a `Scalar`.
153 fn eval_libc(&self, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
154 self.eval_path_scalar(&["libc", name])
157 /// Helper function to get a `libc` constant as an `i32`.
158 fn eval_libc_i32(&self, name: &str) -> InterpResult<'tcx, i32> {
159 // TODO: Cache the result.
160 self.eval_libc(name)?.to_i32()
163 /// Helper function to get a `windows` constant as a `Scalar`.
164 fn eval_windows(&self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
165 self.eval_context_ref().eval_path_scalar(&["std", "sys", "windows", module, name])
168 /// Helper function to get a `windows` constant as a `u64`.
169 fn eval_windows_u64(&self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
170 // TODO: Cache the result.
171 self.eval_windows(module, name)?.to_u64()
174 /// Helper function to get the `TyAndLayout` of a `libc` type
175 fn libc_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
176 let this = self.eval_context_ref();
178 .resolve_path(&["libc", name], Namespace::TypeNS)
179 .ty(*this.tcx, ty::ParamEnv::reveal_all());
183 /// Helper function to get the `TyAndLayout` of a `windows` type
184 fn windows_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
185 let this = self.eval_context_ref();
187 .resolve_path(&["std", "sys", "windows", "c", name], Namespace::TypeNS)
188 .ty(*this.tcx, ty::ParamEnv::reveal_all());
192 /// Project to the given *named* field of the mplace (which must be a struct or union type).
193 fn mplace_field_named(
195 mplace: &MPlaceTy<'tcx, Provenance>,
197 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
198 let this = self.eval_context_ref();
199 let adt = mplace.layout.ty.ty_adt_def().unwrap();
200 for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
201 if field.name.as_str() == name {
202 return this.mplace_field(mplace, idx);
205 bug!("No field named {} in type {}", name, mplace.layout.ty);
208 /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
209 /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
210 /// this method is fine for almost all integer types.
214 dest: &PlaceTy<'tcx, Provenance>,
215 ) -> InterpResult<'tcx> {
216 assert!(dest.layout.abi.is_scalar(), "write_int on non-scalar type {}", dest.layout.ty);
217 let val = if dest.layout.abi.is_signed() {
218 Scalar::from_int(i, dest.layout.size)
220 Scalar::from_uint(u64::try_from(i.into()).unwrap(), dest.layout.size)
222 self.eval_context_mut().write_scalar(val, dest)
225 /// Write the first N fields of the given place.
229 dest: &MPlaceTy<'tcx, Provenance>,
230 ) -> InterpResult<'tcx> {
231 let this = self.eval_context_mut();
232 for (idx, &val) in values.iter().enumerate() {
233 let field = this.mplace_field(dest, idx)?;
234 this.write_int(val, &field.into())?;
239 /// Write the given fields of the given place.
240 fn write_int_fields_named(
242 values: &[(&str, i128)],
243 dest: &MPlaceTy<'tcx, Provenance>,
244 ) -> InterpResult<'tcx> {
245 let this = self.eval_context_mut();
246 for &(name, val) in values.iter() {
247 let field = this.mplace_field_named(dest, name)?;
248 this.write_int(val, &field.into())?;
253 /// Write a 0 of the appropriate size to `dest`.
254 fn write_null(&mut self, dest: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
255 self.write_int(0, dest)
258 /// Test if this pointer equals 0.
259 fn ptr_is_null(&self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, bool> {
260 Ok(ptr.addr().bytes() == 0)
263 /// Get the `Place` for a local
264 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Provenance>> {
265 let this = self.eval_context_mut();
266 let place = mir::Place { local, projection: List::empty() };
267 this.eval_place(place)
270 /// Generate some random bytes, and write them to `dest`.
271 fn gen_random(&mut self, ptr: Pointer<Option<Provenance>>, len: u64) -> InterpResult<'tcx> {
272 // Some programs pass in a null pointer and a length of 0
273 // to their platform's random-generation function (e.g. getrandom())
274 // on Linux. For compatibility with these programs, we don't perform
275 // any additional checks - it's okay if the pointer is invalid,
276 // since we wouldn't actually be writing to it.
280 let this = self.eval_context_mut();
282 let mut data = vec![0; usize::try_from(len).unwrap()];
284 if this.machine.communicate() {
285 // Fill the buffer using the host's rng.
286 getrandom::getrandom(&mut data)
287 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
289 let rng = this.machine.rng.get_mut();
290 rng.fill_bytes(&mut data);
293 this.write_bytes_ptr(ptr, data.iter().copied())
296 /// Call a function: Push the stack frame and pass the arguments.
297 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
299 /// If you do not provie a return place, a dangling zero-sized place will be created
300 /// for your convenience.
303 f: ty::Instance<'tcx>,
305 args: &[Immediate<Provenance>],
306 dest: Option<&PlaceTy<'tcx, Provenance>>,
307 stack_pop: StackPopCleanup,
308 ) -> InterpResult<'tcx> {
309 let this = self.eval_context_mut();
310 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
311 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
312 if this.machine.enforce_abi && callee_abi != caller_abi {
314 "calling a function with ABI {} using caller ABI {}",
321 let mir = this.load_mir(f.def, None)?;
322 let dest = match dest {
323 Some(dest) => dest.clone(),
324 None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?).into(),
326 this.push_stack_frame(f, mir, &dest, stack_pop)?;
328 // Initialize arguments.
329 let mut callee_args = this.frame().body.args_iter();
331 let callee_arg = this.local_place(
334 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
336 this.write_immediate(*arg, &callee_arg)?;
338 if callee_args.next().is_some() {
339 throw_ub_format!("callee has more arguments than expected");
345 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
346 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
347 /// The range is relative to `place`.
348 fn visit_freeze_sensitive(
350 place: &MPlaceTy<'tcx, Provenance>,
352 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
353 ) -> InterpResult<'tcx> {
354 let this = self.eval_context_ref();
355 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
358 this.size_and_align_of_mplace(place)?
359 .map(|(size, _)| size)
360 .unwrap_or_else(|| place.layout.size)
362 // Store how far we proceeded into the place so far. Everything to the left of
363 // this offset has already been handled, in the sense that the frozen parts
364 // have had `action` called on them.
365 let start_addr = place.ptr.addr();
366 let mut cur_addr = start_addr;
367 // Called when we detected an `UnsafeCell` at the given offset and size.
368 // Calls `action` and advances `cur_ptr`.
369 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer<Option<Provenance>>,
370 unsafe_cell_size: Size| {
371 // We assume that we are given the fields in increasing offset order,
372 // and nothing else changes.
373 let unsafe_cell_addr = unsafe_cell_ptr.addr();
374 assert!(unsafe_cell_addr >= cur_addr);
375 let frozen_size = unsafe_cell_addr - cur_addr;
376 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
377 if frozen_size != Size::ZERO {
378 action(alloc_range(cur_addr - start_addr, frozen_size), /*frozen*/ true)?;
380 cur_addr += frozen_size;
381 // This `UnsafeCell` is NOT frozen.
382 if unsafe_cell_size != Size::ZERO {
384 alloc_range(cur_addr - start_addr, unsafe_cell_size),
388 cur_addr += unsafe_cell_size;
394 let mut visitor = UnsafeCellVisitor {
396 unsafe_cell_action: |place| {
397 trace!("unsafe_cell_action on {:?}", place.ptr);
398 // We need a size to go on.
399 let unsafe_cell_size = this
400 .size_and_align_of_mplace(place)?
401 .map(|(size, _)| size)
402 // for extern types, just cover what we can
403 .unwrap_or_else(|| place.layout.size);
404 // Now handle this `UnsafeCell`, unless it is empty.
405 if unsafe_cell_size != Size::ZERO {
406 unsafe_cell_action(&place.ptr, unsafe_cell_size)
412 visitor.visit_value(place)?;
414 // The part between the end_ptr and the end of the place is also frozen.
415 // So pretend there is a 0-sized `UnsafeCell` at the end.
416 unsafe_cell_action(&place.ptr.offset(size, this)?, Size::ZERO)?;
420 /// Visiting the memory covered by a `MemPlace`, being aware of
421 /// whether we are inside an `UnsafeCell` or not.
422 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
424 F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
426 ecx: &'ecx MiriInterpCx<'mir, 'tcx>,
427 unsafe_cell_action: F,
430 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, MiriMachine<'mir, 'tcx>>
431 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
433 F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
435 type V = MPlaceTy<'tcx, Provenance>;
438 fn ecx(&self) -> &MiriInterpCx<'mir, 'tcx> {
442 // Hook to detect `UnsafeCell`.
443 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
444 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
445 let is_unsafe_cell = match v.layout.ty.kind() {
447 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
451 // We do not have to recurse further, this is an `UnsafeCell`.
452 (self.unsafe_cell_action)(v)
453 } else if self.ecx.type_is_freeze(v.layout.ty) {
454 // This is `Freeze`, there cannot be an `UnsafeCell`
456 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
457 // A (non-frozen) union. We fall back to whatever the type says.
458 (self.unsafe_cell_action)(v)
460 // We want to not actually read from memory for this visit. So, before
461 // walking this value, we have to make sure it is not a
462 // `Variants::Multiple`.
463 match v.layout.variants {
464 Variants::Multiple { .. } => {
465 // A multi-variant enum, or generator, or so.
466 // Treat this like a union: without reading from memory,
467 // we cannot determine the variant we are in. Reading from
468 // memory would be subject to Stacked Borrows rules, leading
469 // to all sorts of "funny" recursion.
470 // We only end up here if the type is *not* freeze, so we just call the
471 // `UnsafeCell` action.
472 (self.unsafe_cell_action)(v)
474 Variants::Single { .. } => {
475 // Proceed further, try to find where exactly that `UnsafeCell`
483 // Make sure we visit aggregrates in increasing offset order.
486 place: &MPlaceTy<'tcx, Provenance>,
487 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Provenance>>>,
488 ) -> InterpResult<'tcx> {
489 match place.layout.fields {
490 FieldsShape::Array { .. } => {
491 // For the array layout, we know the iterator will yield sorted elements so
492 // we can avoid the allocation.
493 self.walk_aggregate(place, fields)
495 FieldsShape::Arbitrary { .. } => {
496 // Gather the subplaces and sort them before visiting.
497 let mut places = fields
498 .collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Provenance>>>>()?;
499 // we just compare offsets, the abs. value never matters
500 places.sort_by_key(|place| place.ptr.addr());
501 self.walk_aggregate(place, places.into_iter().map(Ok))
503 FieldsShape::Union { .. } | FieldsShape::Primitive => {
505 bug!("unions/primitives are not aggregates we should ever visit")
512 _v: &MPlaceTy<'tcx, Provenance>,
513 _fields: NonZeroUsize,
514 ) -> InterpResult<'tcx> {
515 bug!("we should have already handled unions in `visit_value`")
520 /// Helper function used inside the shims of foreign functions to check that isolation is
521 /// disabled. It returns an error using the `name` of the foreign function if this is not the
523 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
524 if !self.eval_context_ref().machine.communicate() {
525 self.reject_in_isolation(name, RejectOpWith::Abort)?;
530 /// Helper function used inside the shims of foreign functions which reject the op
531 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
532 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
533 let this = self.eval_context_ref();
535 RejectOpWith::Abort => isolation_abort_error(op_name),
536 RejectOpWith::WarningWithoutBacktrace => {
539 .warn(format!("{op_name} was made to return an error due to isolation"));
542 RejectOpWith::Warning => {
543 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
546 RejectOpWith::NoWarning => Ok(()), // no warning
550 /// Helper function used inside the shims of foreign functions to assert that the target OS
551 /// is `target_os`. It panics showing a message with the `name` of the foreign function
552 /// if this is not the case.
553 fn assert_target_os(&self, target_os: &str, name: &str) {
555 self.eval_context_ref().tcx.sess.target.os,
557 "`{}` is only available on the `{}` target OS",
563 /// Helper function used inside the shims of foreign functions to assert that the target OS
564 /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
565 /// if this is not the case.
566 fn assert_target_os_is_unix(&self, name: &str) {
568 target_os_is_unix(self.eval_context_ref().tcx.sess.target.os.as_ref()),
569 "`{}` is only available for supported UNIX family targets",
574 /// Get last error variable as a place, lazily allocating thread-local storage for it if
576 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
577 let this = self.eval_context_mut();
578 if let Some(errno_place) = this.active_thread_ref().last_error {
581 // Allocate new place, set initial value to 0.
582 let errno_layout = this.machine.layouts.u32;
583 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
584 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
585 this.active_thread_mut().last_error = Some(errno_place);
590 /// Sets the last error variable.
591 fn set_last_error(&mut self, scalar: Scalar<Provenance>) -> InterpResult<'tcx> {
592 let this = self.eval_context_mut();
593 let errno_place = this.last_error_place()?;
594 this.write_scalar(scalar, &errno_place.into())
597 /// Gets the last error variable.
598 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Provenance>> {
599 let this = self.eval_context_mut();
600 let errno_place = this.last_error_place()?;
601 this.read_scalar(&errno_place.into())
604 /// This function tries to produce the most similar OS error from the `std::io::ErrorKind`
605 /// as a platform-specific errnum.
606 fn io_error_to_errnum(
608 err_kind: std::io::ErrorKind,
609 ) -> InterpResult<'tcx, Scalar<Provenance>> {
610 let this = self.eval_context_ref();
611 let target = &this.tcx.sess.target;
612 if target.families.iter().any(|f| f == "unix") {
613 for &(name, kind) in UNIX_IO_ERROR_TABLE {
614 if err_kind == kind {
615 return this.eval_libc(name);
618 throw_unsup_format!("io error {:?} cannot be translated into a raw os error", err_kind)
619 } else if target.families.iter().any(|f| f == "windows") {
620 // FIXME: we have to finish implementing the Windows equivalent of this.
621 use std::io::ErrorKind::*;
625 NotFound => "ERROR_FILE_NOT_FOUND",
626 PermissionDenied => "ERROR_ACCESS_DENIED",
629 "io error {:?} cannot be translated into a raw os error",
636 "converting io::Error into errnum is unsupported for OS {}",
642 /// The inverse of `io_error_to_errnum`.
643 #[allow(clippy::needless_return)]
644 fn try_errnum_to_io_error(
646 errnum: Scalar<Provenance>,
647 ) -> InterpResult<'tcx, Option<std::io::ErrorKind>> {
648 let this = self.eval_context_ref();
649 let target = &this.tcx.sess.target;
650 if target.families.iter().any(|f| f == "unix") {
651 let errnum = errnum.to_i32()?;
652 for &(name, kind) in UNIX_IO_ERROR_TABLE {
653 if errnum == this.eval_libc_i32(name)? {
654 return Ok(Some(kind));
657 // Our table is as complete as the mapping in std, so we are okay with saying "that's a
658 // strange one" here.
662 "converting errnum into io::Error is unsupported for OS {}",
668 /// Sets the last OS error using a `std::io::ErrorKind`.
669 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
670 self.set_last_error(self.io_error_to_errnum(err_kind)?)
673 /// Helper function that consumes an `std::io::Result<T>` and returns an
674 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
675 /// `Ok(-1)` and sets the last OS error accordingly.
677 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
678 /// functions return different integer types (like `read`, that returns an `i64`).
679 fn try_unwrap_io_result<T: From<i32>>(
681 result: std::io::Result<T>,
682 ) -> InterpResult<'tcx, T> {
686 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
692 /// Calculates the MPlaceTy given the offset and layout of an access on an operand
693 fn deref_operand_and_offset(
695 op: &OpTy<'tcx, Provenance>,
697 layout: TyAndLayout<'tcx>,
698 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
699 let this = self.eval_context_ref();
700 let op_place = this.deref_operand(op)?; // FIXME: we still deref with the original type!
701 let offset = Size::from_bytes(offset);
703 // Ensure that the access is within bounds.
704 assert!(op_place.layout.size >= offset + layout.size);
705 let value_place = op_place.offset(offset, layout, this)?;
709 fn read_scalar_at_offset(
711 op: &OpTy<'tcx, Provenance>,
713 layout: TyAndLayout<'tcx>,
714 ) -> InterpResult<'tcx, Scalar<Provenance>> {
715 let this = self.eval_context_ref();
716 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
717 this.read_scalar(&value_place.into())
720 fn write_scalar_at_offset(
722 op: &OpTy<'tcx, Provenance>,
724 value: impl Into<Scalar<Provenance>>,
725 layout: TyAndLayout<'tcx>,
726 ) -> InterpResult<'tcx, ()> {
727 let this = self.eval_context_mut();
728 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
729 this.write_scalar(value, &value_place.into())
732 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
733 /// if the value in the `timespec` struct is invalid. Some libc functions will return
734 /// `EINVAL` in this case.
737 tp: &MPlaceTy<'tcx, Provenance>,
738 ) -> InterpResult<'tcx, Option<Duration>> {
739 let this = self.eval_context_mut();
740 let seconds_place = this.mplace_field(tp, 0)?;
741 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
742 let seconds = seconds_scalar.to_machine_isize(this)?;
743 let nanoseconds_place = this.mplace_field(tp, 1)?;
744 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
745 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
748 // tv_sec must be non-negative.
749 let seconds: u64 = seconds.try_into().ok()?;
750 // tv_nsec must be non-negative.
751 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
752 if nanoseconds >= 1_000_000_000 {
753 // tv_nsec must not be greater than 999,999,999.
756 Duration::new(seconds, nanoseconds)
760 /// Read a sequence of bytes until the first null terminator.
761 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, &'a [u8]>
766 let this = self.eval_context_ref();
767 let size1 = Size::from_bytes(1);
769 // Step 1: determine the length.
770 let mut len = Size::ZERO;
772 // FIXME: We are re-getting the allocation each time around the loop.
773 // Would be nice if we could somehow "extend" an existing AllocRange.
774 let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
775 let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
783 // Step 2: get the bytes.
784 this.read_bytes_ptr_strip_provenance(ptr, len)
787 /// Helper function to write a sequence of bytes with an added null-terminator, which is what
788 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
789 /// to write if `size` is not large enough to fit the contents of `c_str` plus a null
790 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
791 /// string length returned does include the null terminator.
795 ptr: Pointer<Option<Provenance>>,
797 ) -> InterpResult<'tcx, (bool, u64)> {
798 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
799 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
800 let string_length = u64::try_from(c_str.len()).unwrap();
801 let string_length = string_length.checked_add(1).unwrap();
802 if size < string_length {
803 return Ok((false, string_length));
805 self.eval_context_mut()
806 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
807 Ok((true, string_length))
810 /// Read a sequence of u16 until the first null terminator.
811 fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {
812 let this = self.eval_context_ref();
813 let size2 = Size::from_bytes(2);
814 let align2 = Align::from_bytes(2).unwrap();
816 let mut wchars = Vec::new();
818 // FIXME: We are re-getting the allocation each time around the loop.
819 // Would be nice if we could somehow "extend" an existing AllocRange.
820 let alloc = this.get_ptr_alloc(ptr, size2, align2)?.unwrap(); // not a ZST, so we will get a result
821 let wchar = alloc.read_integer(alloc_range(Size::ZERO, size2))?.to_u16()?;
826 ptr = ptr.offset(size2, this)?;
833 /// Helper function to write a sequence of u16 with an added 0x0000-terminator, which is what
834 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
835 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
836 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
837 /// string length returned does include the null terminator. Length is measured in units of
842 ptr: Pointer<Option<Provenance>>,
844 ) -> InterpResult<'tcx, (bool, u64)> {
845 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
846 // 0x0000 terminator to memory would cause an out-of-bounds access.
847 let string_length = u64::try_from(wide_str.len()).unwrap();
848 let string_length = string_length.checked_add(1).unwrap();
849 if size < string_length {
850 return Ok((false, string_length));
853 // Store the UTF-16 string.
854 let size2 = Size::from_bytes(2);
855 let this = self.eval_context_mut();
857 .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
858 .unwrap(); // not a ZST, so we will get a result
859 for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
860 let offset = u64::try_from(offset).unwrap();
861 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
863 Ok((true, string_length))
866 /// Check that the ABI is what we expect.
867 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
868 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
870 "calling a function with ABI {} using caller ABI {}",
878 fn frame_in_std(&self) -> bool {
879 let this = self.eval_context_ref();
880 let Some(start_fn) = this.tcx.lang_items().start_fn() else {
884 let frame = this.frame();
885 // Make an attempt to get at the instance of the function this is inlined from.
886 let instance: Option<_> = try {
887 let scope = frame.current_source_info()?.scope;
888 let inlined_parent = frame.body.source_scopes[scope].inlined_parent_scope?;
889 let source = &frame.body.source_scopes[inlined_parent];
890 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
892 // Fall back to the instance of the function itself.
893 let instance = instance.unwrap_or(frame.instance);
894 // Now check if this is in the same crate as start_fn.
895 // As a special exception we also allow unit tests from
896 // <https://github.com/rust-lang/miri-test-libstd/tree/master/std_miri_test> to call these
898 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
899 frame_crate == this.tcx.def_path(start_fn).krate
900 || this.tcx.crate_name(frame_crate).as_str() == "std_miri_test"
903 /// Handler that should be called when unsupported functionality is encountered.
904 /// This function will either panic within the context of the emulated application
905 /// or return an error in the Miri process context
907 /// Return value of `Ok(bool)` indicates whether execution should continue.
908 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
909 let this = self.eval_context_mut();
910 if this.machine.panic_on_unsupported {
911 // message is slightly different here to make automated analysis easier
912 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
913 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
916 throw_unsup_format!("{}", error_msg.as_ref());
920 fn check_abi_and_shim_symbol_clash(
925 ) -> InterpResult<'tcx, ()> {
926 self.check_abi(abi, exp_abi)?;
927 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
928 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
930 span: body.span.data(),
936 fn check_shim<'a, const N: usize>(
941 args: &'a [OpTy<'tcx, Provenance>],
942 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
944 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
946 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
947 check_arg_count(args)
950 /// Mark a machine allocation that was just created as immutable.
951 fn mark_immutable(&mut self, mplace: &MemPlace<Provenance>) {
952 let this = self.eval_context_mut();
953 // This got just allocated, so there definitely is a pointer here.
954 let provenance = mplace.ptr.into_pointer_or_addr().unwrap().provenance;
955 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
958 fn item_link_name(&self, def_id: DefId) -> Symbol {
959 let tcx = self.eval_context_ref().tcx;
960 match tcx.get_attrs(def_id, sym::link_name).filter_map(|a| a.value_str()).next() {
962 None => tcx.item_name(def_id),
967 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
968 /// Get the current span in the topmost function which is workspace-local and not
969 /// `#[track_caller]`.
970 /// This function is backed by a cache, and can be assumed to be very fast.
971 /// It will work even when the stack is empty.
972 pub fn current_span(&self) -> Span {
973 self.top_user_relevant_frame()
974 .map(|frame_idx| self.stack()[frame_idx].current_span())
975 .unwrap_or(rustc_span::DUMMY_SP)
978 /// Returns the span of the *caller* of the current operation, again
979 /// walking down the stack to find the closest frame in a local crate, if the caller of the
980 /// current operation is not in a local crate.
981 /// This is useful when we are processing something which occurs on function-entry and we want
982 /// to point at the call to the function, not the function definition generally.
983 pub fn caller_span(&self) -> Span {
984 // We need to go down at least to the caller (len - 2), or however
985 // far we have to go to find a frame in a local crate which is also not #[track_caller].
986 let frame_idx = self.top_user_relevant_frame().unwrap();
987 let frame_idx = cmp::min(frame_idx, self.stack().len().checked_sub(2).unwrap());
988 self.stack()[frame_idx].current_span()
991 fn stack(&self) -> &[Frame<'mir, 'tcx, Provenance, machine::FrameData<'tcx>>] {
992 self.threads.active_thread_stack()
995 fn top_user_relevant_frame(&self) -> Option<usize> {
996 self.threads.active_thread_ref().top_user_relevant_frame()
999 /// This is the source of truth for the `is_user_relevant` flag in our `FrameExtra`.
1000 pub fn is_user_relevant(&self, frame: &Frame<'mir, 'tcx, Provenance>) -> bool {
1001 let def_id = frame.instance.def_id();
1002 (def_id.is_local() || self.local_crates.contains(&def_id.krate))
1003 && !frame.instance.def.requires_caller_location(self.tcx)
1007 /// Check that the number of args is what we expect.
1008 pub fn check_arg_count<'a, 'tcx, const N: usize>(
1009 args: &'a [OpTy<'tcx, Provenance>],
1010 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
1012 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
1014 if let Ok(ops) = args.try_into() {
1017 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
1020 pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1021 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1022 "{} not available when isolation is enabled",
1027 /// Retrieve the list of local crates that should have been passed by cargo-miri in
1028 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
1029 pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
1030 // Convert the local crate names from the passed-in config into CrateNums so that they can
1031 // be looked up quickly during execution
1032 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
1033 .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
1034 .unwrap_or_default();
1035 let mut local_crates = Vec::new();
1036 for &crate_num in tcx.crates(()) {
1037 let name = tcx.crate_name(crate_num);
1038 let name = name.as_str();
1039 if local_crate_names.iter().any(|local_name| local_name == name) {
1040 local_crates.push(crate_num);
1046 /// Helper function used inside the shims of foreign functions to check that
1047 /// `target_os` is a supported UNIX OS.
1048 pub fn target_os_is_unix(target_os: &str) -> bool {
1049 matches!(target_os, "linux" | "macos" | "freebsd" | "android")