6 use std::num::NonZeroUsize;
7 use std::time::Duration;
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.
77 fn try_resolve_did<'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
78 tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == path[0]).and_then(
80 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
81 let mut items = tcx.module_children(krate);
82 let mut path_it = path.iter().skip(1).peekable();
84 while let Some(segment) = path_it.next() {
85 for item in mem::take(&mut items).iter() {
86 if item.ident.name.as_str() == *segment {
87 if path_it.peek().is_none() {
88 return Some(item.res.def_id());
91 items = tcx.module_children(item.res.def_id());
101 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
102 /// Gets an instance for a path; fails gracefully if the path does not exist.
103 fn try_resolve_path(&self, path: &[&str]) -> Option<ty::Instance<'tcx>> {
104 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)?;
105 Some(ty::Instance::mono(self.eval_context_ref().tcx.tcx, did))
108 /// Gets an instance for a path.
109 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
110 self.try_resolve_path(path)
111 .unwrap_or_else(|| panic!("failed to find required Rust item: {path:?}"))
114 /// Evaluates the scalar at the specified path. Returns Some(val)
115 /// if the path could be resolved, and None otherwise
116 fn eval_path_scalar(&self, path: &[&str]) -> InterpResult<'tcx, Scalar<Provenance>> {
117 let this = self.eval_context_ref();
118 let instance = this.resolve_path(path);
119 let cid = GlobalId { instance, promoted: None };
120 // We don't give a span -- this isn't actually used directly by the program anyway.
121 let const_val = this.eval_global(cid, None)?;
122 this.read_scalar(&const_val.into())
125 /// Helper function to get a `libc` constant as a `Scalar`.
126 fn eval_libc(&self, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
127 self.eval_path_scalar(&["libc", name])
130 /// Helper function to get a `libc` constant as an `i32`.
131 fn eval_libc_i32(&self, name: &str) -> InterpResult<'tcx, i32> {
132 // TODO: Cache the result.
133 self.eval_libc(name)?.to_i32()
136 /// Helper function to get a `windows` constant as a `Scalar`.
137 fn eval_windows(&self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
138 self.eval_context_ref().eval_path_scalar(&["std", "sys", "windows", module, name])
141 /// Helper function to get a `windows` constant as a `u64`.
142 fn eval_windows_u64(&self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
143 // TODO: Cache the result.
144 self.eval_windows(module, name)?.to_u64()
147 /// Helper function to get the `TyAndLayout` of a `libc` type
148 fn libc_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
149 let this = self.eval_context_ref();
150 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
154 /// Helper function to get the `TyAndLayout` of a `windows` type
155 fn windows_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
156 let this = self.eval_context_ref();
158 .resolve_path(&["std", "sys", "windows", "c", name])
159 .ty(*this.tcx, ty::ParamEnv::reveal_all());
163 /// Project to the given *named* field of the mplace (which must be a struct or union type).
164 fn mplace_field_named(
166 mplace: &MPlaceTy<'tcx, Provenance>,
168 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
169 let this = self.eval_context_ref();
170 let adt = mplace.layout.ty.ty_adt_def().unwrap();
171 for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
172 if field.name.as_str() == name {
173 return this.mplace_field(mplace, idx);
176 bug!("No field named {} in type {}", name, mplace.layout.ty);
179 /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
180 /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
181 /// this method is fine for almost all integer types.
185 dest: &PlaceTy<'tcx, Provenance>,
186 ) -> InterpResult<'tcx> {
187 assert!(dest.layout.abi.is_scalar(), "write_int on non-scalar type {}", dest.layout.ty);
188 let val = if dest.layout.abi.is_signed() {
189 Scalar::from_int(i, dest.layout.size)
191 Scalar::from_uint(u64::try_from(i.into()).unwrap(), dest.layout.size)
193 self.eval_context_mut().write_scalar(val, dest)
196 /// Write the first N fields of the given place.
200 dest: &MPlaceTy<'tcx, Provenance>,
201 ) -> InterpResult<'tcx> {
202 let this = self.eval_context_mut();
203 for (idx, &val) in values.iter().enumerate() {
204 let field = this.mplace_field(dest, idx)?;
205 this.write_int(val, &field.into())?;
210 /// Write the given fields of the given place.
211 fn write_int_fields_named(
213 values: &[(&str, i128)],
214 dest: &MPlaceTy<'tcx, Provenance>,
215 ) -> InterpResult<'tcx> {
216 let this = self.eval_context_mut();
217 for &(name, val) in values.iter() {
218 let field = this.mplace_field_named(dest, name)?;
219 this.write_int(val, &field.into())?;
224 /// Write a 0 of the appropriate size to `dest`.
225 fn write_null(&mut self, dest: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
226 self.write_int(0, dest)
229 /// Test if this pointer equals 0.
230 fn ptr_is_null(&self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, bool> {
231 Ok(ptr.addr().bytes() == 0)
234 /// Get the `Place` for a local
235 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Provenance>> {
236 let this = self.eval_context_mut();
237 let place = mir::Place { local, projection: List::empty() };
238 this.eval_place(place)
241 /// Generate some random bytes, and write them to `dest`.
242 fn gen_random(&mut self, ptr: Pointer<Option<Provenance>>, len: u64) -> InterpResult<'tcx> {
243 // Some programs pass in a null pointer and a length of 0
244 // to their platform's random-generation function (e.g. getrandom())
245 // on Linux. For compatibility with these programs, we don't perform
246 // any additional checks - it's okay if the pointer is invalid,
247 // since we wouldn't actually be writing to it.
251 let this = self.eval_context_mut();
253 let mut data = vec![0; usize::try_from(len).unwrap()];
255 if this.machine.communicate() {
256 // Fill the buffer using the host's rng.
257 getrandom::getrandom(&mut data)
258 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
260 let rng = this.machine.rng.get_mut();
261 rng.fill_bytes(&mut data);
264 this.write_bytes_ptr(ptr, data.iter().copied())
267 /// Call a function: Push the stack frame and pass the arguments.
268 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
270 /// If you do not provie a return place, a dangling zero-sized place will be created
271 /// for your convenience.
274 f: ty::Instance<'tcx>,
276 args: &[Immediate<Provenance>],
277 dest: Option<&PlaceTy<'tcx, Provenance>>,
278 stack_pop: StackPopCleanup,
279 ) -> InterpResult<'tcx> {
280 let this = self.eval_context_mut();
281 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
282 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
283 if this.machine.enforce_abi && callee_abi != caller_abi {
285 "calling a function with ABI {} using caller ABI {}",
292 let mir = this.load_mir(f.def, None)?;
293 let dest = match dest {
294 Some(dest) => dest.clone(),
295 None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?).into(),
297 this.push_stack_frame(f, mir, &dest, stack_pop)?;
299 // Initialize arguments.
300 let mut callee_args = this.frame().body.args_iter();
302 let callee_arg = this.local_place(
305 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
307 this.write_immediate(*arg, &callee_arg)?;
309 if callee_args.next().is_some() {
310 throw_ub_format!("callee has more arguments than expected");
316 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
317 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
318 /// The range is relative to `place`.
319 fn visit_freeze_sensitive(
321 place: &MPlaceTy<'tcx, Provenance>,
323 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
324 ) -> InterpResult<'tcx> {
325 let this = self.eval_context_ref();
326 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
329 this.size_and_align_of_mplace(place)?
330 .map(|(size, _)| size)
331 .unwrap_or_else(|| place.layout.size)
333 // Store how far we proceeded into the place so far. Everything to the left of
334 // this offset has already been handled, in the sense that the frozen parts
335 // have had `action` called on them.
336 let start_addr = place.ptr.addr();
337 let mut cur_addr = start_addr;
338 // Called when we detected an `UnsafeCell` at the given offset and size.
339 // Calls `action` and advances `cur_ptr`.
340 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer<Option<Provenance>>,
341 unsafe_cell_size: Size| {
342 // We assume that we are given the fields in increasing offset order,
343 // and nothing else changes.
344 let unsafe_cell_addr = unsafe_cell_ptr.addr();
345 assert!(unsafe_cell_addr >= cur_addr);
346 let frozen_size = unsafe_cell_addr - cur_addr;
347 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
348 if frozen_size != Size::ZERO {
349 action(alloc_range(cur_addr - start_addr, frozen_size), /*frozen*/ true)?;
351 cur_addr += frozen_size;
352 // This `UnsafeCell` is NOT frozen.
353 if unsafe_cell_size != Size::ZERO {
355 alloc_range(cur_addr - start_addr, unsafe_cell_size),
359 cur_addr += unsafe_cell_size;
365 let mut visitor = UnsafeCellVisitor {
367 unsafe_cell_action: |place| {
368 trace!("unsafe_cell_action on {:?}", place.ptr);
369 // We need a size to go on.
370 let unsafe_cell_size = this
371 .size_and_align_of_mplace(place)?
372 .map(|(size, _)| size)
373 // for extern types, just cover what we can
374 .unwrap_or_else(|| place.layout.size);
375 // Now handle this `UnsafeCell`, unless it is empty.
376 if unsafe_cell_size != Size::ZERO {
377 unsafe_cell_action(&place.ptr, unsafe_cell_size)
383 visitor.visit_value(place)?;
385 // The part between the end_ptr and the end of the place is also frozen.
386 // So pretend there is a 0-sized `UnsafeCell` at the end.
387 unsafe_cell_action(&place.ptr.offset(size, this)?, Size::ZERO)?;
391 /// Visiting the memory covered by a `MemPlace`, being aware of
392 /// whether we are inside an `UnsafeCell` or not.
393 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
395 F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
397 ecx: &'ecx MiriInterpCx<'mir, 'tcx>,
398 unsafe_cell_action: F,
401 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, MiriMachine<'mir, 'tcx>>
402 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
404 F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
406 type V = MPlaceTy<'tcx, Provenance>;
409 fn ecx(&self) -> &MiriInterpCx<'mir, 'tcx> {
413 // Hook to detect `UnsafeCell`.
414 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
415 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
416 let is_unsafe_cell = match v.layout.ty.kind() {
418 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
422 // We do not have to recurse further, this is an `UnsafeCell`.
423 (self.unsafe_cell_action)(v)
424 } else if self.ecx.type_is_freeze(v.layout.ty) {
425 // This is `Freeze`, there cannot be an `UnsafeCell`
427 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
428 // A (non-frozen) union. We fall back to whatever the type says.
429 (self.unsafe_cell_action)(v)
431 // We want to not actually read from memory for this visit. So, before
432 // walking this value, we have to make sure it is not a
433 // `Variants::Multiple`.
434 match v.layout.variants {
435 Variants::Multiple { .. } => {
436 // A multi-variant enum, or generator, or so.
437 // Treat this like a union: without reading from memory,
438 // we cannot determine the variant we are in. Reading from
439 // memory would be subject to Stacked Borrows rules, leading
440 // to all sorts of "funny" recursion.
441 // We only end up here if the type is *not* freeze, so we just call the
442 // `UnsafeCell` action.
443 (self.unsafe_cell_action)(v)
445 Variants::Single { .. } => {
446 // Proceed further, try to find where exactly that `UnsafeCell`
454 // Make sure we visit aggregrates in increasing offset order.
457 place: &MPlaceTy<'tcx, Provenance>,
458 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Provenance>>>,
459 ) -> InterpResult<'tcx> {
460 match place.layout.fields {
461 FieldsShape::Array { .. } => {
462 // For the array layout, we know the iterator will yield sorted elements so
463 // we can avoid the allocation.
464 self.walk_aggregate(place, fields)
466 FieldsShape::Arbitrary { .. } => {
467 // Gather the subplaces and sort them before visiting.
468 let mut places = fields
469 .collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Provenance>>>>()?;
470 // we just compare offsets, the abs. value never matters
471 places.sort_by_key(|place| place.ptr.addr());
472 self.walk_aggregate(place, places.into_iter().map(Ok))
474 FieldsShape::Union { .. } | FieldsShape::Primitive => {
476 bug!("unions/primitives are not aggregates we should ever visit")
483 _v: &MPlaceTy<'tcx, Provenance>,
484 _fields: NonZeroUsize,
485 ) -> InterpResult<'tcx> {
486 bug!("we should have already handled unions in `visit_value`")
491 /// Helper function used inside the shims of foreign functions to check that isolation is
492 /// disabled. It returns an error using the `name` of the foreign function if this is not the
494 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
495 if !self.eval_context_ref().machine.communicate() {
496 self.reject_in_isolation(name, RejectOpWith::Abort)?;
501 /// Helper function used inside the shims of foreign functions which reject the op
502 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
503 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
504 let this = self.eval_context_ref();
506 RejectOpWith::Abort => isolation_abort_error(op_name),
507 RejectOpWith::WarningWithoutBacktrace => {
510 .warn(format!("{op_name} was made to return an error due to isolation"));
513 RejectOpWith::Warning => {
514 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
517 RejectOpWith::NoWarning => Ok(()), // no warning
521 /// Helper function used inside the shims of foreign functions to assert that the target OS
522 /// is `target_os`. It panics showing a message with the `name` of the foreign function
523 /// if this is not the case.
524 fn assert_target_os(&self, target_os: &str, name: &str) {
526 self.eval_context_ref().tcx.sess.target.os,
528 "`{}` is only available on the `{}` target OS",
534 /// Helper function used inside the shims of foreign functions to assert that the target OS
535 /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
536 /// if this is not the case.
537 fn assert_target_os_is_unix(&self, name: &str) {
539 target_os_is_unix(self.eval_context_ref().tcx.sess.target.os.as_ref()),
540 "`{}` is only available for supported UNIX family targets",
545 /// Get last error variable as a place, lazily allocating thread-local storage for it if
547 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
548 let this = self.eval_context_mut();
549 if let Some(errno_place) = this.active_thread_ref().last_error {
552 // Allocate new place, set initial value to 0.
553 let errno_layout = this.machine.layouts.u32;
554 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
555 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
556 this.active_thread_mut().last_error = Some(errno_place);
561 /// Sets the last error variable.
562 fn set_last_error(&mut self, scalar: Scalar<Provenance>) -> InterpResult<'tcx> {
563 let this = self.eval_context_mut();
564 let errno_place = this.last_error_place()?;
565 this.write_scalar(scalar, &errno_place.into())
568 /// Gets the last error variable.
569 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Provenance>> {
570 let this = self.eval_context_mut();
571 let errno_place = this.last_error_place()?;
572 this.read_scalar(&errno_place.into())
575 /// This function tries to produce the most similar OS error from the `std::io::ErrorKind`
576 /// as a platform-specific errnum.
577 fn io_error_to_errnum(
579 err_kind: std::io::ErrorKind,
580 ) -> InterpResult<'tcx, Scalar<Provenance>> {
581 let this = self.eval_context_ref();
582 let target = &this.tcx.sess.target;
583 if target.families.iter().any(|f| f == "unix") {
584 for &(name, kind) in UNIX_IO_ERROR_TABLE {
585 if err_kind == kind {
586 return this.eval_libc(name);
589 throw_unsup_format!("io error {:?} cannot be translated into a raw os error", err_kind)
590 } else if target.families.iter().any(|f| f == "windows") {
591 // FIXME: we have to finish implementing the Windows equivalent of this.
592 use std::io::ErrorKind::*;
596 NotFound => "ERROR_FILE_NOT_FOUND",
597 PermissionDenied => "ERROR_ACCESS_DENIED",
600 "io error {:?} cannot be translated into a raw os error",
607 "converting io::Error into errnum is unsupported for OS {}",
613 /// The inverse of `io_error_to_errnum`.
614 #[allow(clippy::needless_return)]
615 fn try_errnum_to_io_error(
617 errnum: Scalar<Provenance>,
618 ) -> InterpResult<'tcx, Option<std::io::ErrorKind>> {
619 let this = self.eval_context_ref();
620 let target = &this.tcx.sess.target;
621 if target.families.iter().any(|f| f == "unix") {
622 let errnum = errnum.to_i32()?;
623 for &(name, kind) in UNIX_IO_ERROR_TABLE {
624 if errnum == this.eval_libc_i32(name)? {
625 return Ok(Some(kind));
628 // Our table is as complete as the mapping in std, so we are okay with saying "that's a
629 // strange one" here.
633 "converting errnum into io::Error is unsupported for OS {}",
639 /// Sets the last OS error using a `std::io::ErrorKind`.
640 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
641 self.set_last_error(self.io_error_to_errnum(err_kind)?)
644 /// Helper function that consumes an `std::io::Result<T>` and returns an
645 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
646 /// `Ok(-1)` and sets the last OS error accordingly.
648 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
649 /// functions return different integer types (like `read`, that returns an `i64`).
650 fn try_unwrap_io_result<T: From<i32>>(
652 result: std::io::Result<T>,
653 ) -> InterpResult<'tcx, T> {
657 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
663 /// Calculates the MPlaceTy given the offset and layout of an access on an operand
664 fn deref_operand_and_offset(
666 op: &OpTy<'tcx, Provenance>,
668 layout: TyAndLayout<'tcx>,
669 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
670 let this = self.eval_context_ref();
671 let op_place = this.deref_operand(op)?; // FIXME: we still deref with the original type!
672 let offset = Size::from_bytes(offset);
674 // Ensure that the access is within bounds.
675 assert!(op_place.layout.size >= offset + layout.size);
676 let value_place = op_place.offset(offset, layout, this)?;
680 fn read_scalar_at_offset(
682 op: &OpTy<'tcx, Provenance>,
684 layout: TyAndLayout<'tcx>,
685 ) -> InterpResult<'tcx, Scalar<Provenance>> {
686 let this = self.eval_context_ref();
687 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
688 this.read_scalar(&value_place.into())
691 fn write_scalar_at_offset(
693 op: &OpTy<'tcx, Provenance>,
695 value: impl Into<Scalar<Provenance>>,
696 layout: TyAndLayout<'tcx>,
697 ) -> InterpResult<'tcx, ()> {
698 let this = self.eval_context_mut();
699 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
700 this.write_scalar(value, &value_place.into())
703 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
704 /// if the value in the `timespec` struct is invalid. Some libc functions will return
705 /// `EINVAL` in this case.
708 tp: &MPlaceTy<'tcx, Provenance>,
709 ) -> InterpResult<'tcx, Option<Duration>> {
710 let this = self.eval_context_mut();
711 let seconds_place = this.mplace_field(tp, 0)?;
712 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
713 let seconds = seconds_scalar.to_machine_isize(this)?;
714 let nanoseconds_place = this.mplace_field(tp, 1)?;
715 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
716 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
719 // tv_sec must be non-negative.
720 let seconds: u64 = seconds.try_into().ok()?;
721 // tv_nsec must be non-negative.
722 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
723 if nanoseconds >= 1_000_000_000 {
724 // tv_nsec must not be greater than 999,999,999.
727 Duration::new(seconds, nanoseconds)
731 /// Read a sequence of bytes until the first null terminator.
732 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, &'a [u8]>
737 let this = self.eval_context_ref();
738 let size1 = Size::from_bytes(1);
740 // Step 1: determine the length.
741 let mut len = Size::ZERO;
743 // FIXME: We are re-getting the allocation each time around the loop.
744 // Would be nice if we could somehow "extend" an existing AllocRange.
745 let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
746 let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
754 // Step 2: get the bytes.
755 this.read_bytes_ptr_strip_provenance(ptr, len)
758 /// Helper function to write a sequence of bytes with an added null-terminator, which is what
759 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
760 /// to write if `size` is not large enough to fit the contents of `c_str` plus a null
761 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
762 /// string length returned does include the null terminator.
766 ptr: Pointer<Option<Provenance>>,
768 ) -> InterpResult<'tcx, (bool, u64)> {
769 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
770 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
771 let string_length = u64::try_from(c_str.len()).unwrap();
772 let string_length = string_length.checked_add(1).unwrap();
773 if size < string_length {
774 return Ok((false, string_length));
776 self.eval_context_mut()
777 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
778 Ok((true, string_length))
781 /// Read a sequence of u16 until the first null terminator.
782 fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {
783 let this = self.eval_context_ref();
784 let size2 = Size::from_bytes(2);
785 let align2 = Align::from_bytes(2).unwrap();
787 let mut wchars = Vec::new();
789 // FIXME: We are re-getting the allocation each time around the loop.
790 // Would be nice if we could somehow "extend" an existing AllocRange.
791 let alloc = this.get_ptr_alloc(ptr, size2, align2)?.unwrap(); // not a ZST, so we will get a result
792 let wchar = alloc.read_integer(alloc_range(Size::ZERO, size2))?.to_u16()?;
797 ptr = ptr.offset(size2, this)?;
804 /// Helper function to write a sequence of u16 with an added 0x0000-terminator, which is what
805 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
806 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
807 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
808 /// string length returned does include the null terminator. Length is measured in units of
813 ptr: Pointer<Option<Provenance>>,
815 ) -> InterpResult<'tcx, (bool, u64)> {
816 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
817 // 0x0000 terminator to memory would cause an out-of-bounds access.
818 let string_length = u64::try_from(wide_str.len()).unwrap();
819 let string_length = string_length.checked_add(1).unwrap();
820 if size < string_length {
821 return Ok((false, string_length));
824 // Store the UTF-16 string.
825 let size2 = Size::from_bytes(2);
826 let this = self.eval_context_mut();
828 .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
829 .unwrap(); // not a ZST, so we will get a result
830 for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
831 let offset = u64::try_from(offset).unwrap();
832 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
834 Ok((true, string_length))
837 /// Check that the ABI is what we expect.
838 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
839 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
841 "calling a function with ABI {} using caller ABI {}",
849 fn frame_in_std(&self) -> bool {
850 let this = self.eval_context_ref();
851 let Some(start_fn) = this.tcx.lang_items().start_fn() else {
855 let frame = this.frame();
856 // Make an attempt to get at the instance of the function this is inlined from.
857 let instance: Option<_> = try {
858 let scope = frame.current_source_info()?.scope;
859 let inlined_parent = frame.body.source_scopes[scope].inlined_parent_scope?;
860 let source = &frame.body.source_scopes[inlined_parent];
861 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
863 // Fall back to the instance of the function itself.
864 let instance = instance.unwrap_or(frame.instance);
865 // Now check if this is in the same crate as start_fn.
866 // As a special exception we also allow unit tests from
867 // <https://github.com/rust-lang/miri-test-libstd/tree/master/std_miri_test> to call these
869 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
870 frame_crate == this.tcx.def_path(start_fn).krate
871 || this.tcx.crate_name(frame_crate).as_str() == "std_miri_test"
874 /// Handler that should be called when unsupported functionality is encountered.
875 /// This function will either panic within the context of the emulated application
876 /// or return an error in the Miri process context
878 /// Return value of `Ok(bool)` indicates whether execution should continue.
879 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
880 let this = self.eval_context_mut();
881 if this.machine.panic_on_unsupported {
882 // message is slightly different here to make automated analysis easier
883 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
884 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
887 throw_unsup_format!("{}", error_msg.as_ref());
891 fn check_abi_and_shim_symbol_clash(
896 ) -> InterpResult<'tcx, ()> {
897 self.check_abi(abi, exp_abi)?;
898 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
899 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
901 span: body.span.data(),
907 fn check_shim<'a, const N: usize>(
912 args: &'a [OpTy<'tcx, Provenance>],
913 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
915 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
917 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
918 check_arg_count(args)
921 /// Mark a machine allocation that was just created as immutable.
922 fn mark_immutable(&mut self, mplace: &MemPlace<Provenance>) {
923 let this = self.eval_context_mut();
924 // This got just allocated, so there definitely is a pointer here.
925 let provenance = mplace.ptr.into_pointer_or_addr().unwrap().provenance;
926 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
929 fn item_link_name(&self, def_id: DefId) -> Symbol {
930 let tcx = self.eval_context_ref().tcx;
931 match tcx.get_attrs(def_id, sym::link_name).filter_map(|a| a.value_str()).next() {
933 None => tcx.item_name(def_id),
938 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
939 pub fn current_span(&self) -> CurrentSpan<'_, 'mir, 'tcx> {
940 CurrentSpan { current_frame_idx: None, machine: self }
944 /// A `CurrentSpan` should be created infrequently (ideally once) per interpreter step. It does
945 /// nothing on creation, but when `CurrentSpan::get` is called, searches the current stack for the
946 /// topmost frame which corresponds to a local crate, and returns the current span in that frame.
947 /// The result of that search is cached so that later calls are approximately free.
949 pub struct CurrentSpan<'a, 'mir, 'tcx> {
950 current_frame_idx: Option<usize>,
951 machine: &'a MiriMachine<'mir, 'tcx>,
954 impl<'a, 'mir: 'a, 'tcx: 'a + 'mir> CurrentSpan<'a, 'mir, 'tcx> {
955 pub fn machine(&self) -> &'a MiriMachine<'mir, 'tcx> {
959 /// Get the current span, skipping non-local frames.
960 /// This function is backed by a cache, and can be assumed to be very fast.
961 pub fn get(&mut self) -> Span {
962 let idx = self.current_frame_idx();
963 self.stack().get(idx).map(Frame::current_span).unwrap_or(rustc_span::DUMMY_SP)
966 /// Returns the span of the *caller* of the current operation, again
967 /// walking down the stack to find the closest frame in a local crate, if the caller of the
968 /// current operation is not in a local crate.
969 /// This is useful when we are processing something which occurs on function-entry and we want
970 /// to point at the call to the function, not the function definition generally.
971 pub fn get_caller(&mut self) -> Span {
972 // We need to go down at least to the caller (len - 2), or however
973 // far we have to go to find a frame in a local crate.
974 let local_frame_idx = self.current_frame_idx();
975 let stack = self.stack();
976 let idx = cmp::min(local_frame_idx, stack.len().saturating_sub(2));
977 stack.get(idx).map(Frame::current_span).unwrap_or(rustc_span::DUMMY_SP)
980 fn stack(&self) -> &[Frame<'mir, 'tcx, Provenance, machine::FrameData<'tcx>>] {
981 self.machine.threads.active_thread_stack()
984 fn current_frame_idx(&mut self) -> usize {
987 .get_or_insert_with(|| Self::compute_current_frame_index(self.machine))
990 // Find the position of the inner-most frame which is part of the crate being
991 // compiled/executed, part of the Cargo workspace, and is also not #[track_caller].
993 fn compute_current_frame_index(machine: &MiriMachine<'_, '_>) -> usize {
996 .active_thread_stack()
1000 .find_map(|(idx, frame)| {
1001 let def_id = frame.instance.def_id();
1002 if (def_id.is_local() || machine.local_crates.contains(&def_id.krate))
1003 && !frame.instance.def.requires_caller_location(machine.tcx)
1014 /// Check that the number of args is what we expect.
1015 pub fn check_arg_count<'a, 'tcx, const N: usize>(
1016 args: &'a [OpTy<'tcx, Provenance>],
1017 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
1019 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
1021 if let Ok(ops) = args.try_into() {
1024 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
1027 pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1028 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1029 "{} not available when isolation is enabled",
1034 /// Retrieve the list of local crates that should have been passed by cargo-miri in
1035 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
1036 pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
1037 // Convert the local crate names from the passed-in config into CrateNums so that they can
1038 // be looked up quickly during execution
1039 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
1040 .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
1041 .unwrap_or_default();
1042 let mut local_crates = Vec::new();
1043 for &crate_num in tcx.crates(()) {
1044 let name = tcx.crate_name(crate_num);
1045 let name = name.as_str();
1046 if local_crate_names.iter().any(|local_name| local_name == name) {
1047 local_crates.push(crate_num);
1053 /// Helper function used inside the shims of foreign functions to check that
1054 /// `target_os` is a supported UNIX OS.
1055 pub fn target_os_is_unix(target_os: &str) -> bool {
1056 matches!(target_os, "linux" | "macos" | "freebsd" | "android")