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 "`{name}` is only available on the `{target_os}` target OS",
561 /// Helper function used inside the shims of foreign functions to assert that the target OS
562 /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
563 /// if this is not the case.
564 fn assert_target_os_is_unix(&self, name: &str) {
566 target_os_is_unix(self.eval_context_ref().tcx.sess.target.os.as_ref()),
567 "`{name}` is only available for supported UNIX family targets",
571 /// Get last error variable as a place, lazily allocating thread-local storage for it if
573 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
574 let this = self.eval_context_mut();
575 if let Some(errno_place) = this.active_thread_ref().last_error {
578 // Allocate new place, set initial value to 0.
579 let errno_layout = this.machine.layouts.u32;
580 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
581 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
582 this.active_thread_mut().last_error = Some(errno_place);
587 /// Sets the last error variable.
588 fn set_last_error(&mut self, scalar: Scalar<Provenance>) -> InterpResult<'tcx> {
589 let this = self.eval_context_mut();
590 let errno_place = this.last_error_place()?;
591 this.write_scalar(scalar, &errno_place.into())
594 /// Gets the last error variable.
595 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Provenance>> {
596 let this = self.eval_context_mut();
597 let errno_place = this.last_error_place()?;
598 this.read_scalar(&errno_place.into())
601 /// This function tries to produce the most similar OS error from the `std::io::ErrorKind`
602 /// as a platform-specific errnum.
603 fn io_error_to_errnum(
605 err_kind: std::io::ErrorKind,
606 ) -> InterpResult<'tcx, Scalar<Provenance>> {
607 let this = self.eval_context_ref();
608 let target = &this.tcx.sess.target;
609 if target.families.iter().any(|f| f == "unix") {
610 for &(name, kind) in UNIX_IO_ERROR_TABLE {
611 if err_kind == kind {
612 return this.eval_libc(name);
615 throw_unsup_format!("io error {:?} cannot be translated into a raw os error", err_kind)
616 } else if target.families.iter().any(|f| f == "windows") {
617 // FIXME: we have to finish implementing the Windows equivalent of this.
618 use std::io::ErrorKind::*;
622 NotFound => "ERROR_FILE_NOT_FOUND",
623 PermissionDenied => "ERROR_ACCESS_DENIED",
626 "io error {:?} cannot be translated into a raw os error",
633 "converting io::Error into errnum is unsupported for OS {}",
639 /// The inverse of `io_error_to_errnum`.
640 #[allow(clippy::needless_return)]
641 fn try_errnum_to_io_error(
643 errnum: Scalar<Provenance>,
644 ) -> InterpResult<'tcx, Option<std::io::ErrorKind>> {
645 let this = self.eval_context_ref();
646 let target = &this.tcx.sess.target;
647 if target.families.iter().any(|f| f == "unix") {
648 let errnum = errnum.to_i32()?;
649 for &(name, kind) in UNIX_IO_ERROR_TABLE {
650 if errnum == this.eval_libc_i32(name)? {
651 return Ok(Some(kind));
654 // Our table is as complete as the mapping in std, so we are okay with saying "that's a
655 // strange one" here.
659 "converting errnum into io::Error is unsupported for OS {}",
665 /// Sets the last OS error using a `std::io::ErrorKind`.
666 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
667 self.set_last_error(self.io_error_to_errnum(err_kind)?)
670 /// Helper function that consumes an `std::io::Result<T>` and returns an
671 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
672 /// `Ok(-1)` and sets the last OS error accordingly.
674 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
675 /// functions return different integer types (like `read`, that returns an `i64`).
676 fn try_unwrap_io_result<T: From<i32>>(
678 result: std::io::Result<T>,
679 ) -> InterpResult<'tcx, T> {
683 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
689 /// Calculates the MPlaceTy given the offset and layout of an access on an operand
690 fn deref_operand_and_offset(
692 op: &OpTy<'tcx, Provenance>,
694 layout: TyAndLayout<'tcx>,
695 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
696 let this = self.eval_context_ref();
697 let op_place = this.deref_operand(op)?; // FIXME: we still deref with the original type!
698 let offset = Size::from_bytes(offset);
700 // Ensure that the access is within bounds.
701 assert!(op_place.layout.size >= offset + layout.size);
702 let value_place = op_place.offset(offset, layout, this)?;
706 fn read_scalar_at_offset(
708 op: &OpTy<'tcx, Provenance>,
710 layout: TyAndLayout<'tcx>,
711 ) -> InterpResult<'tcx, Scalar<Provenance>> {
712 let this = self.eval_context_ref();
713 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
714 this.read_scalar(&value_place.into())
717 fn write_scalar_at_offset(
719 op: &OpTy<'tcx, Provenance>,
721 value: impl Into<Scalar<Provenance>>,
722 layout: TyAndLayout<'tcx>,
723 ) -> InterpResult<'tcx, ()> {
724 let this = self.eval_context_mut();
725 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
726 this.write_scalar(value, &value_place.into())
729 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
730 /// if the value in the `timespec` struct is invalid. Some libc functions will return
731 /// `EINVAL` in this case.
734 tp: &MPlaceTy<'tcx, Provenance>,
735 ) -> InterpResult<'tcx, Option<Duration>> {
736 let this = self.eval_context_mut();
737 let seconds_place = this.mplace_field(tp, 0)?;
738 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
739 let seconds = seconds_scalar.to_machine_isize(this)?;
740 let nanoseconds_place = this.mplace_field(tp, 1)?;
741 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
742 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
745 // tv_sec must be non-negative.
746 let seconds: u64 = seconds.try_into().ok()?;
747 // tv_nsec must be non-negative.
748 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
749 if nanoseconds >= 1_000_000_000 {
750 // tv_nsec must not be greater than 999,999,999.
753 Duration::new(seconds, nanoseconds)
757 /// Read a sequence of bytes until the first null terminator.
758 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, &'a [u8]>
763 let this = self.eval_context_ref();
764 let size1 = Size::from_bytes(1);
766 // Step 1: determine the length.
767 let mut len = Size::ZERO;
769 // FIXME: We are re-getting the allocation each time around the loop.
770 // Would be nice if we could somehow "extend" an existing AllocRange.
771 let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
772 let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
780 // Step 2: get the bytes.
781 this.read_bytes_ptr_strip_provenance(ptr, len)
784 /// Helper function to write a sequence of bytes with an added null-terminator, which is what
785 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
786 /// to write if `size` is not large enough to fit the contents of `c_str` plus a null
787 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
788 /// string length returned does include the null terminator.
792 ptr: Pointer<Option<Provenance>>,
794 ) -> InterpResult<'tcx, (bool, u64)> {
795 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
796 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
797 let string_length = u64::try_from(c_str.len()).unwrap();
798 let string_length = string_length.checked_add(1).unwrap();
799 if size < string_length {
800 return Ok((false, string_length));
802 self.eval_context_mut()
803 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
804 Ok((true, string_length))
807 /// Read a sequence of u16 until the first null terminator.
808 fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {
809 let this = self.eval_context_ref();
810 let size2 = Size::from_bytes(2);
811 let align2 = Align::from_bytes(2).unwrap();
813 let mut wchars = Vec::new();
815 // FIXME: We are re-getting the allocation each time around the loop.
816 // Would be nice if we could somehow "extend" an existing AllocRange.
817 let alloc = this.get_ptr_alloc(ptr, size2, align2)?.unwrap(); // not a ZST, so we will get a result
818 let wchar = alloc.read_integer(alloc_range(Size::ZERO, size2))?.to_u16()?;
823 ptr = ptr.offset(size2, this)?;
830 /// Helper function to write a sequence of u16 with an added 0x0000-terminator, which is what
831 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
832 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
833 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
834 /// string length returned does include the null terminator. Length is measured in units of
839 ptr: Pointer<Option<Provenance>>,
841 ) -> InterpResult<'tcx, (bool, u64)> {
842 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
843 // 0x0000 terminator to memory would cause an out-of-bounds access.
844 let string_length = u64::try_from(wide_str.len()).unwrap();
845 let string_length = string_length.checked_add(1).unwrap();
846 if size < string_length {
847 return Ok((false, string_length));
850 // Store the UTF-16 string.
851 let size2 = Size::from_bytes(2);
852 let this = self.eval_context_mut();
854 .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
855 .unwrap(); // not a ZST, so we will get a result
856 for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
857 let offset = u64::try_from(offset).unwrap();
858 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
860 Ok((true, string_length))
863 /// Check that the ABI is what we expect.
864 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
865 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
867 "calling a function with ABI {} using caller ABI {}",
875 fn frame_in_std(&self) -> bool {
876 let this = self.eval_context_ref();
877 let Some(start_fn) = this.tcx.lang_items().start_fn() else {
881 let frame = this.frame();
882 // Make an attempt to get at the instance of the function this is inlined from.
883 let instance: Option<_> = try {
884 let scope = frame.current_source_info()?.scope;
885 let inlined_parent = frame.body.source_scopes[scope].inlined_parent_scope?;
886 let source = &frame.body.source_scopes[inlined_parent];
887 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
889 // Fall back to the instance of the function itself.
890 let instance = instance.unwrap_or(frame.instance);
891 // Now check if this is in the same crate as start_fn.
892 // As a special exception we also allow unit tests from
893 // <https://github.com/rust-lang/miri-test-libstd/tree/master/std_miri_test> to call these
895 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
896 frame_crate == this.tcx.def_path(start_fn).krate
897 || this.tcx.crate_name(frame_crate).as_str() == "std_miri_test"
900 /// Handler that should be called when unsupported functionality is encountered.
901 /// This function will either panic within the context of the emulated application
902 /// or return an error in the Miri process context
904 /// Return value of `Ok(bool)` indicates whether execution should continue.
905 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
906 let this = self.eval_context_mut();
907 if this.machine.panic_on_unsupported {
908 // message is slightly different here to make automated analysis easier
909 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
910 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
913 throw_unsup_format!("{}", error_msg.as_ref());
917 fn check_abi_and_shim_symbol_clash(
922 ) -> InterpResult<'tcx, ()> {
923 self.check_abi(abi, exp_abi)?;
924 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
925 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
927 span: body.span.data(),
933 fn check_shim<'a, const N: usize>(
938 args: &'a [OpTy<'tcx, Provenance>],
939 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
941 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
943 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
944 check_arg_count(args)
947 /// Mark a machine allocation that was just created as immutable.
948 fn mark_immutable(&mut self, mplace: &MemPlace<Provenance>) {
949 let this = self.eval_context_mut();
950 // This got just allocated, so there definitely is a pointer here.
951 let provenance = mplace.ptr.into_pointer_or_addr().unwrap().provenance;
952 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
955 fn item_link_name(&self, def_id: DefId) -> Symbol {
956 let tcx = self.eval_context_ref().tcx;
957 match tcx.get_attrs(def_id, sym::link_name).filter_map(|a| a.value_str()).next() {
959 None => tcx.item_name(def_id),
964 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
965 /// Get the current span in the topmost function which is workspace-local and not
966 /// `#[track_caller]`.
967 /// This function is backed by a cache, and can be assumed to be very fast.
968 /// It will work even when the stack is empty.
969 pub fn current_span(&self) -> Span {
970 self.top_user_relevant_frame()
971 .map(|frame_idx| self.stack()[frame_idx].current_span())
972 .unwrap_or(rustc_span::DUMMY_SP)
975 /// Returns the span of the *caller* of the current operation, again
976 /// walking down the stack to find the closest frame in a local crate, if the caller of the
977 /// current operation is not in a local crate.
978 /// This is useful when we are processing something which occurs on function-entry and we want
979 /// to point at the call to the function, not the function definition generally.
980 pub fn caller_span(&self) -> Span {
981 // We need to go down at least to the caller (len - 2), or however
982 // far we have to go to find a frame in a local crate which is also not #[track_caller].
983 let frame_idx = self.top_user_relevant_frame().unwrap();
984 let frame_idx = cmp::min(frame_idx, self.stack().len().checked_sub(2).unwrap());
985 self.stack()[frame_idx].current_span()
988 fn stack(&self) -> &[Frame<'mir, 'tcx, Provenance, machine::FrameExtra<'tcx>>] {
989 self.threads.active_thread_stack()
992 fn top_user_relevant_frame(&self) -> Option<usize> {
993 self.threads.active_thread_ref().top_user_relevant_frame()
996 /// This is the source of truth for the `is_user_relevant` flag in our `FrameExtra`.
997 pub fn is_user_relevant(&self, frame: &Frame<'mir, 'tcx, Provenance>) -> bool {
998 let def_id = frame.instance.def_id();
999 (def_id.is_local() || self.local_crates.contains(&def_id.krate))
1000 && !frame.instance.def.requires_caller_location(self.tcx)
1004 /// Check that the number of args is what we expect.
1005 pub fn check_arg_count<'a, 'tcx, const N: usize>(
1006 args: &'a [OpTy<'tcx, Provenance>],
1007 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
1009 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
1011 if let Ok(ops) = args.try_into() {
1014 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
1017 pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1018 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1019 "{name} not available when isolation is enabled",
1023 /// Retrieve the list of local crates that should have been passed by cargo-miri in
1024 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
1025 pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
1026 // Convert the local crate names from the passed-in config into CrateNums so that they can
1027 // be looked up quickly during execution
1028 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
1029 .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
1030 .unwrap_or_default();
1031 let mut local_crates = Vec::new();
1032 for &crate_num in tcx.crates(()) {
1033 let name = tcx.crate_name(crate_num);
1034 let name = name.as_str();
1035 if local_crate_names.iter().any(|local_name| local_name == name) {
1036 local_crates.push(crate_num);
1042 /// Helper function used inside the shims of foreign functions to check that
1043 /// `target_os` is a supported UNIX OS.
1044 pub fn target_os_is_unix(target_os: &str) -> bool {
1045 matches!(target_os, "linux" | "macos" | "freebsd" | "android")