1 use std::convert::{TryFrom, TryInto};
3 use std::num::NonZeroUsize;
4 use std::time::Duration;
8 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_middle::ty::{
12 layout::{LayoutOf, TyAndLayout},
15 use rustc_span::Symbol;
16 use rustc_target::abi::{Align, FieldsShape, Size, Variants};
17 use rustc_target::spec::abi::Abi;
23 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
25 /// Gets an instance for a path.
26 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
27 tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == path[0]).and_then(
29 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
30 let mut items = tcx.module_children(krate);
31 let mut path_it = path.iter().skip(1).peekable();
33 while let Some(segment) = path_it.next() {
34 for item in mem::replace(&mut items, Default::default()).iter() {
35 if item.ident.name.as_str() == *segment {
36 if path_it.peek().is_none() {
37 return Some(item.res.def_id());
40 items = tcx.module_children(item.res.def_id());
50 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
51 /// Gets an instance for a path.
52 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
53 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)
54 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path));
55 ty::Instance::mono(self.eval_context_ref().tcx.tcx, did)
58 /// Evaluates the scalar at the specified path. Returns Some(val)
59 /// if the path could be resolved, and None otherwise
60 fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Scalar<Tag>> {
61 let this = self.eval_context_mut();
62 let instance = this.resolve_path(path);
63 let cid = GlobalId { instance, promoted: None };
64 let const_val = this.eval_to_allocation(cid)?;
65 let const_val = this.read_scalar(&const_val.into())?;
66 return Ok(const_val.check_init()?);
69 /// Helper function to get a `libc` constant as a `Scalar`.
70 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
71 self.eval_context_mut().eval_path_scalar(&["libc", name])
74 /// Helper function to get a `libc` constant as an `i32`.
75 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
76 // TODO: Cache the result.
77 self.eval_libc(name)?.to_i32()
80 /// Helper function to get a `windows` constant as a `Scalar`.
81 fn eval_windows(&mut self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
82 self.eval_context_mut().eval_path_scalar(&["std", "sys", "windows", module, name])
85 /// Helper function to get a `windows` constant as a `u64`.
86 fn eval_windows_u64(&mut self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
87 // TODO: Cache the result.
88 self.eval_windows(module, name)?.to_u64()
91 /// Helper function to get the `TyAndLayout` of a `libc` type
92 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
93 let this = self.eval_context_mut();
94 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
98 /// Helper function to get the `TyAndLayout` of a `windows` type
99 fn windows_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
100 let this = self.eval_context_mut();
102 .resolve_path(&["std", "sys", "windows", "c", name])
103 .ty(*this.tcx, ty::ParamEnv::reveal_all());
107 /// Write a uint of the appropriate size to `dest`.
108 fn write_uint(&mut self, i: impl Into<u128>, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
109 self.eval_context_mut().write_scalar(Scalar::from_uint(i, dest.layout.size), dest)
112 /// Write an int of the appropriate size to `dest`.
113 fn write_int(&mut self, i: impl Into<i128>, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
114 self.eval_context_mut().write_scalar(Scalar::from_int(i, dest.layout.size), dest)
117 /// Write a 0 of the appropriate size to `dest`.
118 fn write_null(&mut self, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
119 self.write_int(0, dest)
122 /// Test if this pointer equals 0.
123 fn ptr_is_null(&self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, bool> {
124 let this = self.eval_context_ref();
125 let null = Scalar::null_ptr(this);
126 this.ptr_eq(Scalar::from_maybe_pointer(ptr, this), null)
129 /// Get the `Place` for a local
130 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
131 let this = self.eval_context_mut();
132 let place = mir::Place { local: local, projection: List::empty() };
133 this.eval_place(place)
136 /// Generate some random bytes, and write them to `dest`.
137 fn gen_random(&mut self, ptr: Pointer<Option<Tag>>, len: u64) -> InterpResult<'tcx> {
138 // Some programs pass in a null pointer and a length of 0
139 // to their platform's random-generation function (e.g. getrandom())
140 // on Linux. For compatibility with these programs, we don't perform
141 // any additional checks - it's okay if the pointer is invalid,
142 // since we wouldn't actually be writing to it.
146 let this = self.eval_context_mut();
148 let mut data = vec![0; usize::try_from(len).unwrap()];
150 if this.machine.communicate() {
151 // Fill the buffer using the host's rng.
152 getrandom::getrandom(&mut data)
153 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
155 let rng = this.memory.extra.rng.get_mut();
156 rng.fill_bytes(&mut data);
159 this.memory.write_bytes(ptr, data.iter().copied())
162 /// Call a function: Push the stack frame and pass the arguments.
163 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
166 f: ty::Instance<'tcx>,
168 args: &[Immediate<Tag>],
169 dest: Option<&PlaceTy<'tcx, Tag>>,
170 stack_pop: StackPopCleanup,
171 ) -> InterpResult<'tcx> {
172 let this = self.eval_context_mut();
173 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
174 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
175 if this.machine.enforce_abi && callee_abi != caller_abi {
177 "calling a function with ABI {} using caller ABI {}",
184 let mir = &*this.load_mir(f.def, None)?;
185 this.push_stack_frame(f, mir, dest, stack_pop)?;
187 // Initialize arguments.
188 let mut callee_args = this.frame().body.args_iter();
190 let callee_arg = this.local_place(
193 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
195 this.write_immediate(*arg, &callee_arg)?;
197 if callee_args.next().is_some() {
198 throw_ub_format!("callee has more arguments than expected");
204 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
205 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
206 /// The range is relative to `place`.
208 /// Assumes that the `place` has a proper pointer in it.
209 fn visit_freeze_sensitive(
211 place: &MPlaceTy<'tcx, Tag>,
213 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
214 ) -> InterpResult<'tcx> {
215 let this = self.eval_context_ref();
216 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
219 this.size_and_align_of_mplace(place)?
220 .map(|(size, _)| size)
221 .unwrap_or_else(|| place.layout.size)
223 // Store how far we proceeded into the place so far. Everything to the left of
224 // this offset has already been handled, in the sense that the frozen parts
225 // have had `action` called on them.
226 let ptr = place.ptr.into_pointer_or_addr().unwrap();
227 let start_offset = ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
228 let mut cur_offset = start_offset;
229 // Called when we detected an `UnsafeCell` at the given offset and size.
230 // Calls `action` and advances `cur_ptr`.
231 let mut unsafe_cell_action = |unsafe_cell_ptr: Pointer<Option<Tag>>,
232 unsafe_cell_size: Size| {
233 let unsafe_cell_ptr = unsafe_cell_ptr.into_pointer_or_addr().unwrap();
234 debug_assert_eq!(unsafe_cell_ptr.provenance, ptr.provenance);
235 // We assume that we are given the fields in increasing offset order,
236 // and nothing else changes.
237 let unsafe_cell_offset = unsafe_cell_ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
238 assert!(unsafe_cell_offset >= cur_offset);
239 let frozen_size = unsafe_cell_offset - cur_offset;
240 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
241 if frozen_size != Size::ZERO {
242 action(alloc_range(cur_offset - start_offset, frozen_size), /*frozen*/ true)?;
244 cur_offset += frozen_size;
245 // This `UnsafeCell` is NOT frozen.
246 if unsafe_cell_size != Size::ZERO {
248 alloc_range(cur_offset - start_offset, unsafe_cell_size),
252 cur_offset += unsafe_cell_size;
258 let mut visitor = UnsafeCellVisitor {
260 unsafe_cell_action: |place| {
261 trace!("unsafe_cell_action on {:?}", place.ptr);
262 // We need a size to go on.
263 let unsafe_cell_size = this
264 .size_and_align_of_mplace(&place)?
265 .map(|(size, _)| size)
266 // for extern types, just cover what we can
267 .unwrap_or_else(|| place.layout.size);
268 // Now handle this `UnsafeCell`, unless it is empty.
269 if unsafe_cell_size != Size::ZERO {
270 unsafe_cell_action(place.ptr, unsafe_cell_size)
276 visitor.visit_value(place)?;
278 // The part between the end_ptr and the end of the place is also frozen.
279 // So pretend there is a 0-sized `UnsafeCell` at the end.
280 unsafe_cell_action(place.ptr.wrapping_offset(size, this), Size::ZERO)?;
284 /// Visiting the memory covered by a `MemPlace`, being aware of
285 /// whether we are inside an `UnsafeCell` or not.
286 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
288 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
290 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
291 unsafe_cell_action: F,
294 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
295 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
297 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
299 type V = MPlaceTy<'tcx, Tag>;
302 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
306 // Hook to detect `UnsafeCell`.
307 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
308 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
309 let is_unsafe_cell = match v.layout.ty.kind() {
311 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
315 // We do not have to recurse further, this is an `UnsafeCell`.
316 (self.unsafe_cell_action)(v)
317 } else if self.ecx.type_is_freeze(v.layout.ty) {
318 // This is `Freeze`, there cannot be an `UnsafeCell`
320 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
321 // A (non-frozen) union. We fall back to whatever the type says.
322 (self.unsafe_cell_action)(v)
324 // We want to not actually read from memory for this visit. So, before
325 // walking this value, we have to make sure it is not a
326 // `Variants::Multiple`.
327 match v.layout.variants {
328 Variants::Multiple { .. } => {
329 // A multi-variant enum, or generator, or so.
330 // Treat this like a union: without reading from memory,
331 // we cannot determine the variant we are in. Reading from
332 // memory would be subject to Stacked Borrows rules, leading
333 // to all sorts of "funny" recursion.
334 // We only end up here if the type is *not* freeze, so we just call the
335 // `UnsafeCell` action.
336 (self.unsafe_cell_action)(v)
338 Variants::Single { .. } => {
339 // Proceed further, try to find where exactly that `UnsafeCell`
347 // Make sure we visit aggregrates in increasing offset order.
350 place: &MPlaceTy<'tcx, Tag>,
351 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
352 ) -> InterpResult<'tcx> {
353 match place.layout.fields {
354 FieldsShape::Array { .. } => {
355 // For the array layout, we know the iterator will yield sorted elements so
356 // we can avoid the allocation.
357 self.walk_aggregate(place, fields)
359 FieldsShape::Arbitrary { .. } => {
360 // Gather the subplaces and sort them before visiting.
362 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
363 // we just compare offsets, the abs. value never matters
364 places.sort_by_key(|place| {
365 place.ptr.into_pointer_or_addr().unwrap().into_parts().1 as Size
367 self.walk_aggregate(place, places.into_iter().map(Ok))
369 FieldsShape::Union { .. } | FieldsShape::Primitive => {
371 bug!("unions/primitives are not aggregates we should ever visit")
378 _v: &MPlaceTy<'tcx, Tag>,
379 _fields: NonZeroUsize,
380 ) -> InterpResult<'tcx> {
381 bug!("we should have already handled unions in `visit_value`")
386 // Writes several `ImmTy`s contiguously into memory. This is useful when you have to pack
387 // different values into a struct.
388 fn write_packed_immediates(
390 place: &MPlaceTy<'tcx, Tag>,
391 imms: &[ImmTy<'tcx, Tag>],
392 ) -> InterpResult<'tcx> {
393 let this = self.eval_context_mut();
395 let mut offset = Size::from_bytes(0);
398 this.write_immediate(
400 &place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?.into(),
402 offset += imm.layout.size;
407 /// Helper function used inside the shims of foreign functions to check that isolation is
408 /// disabled. It returns an error using the `name` of the foreign function if this is not the
410 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
411 if !self.eval_context_ref().machine.communicate() {
412 self.reject_in_isolation(name, RejectOpWith::Abort)?;
417 /// Helper function used inside the shims of foreign functions which reject the op
418 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
419 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
420 let this = self.eval_context_ref();
422 RejectOpWith::Abort => isolation_abort_error(op_name),
423 RejectOpWith::WarningWithoutBacktrace => {
426 .warn(&format!("{} was made to return an error due to isolation", op_name));
429 RejectOpWith::Warning => {
430 register_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
433 RejectOpWith::NoWarning => Ok(()), // no warning
437 /// Helper function used inside the shims of foreign functions to assert that the target OS
438 /// is `target_os`. It panics showing a message with the `name` of the foreign function
439 /// if this is not the case.
440 fn assert_target_os(&self, target_os: &str, name: &str) {
442 self.eval_context_ref().tcx.sess.target.os,
444 "`{}` is only available on the `{}` target OS",
450 /// Get last error variable as a place, lazily allocating thread-local storage for it if
452 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
453 let this = self.eval_context_mut();
454 if let Some(errno_place) = this.active_thread_ref().last_error {
457 // Allocate new place, set initial value to 0.
458 let errno_layout = this.machine.layouts.u32;
459 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
460 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
461 this.active_thread_mut().last_error = Some(errno_place);
466 /// Sets the last error variable.
467 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
468 let this = self.eval_context_mut();
469 let errno_place = this.last_error_place()?;
470 this.write_scalar(scalar, &errno_place.into())
473 /// Gets the last error variable.
474 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
475 let this = self.eval_context_mut();
476 let errno_place = this.last_error_place()?;
477 this.read_scalar(&errno_place.into())?.check_init()
480 /// Sets the last OS error using a `std::io::ErrorKind`. This function tries to produce the most
481 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
482 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
483 use std::io::ErrorKind::*;
484 let this = self.eval_context_mut();
485 let target = &this.tcx.sess.target;
486 let target_os = &target.os;
487 let last_error = if target.families.contains(&"unix".to_owned()) {
488 this.eval_libc(match err_kind {
489 ConnectionRefused => "ECONNREFUSED",
490 ConnectionReset => "ECONNRESET",
491 PermissionDenied => "EPERM",
492 BrokenPipe => "EPIPE",
493 NotConnected => "ENOTCONN",
494 ConnectionAborted => "ECONNABORTED",
495 AddrNotAvailable => "EADDRNOTAVAIL",
496 AddrInUse => "EADDRINUSE",
497 NotFound => "ENOENT",
498 Interrupted => "EINTR",
499 InvalidInput => "EINVAL",
500 TimedOut => "ETIMEDOUT",
501 AlreadyExists => "EEXIST",
502 WouldBlock => "EWOULDBLOCK",
503 DirectoryNotEmpty => "ENOTEMPTY",
506 "io error {:?} cannot be translated into a raw os error",
511 } else if target.families.contains(&"windows".to_owned()) {
512 // FIXME: we have to finish implementing the Windows equivalent of this.
516 NotFound => "ERROR_FILE_NOT_FOUND",
517 PermissionDenied => "ERROR_ACCESS_DENIED",
520 "io error {:?} cannot be translated into a raw os error",
527 "setting the last OS error from an io::Error is unsupported for {}.",
531 this.set_last_error(last_error)
534 /// Helper function that consumes an `std::io::Result<T>` and returns an
535 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
536 /// `Ok(-1)` and sets the last OS error accordingly.
538 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
539 /// functions return different integer types (like `read`, that returns an `i64`).
540 fn try_unwrap_io_result<T: From<i32>>(
542 result: std::io::Result<T>,
543 ) -> InterpResult<'tcx, T> {
547 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
553 fn read_scalar_at_offset(
555 op: &OpTy<'tcx, Tag>,
557 layout: TyAndLayout<'tcx>,
558 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
559 let this = self.eval_context_ref();
560 let op_place = this.deref_operand(op)?;
561 let offset = Size::from_bytes(offset);
562 // Ensure that the following read at an offset is within bounds
563 assert!(op_place.layout.size >= offset + layout.size);
564 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
565 this.read_scalar(&value_place.into())
568 fn write_scalar_at_offset(
570 op: &OpTy<'tcx, Tag>,
572 value: impl Into<ScalarMaybeUninit<Tag>>,
573 layout: TyAndLayout<'tcx>,
574 ) -> InterpResult<'tcx, ()> {
575 let this = self.eval_context_mut();
576 let op_place = this.deref_operand(op)?;
577 let offset = Size::from_bytes(offset);
578 // Ensure that the following read at an offset is within bounds
579 assert!(op_place.layout.size >= offset + layout.size);
580 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
581 this.write_scalar(value, &value_place.into())
584 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
585 /// if the value in the `timespec` struct is invalid. Some libc functions will return
586 /// `EINVAL` in this case.
587 fn read_timespec(&mut self, tp: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx, Option<Duration>> {
588 let this = self.eval_context_mut();
589 let seconds_place = this.mplace_field(&tp, 0)?;
590 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
591 let seconds = seconds_scalar.to_machine_isize(this)?;
592 let nanoseconds_place = this.mplace_field(&tp, 1)?;
593 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
594 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
597 // tv_sec must be non-negative.
598 let seconds: u64 = seconds.try_into().ok()?;
599 // tv_nsec must be non-negative.
600 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
601 if nanoseconds >= 1_000_000_000 {
602 // tv_nsec must not be greater than 999,999,999.
605 Duration::new(seconds, nanoseconds)
609 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, &'a [u8]>
614 let this = self.eval_context_ref();
615 let size1 = Size::from_bytes(1);
617 // Step 1: determine the length.
618 let mut len = Size::ZERO;
620 // FIXME: We are re-getting the allocation each time around the loop.
621 // Would be nice if we could somehow "extend" an existing AllocRange.
622 let alloc = this.memory.get(ptr.offset(len, this)?.into(), size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
623 let byte = alloc.read_scalar(alloc_range(Size::ZERO, size1))?.to_u8()?;
631 // Step 2: get the bytes.
632 this.memory.read_bytes(ptr.into(), len)
635 fn read_wide_str(&self, mut ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, Vec<u16>> {
636 let this = self.eval_context_ref();
637 let size2 = Size::from_bytes(2);
638 let align2 = Align::from_bytes(2).unwrap();
640 let mut wchars = Vec::new();
642 // FIXME: We are re-getting the allocation each time around the loop.
643 // Would be nice if we could somehow "extend" an existing AllocRange.
644 let alloc = this.memory.get(ptr.into(), size2, align2)?.unwrap(); // not a ZST, so we will get a result
645 let wchar = alloc.read_scalar(alloc_range(Size::ZERO, size2))?.to_u16()?;
650 ptr = ptr.offset(size2, this)?;
657 /// Check that the ABI is what we expect.
658 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
659 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
661 "calling a function with ABI {} using caller ABI {}",
669 fn frame_in_std(&self) -> bool {
670 let this = self.eval_context_ref();
671 this.tcx.lang_items().start_fn().map_or(false, |start_fn| {
672 this.tcx.def_path(this.frame().instance.def_id()).krate
673 == this.tcx.def_path(start_fn).krate
677 /// Handler that should be called when unsupported functionality is encountered.
678 /// This function will either panic within the context of the emulated application
679 /// or return an error in the Miri process context
681 /// Return value of `Ok(bool)` indicates whether execution should continue.
682 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
683 let this = self.eval_context_mut();
684 if this.machine.panic_on_unsupported {
685 // message is slightly different here to make automated analysis easier
686 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
687 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
690 throw_unsup_format!("{}", error_msg.as_ref());
694 fn check_abi_and_shim_symbol_clash(
699 ) -> InterpResult<'tcx, ()> {
700 self.check_abi(abi, exp_abi)?;
701 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
702 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
704 span: body.span.data(),
710 fn check_shim<'a, const N: usize>(
715 args: &'a [OpTy<'tcx, Tag>],
716 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
718 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
720 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
721 check_arg_count(args)
724 /// Mark a machine allocation that was just created as immutable.
725 fn mark_immutable(&mut self, mplace: &MemPlace<Tag>) {
726 let this = self.eval_context_mut();
728 .mark_immutable(mplace.ptr.into_pointer_or_addr().unwrap().provenance.alloc_id)
733 /// Check that the number of args is what we expect.
734 pub fn check_arg_count<'a, 'tcx, const N: usize>(
735 args: &'a [OpTy<'tcx, Tag>],
736 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
738 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
740 if let Ok(ops) = args.try_into() {
743 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
746 pub fn isolation_abort_error(name: &str) -> InterpResult<'static> {
747 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
748 "{} not available when isolation is enabled",
753 pub fn immty_from_int_checked<'tcx>(
754 int: impl Into<i128>,
755 layout: TyAndLayout<'tcx>,
756 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
757 let int = int.into();
758 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
759 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
763 pub fn immty_from_uint_checked<'tcx>(
764 int: impl Into<u128>,
765 layout: TyAndLayout<'tcx>,
766 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
767 let int = int.into();
768 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
769 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())
773 pub fn bool_to_simd_element(b: bool, size: Size) -> Scalar<Tag> {
774 // SIMD uses all-1 as pattern for "true"
775 let val = if b { -1 } else { 0 };
776 Scalar::from_int(val, size)
779 pub fn simd_element_to_bool<'tcx>(elem: ImmTy<'tcx, Tag>) -> InterpResult<'tcx, bool> {
780 let val = elem.to_scalar()?.to_int(elem.layout.size)?;
784 _ => throw_ub_format!("each element of a SIMD mask must be all-0-bits or all-1-bits"),