4 use std::num::NonZeroUsize;
5 use std::time::Duration;
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_middle::mir;
11 use rustc_middle::ty::{
13 layout::{LayoutOf, TyAndLayout},
16 use rustc_span::{def_id::CrateNum, sym, Span, Symbol};
17 use rustc_target::abi::{Align, FieldsShape, Size, Variants};
18 use rustc_target::spec::abi::Abi;
24 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
26 // This mapping should match `decode_error_kind` in
27 // <https://github.com/rust-lang/rust/blob/master/library/std/src/sys/unix/mod.rs>.
28 const UNIX_IO_ERROR_TABLE: &[(&str, std::io::ErrorKind)] = {
29 use std::io::ErrorKind::*;
31 ("E2BIG", ArgumentListTooLong),
32 ("EADDRINUSE", AddrInUse),
33 ("EADDRNOTAVAIL", AddrNotAvailable),
34 ("EBUSY", ResourceBusy),
35 ("ECONNABORTED", ConnectionAborted),
36 ("ECONNREFUSED", ConnectionRefused),
37 ("ECONNRESET", ConnectionReset),
38 ("EDEADLK", Deadlock),
39 ("EDQUOT", FilesystemQuotaExceeded),
40 ("EEXIST", AlreadyExists),
41 ("EFBIG", FileTooLarge),
42 ("EHOSTUNREACH", HostUnreachable),
43 ("EINTR", Interrupted),
44 ("EINVAL", InvalidInput),
45 ("EISDIR", IsADirectory),
46 ("ELOOP", FilesystemLoop),
48 ("ENOMEM", OutOfMemory),
49 ("ENOSPC", StorageFull),
50 ("ENOSYS", Unsupported),
51 ("EMLINK", TooManyLinks),
52 ("ENAMETOOLONG", InvalidFilename),
53 ("ENETDOWN", NetworkDown),
54 ("ENETUNREACH", NetworkUnreachable),
55 ("ENOTCONN", NotConnected),
56 ("ENOTDIR", NotADirectory),
57 ("ENOTEMPTY", DirectoryNotEmpty),
58 ("EPIPE", BrokenPipe),
59 ("EROFS", ReadOnlyFilesystem),
60 ("ESPIPE", NotSeekable),
61 ("ESTALE", StaleNetworkFileHandle),
62 ("ETIMEDOUT", TimedOut),
63 ("ETXTBSY", ExecutableFileBusy),
64 ("EXDEV", CrossesDevices),
65 // The following have two valid options. We have both for the forwards mapping; only the
66 // first one will be used for the backwards mapping.
67 ("EPERM", PermissionDenied),
68 ("EACCES", PermissionDenied),
69 ("EWOULDBLOCK", WouldBlock),
70 ("EAGAIN", WouldBlock),
74 /// Gets an instance for a path.
75 fn try_resolve_did<'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
76 tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == path[0]).and_then(
78 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
79 let mut items = tcx.module_children(krate);
80 let mut path_it = path.iter().skip(1).peekable();
82 while let Some(segment) = path_it.next() {
83 for item in mem::take(&mut items).iter() {
84 if item.ident.name.as_str() == *segment {
85 if path_it.peek().is_none() {
86 return Some(item.res.def_id());
89 items = tcx.module_children(item.res.def_id());
99 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
100 /// Gets an instance for a path; fails gracefully if the path does not exist.
101 fn try_resolve_path(&self, path: &[&str]) -> Option<ty::Instance<'tcx>> {
102 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)?;
103 Some(ty::Instance::mono(self.eval_context_ref().tcx.tcx, did))
106 /// Gets an instance for a path.
107 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
108 self.try_resolve_path(path)
109 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path))
112 /// Evaluates the scalar at the specified path. Returns Some(val)
113 /// if the path could be resolved, and None otherwise
114 fn eval_path_scalar(&self, path: &[&str]) -> InterpResult<'tcx, Scalar<Provenance>> {
115 let this = self.eval_context_ref();
116 let instance = this.resolve_path(path);
117 let cid = GlobalId { instance, promoted: None };
118 let const_val = this.eval_to_allocation(cid)?;
119 this.read_scalar(&const_val.into())
122 /// Helper function to get a `libc` constant as a `Scalar`.
123 fn eval_libc(&self, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
124 self.eval_path_scalar(&["libc", name])
127 /// Helper function to get a `libc` constant as an `i32`.
128 fn eval_libc_i32(&self, name: &str) -> InterpResult<'tcx, i32> {
129 // TODO: Cache the result.
130 self.eval_libc(name)?.to_i32()
133 /// Helper function to get a `windows` constant as a `Scalar`.
134 fn eval_windows(&self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
135 self.eval_context_ref().eval_path_scalar(&["std", "sys", "windows", module, name])
138 /// Helper function to get a `windows` constant as a `u64`.
139 fn eval_windows_u64(&self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
140 // TODO: Cache the result.
141 self.eval_windows(module, name)?.to_u64()
144 /// Helper function to get the `TyAndLayout` of a `libc` type
145 fn libc_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
146 let this = self.eval_context_ref();
147 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
151 /// Helper function to get the `TyAndLayout` of a `windows` type
152 fn windows_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
153 let this = self.eval_context_ref();
155 .resolve_path(&["std", "sys", "windows", "c", name])
156 .ty(*this.tcx, ty::ParamEnv::reveal_all());
160 /// Project to the given *named* field of the mplace (which must be a struct or union type).
161 fn mplace_field_named(
163 mplace: &MPlaceTy<'tcx, Provenance>,
165 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
166 let this = self.eval_context_ref();
167 let adt = mplace.layout.ty.ty_adt_def().unwrap();
168 for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
169 if field.name.as_str() == name {
170 return this.mplace_field(mplace, idx);
173 bug!("No field named {} in type {}", name, mplace.layout.ty);
176 /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
177 /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
178 /// this method is fine for almost all integer types.
182 dest: &PlaceTy<'tcx, Provenance>,
183 ) -> InterpResult<'tcx> {
184 assert!(dest.layout.abi.is_scalar(), "write_int on non-scalar type {}", dest.layout.ty);
185 let val = if dest.layout.abi.is_signed() {
186 Scalar::from_int(i, dest.layout.size)
188 Scalar::from_uint(u64::try_from(i.into()).unwrap(), dest.layout.size)
190 self.eval_context_mut().write_scalar(val, dest)
193 /// Write the first N fields of the given place.
197 dest: &MPlaceTy<'tcx, Provenance>,
198 ) -> InterpResult<'tcx> {
199 let this = self.eval_context_mut();
200 for (idx, &val) in values.iter().enumerate() {
201 let field = this.mplace_field(dest, idx)?;
202 this.write_int(val, &field.into())?;
207 /// Write the given fields of the given place.
208 fn write_int_fields_named(
210 values: &[(&str, i128)],
211 dest: &MPlaceTy<'tcx, Provenance>,
212 ) -> InterpResult<'tcx> {
213 let this = self.eval_context_mut();
214 for &(name, val) in values.iter() {
215 let field = this.mplace_field_named(dest, name)?;
216 this.write_int(val, &field.into())?;
221 /// Write a 0 of the appropriate size to `dest`.
222 fn write_null(&mut self, dest: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
223 self.write_int(0, dest)
226 /// Test if this pointer equals 0.
227 fn ptr_is_null(&self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, bool> {
228 Ok(ptr.addr().bytes() == 0)
231 /// Get the `Place` for a local
232 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Provenance>> {
233 let this = self.eval_context_mut();
234 let place = mir::Place { local, projection: List::empty() };
235 this.eval_place(place)
238 /// Generate some random bytes, and write them to `dest`.
239 fn gen_random(&mut self, ptr: Pointer<Option<Provenance>>, len: u64) -> InterpResult<'tcx> {
240 // Some programs pass in a null pointer and a length of 0
241 // to their platform's random-generation function (e.g. getrandom())
242 // on Linux. For compatibility with these programs, we don't perform
243 // any additional checks - it's okay if the pointer is invalid,
244 // since we wouldn't actually be writing to it.
248 let this = self.eval_context_mut();
250 let mut data = vec![0; usize::try_from(len).unwrap()];
252 if this.machine.communicate() {
253 // Fill the buffer using the host's rng.
254 getrandom::getrandom(&mut data)
255 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
257 let rng = this.machine.rng.get_mut();
258 rng.fill_bytes(&mut data);
261 this.write_bytes_ptr(ptr, data.iter().copied())
264 /// Call a function: Push the stack frame and pass the arguments.
265 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
267 /// If you do not provie a return place, a dangling zero-sized place will be created
268 /// for your convenience.
271 f: ty::Instance<'tcx>,
273 args: &[Immediate<Provenance>],
274 dest: Option<&PlaceTy<'tcx, Provenance>>,
275 stack_pop: StackPopCleanup,
276 ) -> InterpResult<'tcx> {
277 let this = self.eval_context_mut();
278 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
279 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
280 if this.machine.enforce_abi && callee_abi != caller_abi {
282 "calling a function with ABI {} using caller ABI {}",
289 let mir = this.load_mir(f.def, None)?;
290 let dest = match dest {
291 Some(dest) => dest.clone(),
292 None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?).into(),
294 this.push_stack_frame(f, mir, &dest, stack_pop)?;
296 // Initialize arguments.
297 let mut callee_args = this.frame().body.args_iter();
299 let callee_arg = this.local_place(
302 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
304 this.write_immediate(*arg, &callee_arg)?;
306 if callee_args.next().is_some() {
307 throw_ub_format!("callee has more arguments than expected");
313 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
314 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
315 /// The range is relative to `place`.
316 fn visit_freeze_sensitive(
318 place: &MPlaceTy<'tcx, Provenance>,
320 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
321 ) -> InterpResult<'tcx> {
322 let this = self.eval_context_ref();
323 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
326 this.size_and_align_of_mplace(place)?
327 .map(|(size, _)| size)
328 .unwrap_or_else(|| place.layout.size)
330 // Store how far we proceeded into the place so far. Everything to the left of
331 // this offset has already been handled, in the sense that the frozen parts
332 // have had `action` called on them.
333 let start_addr = place.ptr.addr();
334 let mut cur_addr = start_addr;
335 // Called when we detected an `UnsafeCell` at the given offset and size.
336 // Calls `action` and advances `cur_ptr`.
337 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer<Option<Provenance>>,
338 unsafe_cell_size: Size| {
339 // We assume that we are given the fields in increasing offset order,
340 // and nothing else changes.
341 let unsafe_cell_addr = unsafe_cell_ptr.addr();
342 assert!(unsafe_cell_addr >= cur_addr);
343 let frozen_size = unsafe_cell_addr - cur_addr;
344 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
345 if frozen_size != Size::ZERO {
346 action(alloc_range(cur_addr - start_addr, frozen_size), /*frozen*/ true)?;
348 cur_addr += frozen_size;
349 // This `UnsafeCell` is NOT frozen.
350 if unsafe_cell_size != Size::ZERO {
352 alloc_range(cur_addr - start_addr, unsafe_cell_size),
356 cur_addr += unsafe_cell_size;
362 let mut visitor = UnsafeCellVisitor {
364 unsafe_cell_action: |place| {
365 trace!("unsafe_cell_action on {:?}", place.ptr);
366 // We need a size to go on.
367 let unsafe_cell_size = this
368 .size_and_align_of_mplace(place)?
369 .map(|(size, _)| size)
370 // for extern types, just cover what we can
371 .unwrap_or_else(|| place.layout.size);
372 // Now handle this `UnsafeCell`, unless it is empty.
373 if unsafe_cell_size != Size::ZERO {
374 unsafe_cell_action(&place.ptr, unsafe_cell_size)
380 visitor.visit_value(place)?;
382 // The part between the end_ptr and the end of the place is also frozen.
383 // So pretend there is a 0-sized `UnsafeCell` at the end.
384 unsafe_cell_action(&place.ptr.offset(size, this)?, Size::ZERO)?;
388 /// Visiting the memory covered by a `MemPlace`, being aware of
389 /// whether we are inside an `UnsafeCell` or not.
390 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
392 F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
394 ecx: &'ecx MiriInterpCx<'mir, 'tcx>,
395 unsafe_cell_action: F,
398 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, MiriMachine<'mir, 'tcx>>
399 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
401 F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
403 type V = MPlaceTy<'tcx, Provenance>;
406 fn ecx(&self) -> &MiriInterpCx<'mir, 'tcx> {
410 // Hook to detect `UnsafeCell`.
411 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
412 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
413 let is_unsafe_cell = match v.layout.ty.kind() {
415 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
419 // We do not have to recurse further, this is an `UnsafeCell`.
420 (self.unsafe_cell_action)(v)
421 } else if self.ecx.type_is_freeze(v.layout.ty) {
422 // This is `Freeze`, there cannot be an `UnsafeCell`
424 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
425 // A (non-frozen) union. We fall back to whatever the type says.
426 (self.unsafe_cell_action)(v)
428 // We want to not actually read from memory for this visit. So, before
429 // walking this value, we have to make sure it is not a
430 // `Variants::Multiple`.
431 match v.layout.variants {
432 Variants::Multiple { .. } => {
433 // A multi-variant enum, or generator, or so.
434 // Treat this like a union: without reading from memory,
435 // we cannot determine the variant we are in. Reading from
436 // memory would be subject to Stacked Borrows rules, leading
437 // to all sorts of "funny" recursion.
438 // We only end up here if the type is *not* freeze, so we just call the
439 // `UnsafeCell` action.
440 (self.unsafe_cell_action)(v)
442 Variants::Single { .. } => {
443 // Proceed further, try to find where exactly that `UnsafeCell`
451 // Make sure we visit aggregrates in increasing offset order.
454 place: &MPlaceTy<'tcx, Provenance>,
455 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Provenance>>>,
456 ) -> InterpResult<'tcx> {
457 match place.layout.fields {
458 FieldsShape::Array { .. } => {
459 // For the array layout, we know the iterator will yield sorted elements so
460 // we can avoid the allocation.
461 self.walk_aggregate(place, fields)
463 FieldsShape::Arbitrary { .. } => {
464 // Gather the subplaces and sort them before visiting.
465 let mut places = fields
466 .collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Provenance>>>>()?;
467 // we just compare offsets, the abs. value never matters
468 places.sort_by_key(|place| place.ptr.addr());
469 self.walk_aggregate(place, places.into_iter().map(Ok))
471 FieldsShape::Union { .. } | FieldsShape::Primitive => {
473 bug!("unions/primitives are not aggregates we should ever visit")
480 _v: &MPlaceTy<'tcx, Provenance>,
481 _fields: NonZeroUsize,
482 ) -> InterpResult<'tcx> {
483 bug!("we should have already handled unions in `visit_value`")
488 /// Helper function used inside the shims of foreign functions to check that isolation is
489 /// disabled. It returns an error using the `name` of the foreign function if this is not the
491 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
492 if !self.eval_context_ref().machine.communicate() {
493 self.reject_in_isolation(name, RejectOpWith::Abort)?;
498 /// Helper function used inside the shims of foreign functions which reject the op
499 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
500 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
501 let this = self.eval_context_ref();
503 RejectOpWith::Abort => isolation_abort_error(op_name),
504 RejectOpWith::WarningWithoutBacktrace => {
507 .warn(&format!("{} was made to return an error due to isolation", op_name));
510 RejectOpWith::Warning => {
511 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
514 RejectOpWith::NoWarning => Ok(()), // no warning
518 /// Helper function used inside the shims of foreign functions to assert that the target OS
519 /// is `target_os`. It panics showing a message with the `name` of the foreign function
520 /// if this is not the case.
521 fn assert_target_os(&self, target_os: &str, name: &str) {
523 self.eval_context_ref().tcx.sess.target.os,
525 "`{}` is only available on the `{}` target OS",
531 /// Helper function used inside the shims of foreign functions to assert that the target OS
532 /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
533 /// if this is not the case.
534 fn assert_target_os_is_unix(&self, name: &str) {
536 target_os_is_unix(self.eval_context_ref().tcx.sess.target.os.as_ref()),
537 "`{}` is only available for supported UNIX family targets",
542 /// Get last error variable as a place, lazily allocating thread-local storage for it if
544 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
545 let this = self.eval_context_mut();
546 if let Some(errno_place) = this.active_thread_ref().last_error {
549 // Allocate new place, set initial value to 0.
550 let errno_layout = this.machine.layouts.u32;
551 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
552 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
553 this.active_thread_mut().last_error = Some(errno_place);
558 /// Sets the last error variable.
559 fn set_last_error(&mut self, scalar: Scalar<Provenance>) -> InterpResult<'tcx> {
560 let this = self.eval_context_mut();
561 let errno_place = this.last_error_place()?;
562 this.write_scalar(scalar, &errno_place.into())
565 /// Gets the last error variable.
566 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Provenance>> {
567 let this = self.eval_context_mut();
568 let errno_place = this.last_error_place()?;
569 this.read_scalar(&errno_place.into())
572 /// This function tries to produce the most similar OS error from the `std::io::ErrorKind`
573 /// as a platform-specific errnum.
574 fn io_error_to_errnum(
576 err_kind: std::io::ErrorKind,
577 ) -> InterpResult<'tcx, Scalar<Provenance>> {
578 let this = self.eval_context_ref();
579 let target = &this.tcx.sess.target;
580 if target.families.iter().any(|f| f == "unix") {
581 for &(name, kind) in UNIX_IO_ERROR_TABLE {
582 if err_kind == kind {
583 return this.eval_libc(name);
586 throw_unsup_format!("io error {:?} cannot be translated into a raw os error", err_kind)
587 } else if target.families.iter().any(|f| f == "windows") {
588 // FIXME: we have to finish implementing the Windows equivalent of this.
589 use std::io::ErrorKind::*;
593 NotFound => "ERROR_FILE_NOT_FOUND",
594 PermissionDenied => "ERROR_ACCESS_DENIED",
597 "io error {:?} cannot be translated into a raw os error",
604 "converting io::Error into errnum is unsupported for OS {}",
610 /// The inverse of `io_error_to_errnum`.
611 #[allow(clippy::needless_return)]
612 fn try_errnum_to_io_error(
614 errnum: Scalar<Provenance>,
615 ) -> InterpResult<'tcx, Option<std::io::ErrorKind>> {
616 let this = self.eval_context_ref();
617 let target = &this.tcx.sess.target;
618 if target.families.iter().any(|f| f == "unix") {
619 let errnum = errnum.to_i32()?;
620 for &(name, kind) in UNIX_IO_ERROR_TABLE {
621 if errnum == this.eval_libc_i32(name)? {
622 return Ok(Some(kind));
625 // Our table is as complete as the mapping in std, so we are okay with saying "that's a
626 // strange one" here.
630 "converting errnum into io::Error is unsupported for OS {}",
636 /// Sets the last OS error using a `std::io::ErrorKind`.
637 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
638 self.set_last_error(self.io_error_to_errnum(err_kind)?)
641 /// Helper function that consumes an `std::io::Result<T>` and returns an
642 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
643 /// `Ok(-1)` and sets the last OS error accordingly.
645 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
646 /// functions return different integer types (like `read`, that returns an `i64`).
647 fn try_unwrap_io_result<T: From<i32>>(
649 result: std::io::Result<T>,
650 ) -> InterpResult<'tcx, T> {
654 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
660 /// Calculates the MPlaceTy given the offset and layout of an access on an operand
661 fn deref_operand_and_offset(
663 op: &OpTy<'tcx, Provenance>,
665 layout: TyAndLayout<'tcx>,
666 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
667 let this = self.eval_context_ref();
668 let op_place = this.deref_operand(op)?;
669 let offset = Size::from_bytes(offset);
671 // Ensure that the access is within bounds.
672 assert!(op_place.layout.size >= offset + layout.size);
673 let value_place = op_place.offset(offset, layout, this)?;
677 fn read_scalar_at_offset(
679 op: &OpTy<'tcx, Provenance>,
681 layout: TyAndLayout<'tcx>,
682 ) -> InterpResult<'tcx, Scalar<Provenance>> {
683 let this = self.eval_context_ref();
684 let value_place = this.deref_operand_and_offset(op, offset, layout)?;
685 this.read_scalar(&value_place.into())
688 fn write_immediate_at_offset(
690 op: &OpTy<'tcx, Provenance>,
692 value: &ImmTy<'tcx, Provenance>,
693 ) -> InterpResult<'tcx, ()> {
694 let this = self.eval_context_mut();
695 let value_place = this.deref_operand_and_offset(op, offset, value.layout)?;
696 this.write_immediate(**value, &value_place.into())
699 fn write_scalar_at_offset(
701 op: &OpTy<'tcx, Provenance>,
703 value: impl Into<Scalar<Provenance>>,
704 layout: TyAndLayout<'tcx>,
705 ) -> InterpResult<'tcx, ()> {
706 self.write_immediate_at_offset(op, offset, &ImmTy::from_scalar(value.into(), layout))
709 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
710 /// if the value in the `timespec` struct is invalid. Some libc functions will return
711 /// `EINVAL` in this case.
714 tp: &MPlaceTy<'tcx, Provenance>,
715 ) -> InterpResult<'tcx, Option<Duration>> {
716 let this = self.eval_context_mut();
717 let seconds_place = this.mplace_field(tp, 0)?;
718 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
719 let seconds = seconds_scalar.to_machine_isize(this)?;
720 let nanoseconds_place = this.mplace_field(tp, 1)?;
721 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
722 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
725 // tv_sec must be non-negative.
726 let seconds: u64 = seconds.try_into().ok()?;
727 // tv_nsec must be non-negative.
728 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
729 if nanoseconds >= 1_000_000_000 {
730 // tv_nsec must not be greater than 999,999,999.
733 Duration::new(seconds, nanoseconds)
737 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, &'a [u8]>
742 let this = self.eval_context_ref();
743 let size1 = Size::from_bytes(1);
745 // Step 1: determine the length.
746 let mut len = Size::ZERO;
748 // FIXME: We are re-getting the allocation each time around the loop.
749 // Would be nice if we could somehow "extend" an existing AllocRange.
750 let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
751 let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
759 // Step 2: get the bytes.
760 this.read_bytes_ptr_strip_provenance(ptr, len)
763 fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {
764 let this = self.eval_context_ref();
765 let size2 = Size::from_bytes(2);
766 let align2 = Align::from_bytes(2).unwrap();
768 let mut wchars = Vec::new();
770 // FIXME: We are re-getting the allocation each time around the loop.
771 // Would be nice if we could somehow "extend" an existing AllocRange.
772 let alloc = this.get_ptr_alloc(ptr, size2, align2)?.unwrap(); // not a ZST, so we will get a result
773 let wchar = alloc.read_integer(alloc_range(Size::ZERO, size2))?.to_u16()?;
778 ptr = ptr.offset(size2, this)?;
785 /// Check that the ABI is what we expect.
786 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
787 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
789 "calling a function with ABI {} using caller ABI {}",
797 fn frame_in_std(&self) -> bool {
798 let this = self.eval_context_ref();
799 let Some(start_fn) = this.tcx.lang_items().start_fn() else {
803 let frame = this.frame();
804 // Make an attempt to get at the instance of the function this is inlined from.
805 let instance: Option<_> = try {
806 let scope = frame.current_source_info()?.scope;
807 let inlined_parent = frame.body.source_scopes[scope].inlined_parent_scope?;
808 let source = &frame.body.source_scopes[inlined_parent];
809 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
811 // Fall back to the instance of the function itself.
812 let instance = instance.unwrap_or(frame.instance);
813 // Now check if this is in the same crate as start_fn.
814 // As a special exception we also allow unit tests from
815 // <https://github.com/rust-lang/miri-test-libstd/tree/master/std_miri_test> to call these
817 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
818 frame_crate == this.tcx.def_path(start_fn).krate
819 || this.tcx.crate_name(frame_crate).as_str() == "std_miri_test"
822 /// Handler that should be called when unsupported functionality is encountered.
823 /// This function will either panic within the context of the emulated application
824 /// or return an error in the Miri process context
826 /// Return value of `Ok(bool)` indicates whether execution should continue.
827 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
828 let this = self.eval_context_mut();
829 if this.machine.panic_on_unsupported {
830 // message is slightly different here to make automated analysis easier
831 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
832 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
835 throw_unsup_format!("{}", error_msg.as_ref());
839 fn check_abi_and_shim_symbol_clash(
844 ) -> InterpResult<'tcx, ()> {
845 self.check_abi(abi, exp_abi)?;
846 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
847 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
849 span: body.span.data(),
855 fn check_shim<'a, const N: usize>(
860 args: &'a [OpTy<'tcx, Provenance>],
861 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
863 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
865 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
866 check_arg_count(args)
869 /// Mark a machine allocation that was just created as immutable.
870 fn mark_immutable(&mut self, mplace: &MemPlace<Provenance>) {
871 let this = self.eval_context_mut();
872 // This got just allocated, so there definitely is a pointer here.
873 let provenance = mplace.ptr.into_pointer_or_addr().unwrap().provenance;
874 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
877 fn item_link_name(&self, def_id: DefId) -> Symbol {
878 let tcx = self.eval_context_ref().tcx;
879 match tcx.get_attrs(def_id, sym::link_name).filter_map(|a| a.value_str()).next() {
881 None => tcx.item_name(def_id),
886 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
887 pub fn current_span(&self) -> CurrentSpan<'_, 'mir, 'tcx> {
888 CurrentSpan { current_frame_idx: None, machine: self }
892 /// A `CurrentSpan` should be created infrequently (ideally once) per interpreter step. It does
893 /// nothing on creation, but when `CurrentSpan::get` is called, searches the current stack for the
894 /// topmost frame which corresponds to a local crate, and returns the current span in that frame.
895 /// The result of that search is cached so that later calls are approximately free.
897 pub struct CurrentSpan<'a, 'mir, 'tcx> {
898 current_frame_idx: Option<usize>,
899 machine: &'a MiriMachine<'mir, 'tcx>,
902 impl<'a, 'mir: 'a, 'tcx: 'a + 'mir> CurrentSpan<'a, 'mir, 'tcx> {
903 pub fn machine(&self) -> &'a MiriMachine<'mir, 'tcx> {
907 /// Get the current span, skipping non-local frames.
908 /// This function is backed by a cache, and can be assumed to be very fast.
909 pub fn get(&mut self) -> Span {
910 let idx = self.current_frame_idx();
911 Self::frame_span(self.machine, idx)
914 /// Similar to `CurrentSpan::get`, but retrieves the parent frame of the first non-local frame.
915 /// This is useful when we are processing something which occurs on function-entry and we want
916 /// to point at the call to the function, not the function definition generally.
917 pub fn get_parent(&mut self) -> Span {
918 let idx = self.current_frame_idx();
919 Self::frame_span(self.machine, idx.wrapping_sub(1))
922 fn frame_span(machine: &MiriMachine<'_, '_>, idx: usize) -> Span {
925 .active_thread_stack()
927 .map(Frame::current_span)
928 .unwrap_or(rustc_span::DUMMY_SP)
931 fn current_frame_idx(&mut self) -> usize {
934 .get_or_insert_with(|| Self::compute_current_frame_index(self.machine))
937 // Find the position of the inner-most frame which is part of the crate being
938 // compiled/executed, part of the Cargo workspace, and is also not #[track_caller].
940 fn compute_current_frame_index(machine: &MiriMachine<'_, '_>) -> usize {
943 .active_thread_stack()
947 .find_map(|(idx, frame)| {
948 let def_id = frame.instance.def_id();
949 if (def_id.is_local() || machine.local_crates.contains(&def_id.krate))
950 && !frame.instance.def.requires_caller_location(machine.tcx)
961 /// Check that the number of args is what we expect.
962 pub fn check_arg_count<'a, 'tcx, const N: usize>(
963 args: &'a [OpTy<'tcx, Provenance>],
964 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
966 &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
968 if let Ok(ops) = args.try_into() {
971 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
974 pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
975 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
976 "{} not available when isolation is enabled",
981 /// Retrieve the list of local crates that should have been passed by cargo-miri in
982 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
983 pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
984 // Convert the local crate names from the passed-in config into CrateNums so that they can
985 // be looked up quickly during execution
986 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
987 .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
988 .unwrap_or_default();
989 let mut local_crates = Vec::new();
990 for &crate_num in tcx.crates(()) {
991 let name = tcx.crate_name(crate_num);
992 let name = name.as_str();
993 if local_crate_names.iter().any(|local_name| local_name == name) {
994 local_crates.push(crate_num);
1000 /// Helper function used inside the shims of foreign functions to check that
1001 /// `target_os` is a supported UNIX OS.
1002 pub fn target_os_is_unix(target_os: &str) -> bool {
1003 matches!(target_os, "linux" | "macos" | "freebsd" | "android")