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::{self, layout::TyAndLayout, List, TyCtxt};
11 use rustc_span::Symbol;
12 use rustc_target::abi::{Align, FieldsShape, LayoutOf, Size, Variants};
13 use rustc_target::spec::abi::Abi;
19 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
21 /// Gets an instance for a path.
22 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
23 tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == path[0]).and_then(
25 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
26 let mut items = tcx.item_children(krate);
27 let mut path_it = path.iter().skip(1).peekable();
29 while let Some(segment) = path_it.next() {
30 for item in mem::replace(&mut items, Default::default()).iter() {
31 if item.ident.name.as_str() == *segment {
32 if path_it.peek().is_none() {
33 return Some(item.res.def_id());
36 items = tcx.item_children(item.res.def_id());
46 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
47 /// Gets an instance for a path.
48 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
49 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)
50 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path));
51 ty::Instance::mono(self.eval_context_ref().tcx.tcx, did)
54 /// Evaluates the scalar at the specified path. Returns Some(val)
55 /// if the path could be resolved, and None otherwise
56 fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Scalar<Tag>> {
57 let this = self.eval_context_mut();
58 let instance = this.resolve_path(path);
59 let cid = GlobalId { instance, promoted: None };
60 let const_val = this.eval_to_allocation(cid)?;
61 let const_val = this.read_scalar(&const_val.into())?;
62 return Ok(const_val.check_init()?);
65 /// Helper function to get a `libc` constant as a `Scalar`.
66 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
67 self.eval_context_mut().eval_path_scalar(&["libc", name])
70 /// Helper function to get a `libc` constant as an `i32`.
71 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
72 // TODO: Cache the result.
73 self.eval_libc(name)?.to_i32()
76 /// Helper function to get a `windows` constant as a `Scalar`.
77 fn eval_windows(&mut self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
78 self.eval_context_mut().eval_path_scalar(&["std", "sys", "windows", module, name])
81 /// Helper function to get a `windows` constant as a `u64`.
82 fn eval_windows_u64(&mut self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
83 // TODO: Cache the result.
84 self.eval_windows(module, name)?.to_u64()
87 /// Helper function to get the `TyAndLayout` of a `libc` type
88 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
89 let this = self.eval_context_mut();
90 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
94 /// Helper function to get the `TyAndLayout` of a `windows` type
95 fn windows_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
96 let this = self.eval_context_mut();
98 .resolve_path(&["std", "sys", "windows", "c", name])
99 .ty(*this.tcx, ty::ParamEnv::reveal_all());
103 /// Write a 0 of the appropriate size to `dest`.
104 fn write_null(&mut self, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
105 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
108 /// Test if this pointer equals 0.
109 fn ptr_is_null(&self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, bool> {
110 let this = self.eval_context_ref();
111 let null = Scalar::null_ptr(this);
112 this.ptr_eq(Scalar::from_maybe_pointer(ptr, this), null)
115 /// Get the `Place` for a local
116 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
117 let this = self.eval_context_mut();
118 let place = mir::Place { local: local, projection: List::empty() };
119 this.eval_place(place)
122 /// Generate some random bytes, and write them to `dest`.
123 fn gen_random(&mut self, ptr: Pointer<Option<Tag>>, len: u64) -> InterpResult<'tcx> {
124 // Some programs pass in a null pointer and a length of 0
125 // to their platform's random-generation function (e.g. getrandom())
126 // on Linux. For compatibility with these programs, we don't perform
127 // any additional checks - it's okay if the pointer is invalid,
128 // since we wouldn't actually be writing to it.
132 let this = self.eval_context_mut();
134 let mut data = vec![0; usize::try_from(len).unwrap()];
136 if this.machine.communicate() {
137 // Fill the buffer using the host's rng.
138 getrandom::getrandom(&mut data)
139 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
141 let rng = this.memory.extra.rng.get_mut();
142 rng.fill_bytes(&mut data);
145 this.memory.write_bytes(ptr, data.iter().copied())
148 /// Call a function: Push the stack frame and pass the arguments.
149 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
152 f: ty::Instance<'tcx>,
154 args: &[Immediate<Tag>],
155 dest: Option<&PlaceTy<'tcx, Tag>>,
156 stack_pop: StackPopCleanup,
157 ) -> InterpResult<'tcx> {
158 let this = self.eval_context_mut();
159 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
160 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
161 if this.machine.enforce_abi && callee_abi != caller_abi {
163 "calling a function with ABI {} using caller ABI {}",
170 let mir = &*this.load_mir(f.def, None)?;
171 this.push_stack_frame(f, mir, dest, stack_pop)?;
173 // Initialize arguments.
174 let mut callee_args = this.frame().body.args_iter();
176 let callee_arg = this.local_place(
179 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
181 this.write_immediate(*arg, &callee_arg)?;
183 if callee_args.next().is_some() {
184 throw_ub_format!("callee has more arguments than expected");
190 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
191 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
192 /// The range is relative to `place`.
194 /// Assumes that the `place` has a proper pointer in it.
195 fn visit_freeze_sensitive(
197 place: &MPlaceTy<'tcx, Tag>,
199 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
200 ) -> InterpResult<'tcx> {
201 let this = self.eval_context_ref();
202 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
205 this.size_and_align_of_mplace(place)?
206 .map(|(size, _)| size)
207 .unwrap_or_else(|| place.layout.size)
209 // Store how far we proceeded into the place so far. Everything to the left of
210 // this offset has already been handled, in the sense that the frozen parts
211 // have had `action` called on them.
212 let ptr = place.ptr.into_pointer_or_addr().unwrap();
213 let start_offset = ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
214 let mut cur_offset = start_offset;
215 // Called when we detected an `UnsafeCell` at the given offset and size.
216 // Calls `action` and advances `cur_ptr`.
217 let mut unsafe_cell_action = |unsafe_cell_ptr: Pointer<Option<Tag>>,
218 unsafe_cell_size: Size| {
219 let unsafe_cell_ptr = unsafe_cell_ptr.into_pointer_or_addr().unwrap();
220 debug_assert_eq!(unsafe_cell_ptr.provenance, ptr.provenance);
221 // We assume that we are given the fields in increasing offset order,
222 // and nothing else changes.
223 let unsafe_cell_offset = unsafe_cell_ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
224 assert!(unsafe_cell_offset >= cur_offset);
225 let frozen_size = unsafe_cell_offset - cur_offset;
226 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
227 if frozen_size != Size::ZERO {
228 action(alloc_range(cur_offset - start_offset, frozen_size), /*frozen*/ true)?;
230 cur_offset += frozen_size;
231 // This `UnsafeCell` is NOT frozen.
232 if unsafe_cell_size != Size::ZERO {
234 alloc_range(cur_offset - start_offset, unsafe_cell_size),
238 cur_offset += unsafe_cell_size;
244 let mut visitor = UnsafeCellVisitor {
246 unsafe_cell_action: |place| {
247 trace!("unsafe_cell_action on {:?}", place.ptr);
248 // We need a size to go on.
249 let unsafe_cell_size = this
250 .size_and_align_of_mplace(&place)?
251 .map(|(size, _)| size)
252 // for extern types, just cover what we can
253 .unwrap_or_else(|| place.layout.size);
254 // Now handle this `UnsafeCell`, unless it is empty.
255 if unsafe_cell_size != Size::ZERO {
256 unsafe_cell_action(place.ptr, unsafe_cell_size)
262 visitor.visit_value(place)?;
264 // The part between the end_ptr and the end of the place is also frozen.
265 // So pretend there is a 0-sized `UnsafeCell` at the end.
266 unsafe_cell_action(place.ptr.wrapping_offset(size, this), Size::ZERO)?;
270 /// Visiting the memory covered by a `MemPlace`, being aware of
271 /// whether we are inside an `UnsafeCell` or not.
272 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
274 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
276 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
277 unsafe_cell_action: F,
280 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
281 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
283 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
285 type V = MPlaceTy<'tcx, Tag>;
288 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
292 // Hook to detect `UnsafeCell`.
293 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
294 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
295 let is_unsafe_cell = match v.layout.ty.kind() {
297 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
301 // We do not have to recurse further, this is an `UnsafeCell`.
302 (self.unsafe_cell_action)(v)
303 } else if self.ecx.type_is_freeze(v.layout.ty) {
304 // This is `Freeze`, there cannot be an `UnsafeCell`
306 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
307 // A (non-frozen) union. We fall back to whatever the type says.
308 (self.unsafe_cell_action)(v)
310 // We want to not actually read from memory for this visit. So, before
311 // walking this value, we have to make sure it is not a
312 // `Variants::Multiple`.
313 match v.layout.variants {
314 Variants::Multiple { .. } => {
315 // A multi-variant enum, or generator, or so.
316 // Treat this like a union: without reading from memory,
317 // we cannot determine the variant we are in. Reading from
318 // memory would be subject to Stacked Borrows rules, leading
319 // to all sorts of "funny" recursion.
320 // We only end up here if the type is *not* freeze, so we just call the
321 // `UnsafeCell` action.
322 (self.unsafe_cell_action)(v)
324 Variants::Single { .. } => {
325 // Proceed further, try to find where exactly that `UnsafeCell`
333 // Make sure we visit aggregrates in increasing offset order.
336 place: &MPlaceTy<'tcx, Tag>,
337 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
338 ) -> InterpResult<'tcx> {
339 match place.layout.fields {
340 FieldsShape::Array { .. } => {
341 // For the array layout, we know the iterator will yield sorted elements so
342 // we can avoid the allocation.
343 self.walk_aggregate(place, fields)
345 FieldsShape::Arbitrary { .. } => {
346 // Gather the subplaces and sort them before visiting.
348 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
349 // we just compare offsets, the abs. value never matters
350 places.sort_by_key(|place| {
351 place.ptr.into_pointer_or_addr().unwrap().into_parts().1 as Size
353 self.walk_aggregate(place, places.into_iter().map(Ok))
355 FieldsShape::Union { .. } | FieldsShape::Primitive => {
357 bug!("unions/primitives are not aggregates we should ever visit")
364 _v: &MPlaceTy<'tcx, Tag>,
365 _fields: NonZeroUsize,
366 ) -> InterpResult<'tcx> {
367 bug!("we should have already handled unions in `visit_value`")
372 // Writes several `ImmTy`s contiguously into memory. This is useful when you have to pack
373 // different values into a struct.
374 fn write_packed_immediates(
376 place: &MPlaceTy<'tcx, Tag>,
377 imms: &[ImmTy<'tcx, Tag>],
378 ) -> InterpResult<'tcx> {
379 let this = self.eval_context_mut();
381 let mut offset = Size::from_bytes(0);
384 this.write_immediate(
386 &place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?.into(),
388 offset += imm.layout.size;
393 /// Helper function used inside the shims of foreign functions to check that isolation is
394 /// disabled. It returns an error using the `name` of the foreign function if this is not the
396 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
397 if !self.eval_context_ref().machine.communicate() {
398 self.reject_in_isolation(name, RejectOpWith::Abort)?;
403 /// Helper function used inside the shims of foreign functions which reject the op
404 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
405 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
406 let this = self.eval_context_ref();
408 RejectOpWith::Abort => isolation_abort_error(op_name),
409 RejectOpWith::WarningWithoutBacktrace => {
412 .warn(&format!("{} was made to return an error due to isolation", op_name));
415 RejectOpWith::Warning => {
416 register_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
419 RejectOpWith::NoWarning => Ok(()), // no warning
423 /// Helper function used inside the shims of foreign functions to assert that the target OS
424 /// is `target_os`. It panics showing a message with the `name` of the foreign function
425 /// if this is not the case.
426 fn assert_target_os(&self, target_os: &str, name: &str) {
428 self.eval_context_ref().tcx.sess.target.os,
430 "`{}` is only available on the `{}` target OS",
436 /// Get last error variable as a place, lazily allocating thread-local storage for it if
438 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
439 let this = self.eval_context_mut();
440 if let Some(errno_place) = this.active_thread_ref().last_error {
443 // Allocate new place, set initial value to 0.
444 let errno_layout = this.machine.layouts.u32;
445 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
446 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
447 this.active_thread_mut().last_error = Some(errno_place);
452 /// Sets the last error variable.
453 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
454 let this = self.eval_context_mut();
455 let errno_place = this.last_error_place()?;
456 this.write_scalar(scalar, &errno_place.into())
459 /// Gets the last error variable.
460 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
461 let this = self.eval_context_mut();
462 let errno_place = this.last_error_place()?;
463 this.read_scalar(&errno_place.into())?.check_init()
466 /// Sets the last OS error using a `std::io::ErrorKind`. This function tries to produce the most
467 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
468 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
469 use std::io::ErrorKind::*;
470 let this = self.eval_context_mut();
471 let target = &this.tcx.sess.target;
472 let target_os = &target.os;
473 let last_error = if target.families.contains(&"unix".to_owned()) {
474 this.eval_libc(match err_kind {
475 ConnectionRefused => "ECONNREFUSED",
476 ConnectionReset => "ECONNRESET",
477 PermissionDenied => "EPERM",
478 BrokenPipe => "EPIPE",
479 NotConnected => "ENOTCONN",
480 ConnectionAborted => "ECONNABORTED",
481 AddrNotAvailable => "EADDRNOTAVAIL",
482 AddrInUse => "EADDRINUSE",
483 NotFound => "ENOENT",
484 Interrupted => "EINTR",
485 InvalidInput => "EINVAL",
486 TimedOut => "ETIMEDOUT",
487 AlreadyExists => "EEXIST",
488 WouldBlock => "EWOULDBLOCK",
491 "io error {:?} cannot be translated into a raw os error",
496 } else if target.families.contains(&"windows".to_owned()) {
497 // FIXME: we have to finish implementing the Windows equivalent of this.
501 NotFound => "ERROR_FILE_NOT_FOUND",
502 PermissionDenied => "ERROR_ACCESS_DENIED",
505 "io error {:?} cannot be translated into a raw os error",
512 "setting the last OS error from an io::Error is unsupported for {}.",
516 this.set_last_error(last_error)
519 /// Helper function that consumes an `std::io::Result<T>` and returns an
520 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
521 /// `Ok(-1)` and sets the last OS error accordingly.
523 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
524 /// functions return different integer types (like `read`, that returns an `i64`).
525 fn try_unwrap_io_result<T: From<i32>>(
527 result: std::io::Result<T>,
528 ) -> InterpResult<'tcx, T> {
532 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
538 fn read_scalar_at_offset(
540 op: &OpTy<'tcx, Tag>,
542 layout: TyAndLayout<'tcx>,
543 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
544 let this = self.eval_context_ref();
545 let op_place = this.deref_operand(op)?;
546 let offset = Size::from_bytes(offset);
547 // Ensure that the following read at an offset is within bounds
548 assert!(op_place.layout.size >= offset + layout.size);
549 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
550 this.read_scalar(&value_place.into())
553 fn write_scalar_at_offset(
555 op: &OpTy<'tcx, Tag>,
557 value: impl Into<ScalarMaybeUninit<Tag>>,
558 layout: TyAndLayout<'tcx>,
559 ) -> InterpResult<'tcx, ()> {
560 let this = self.eval_context_mut();
561 let op_place = this.deref_operand(op)?;
562 let offset = Size::from_bytes(offset);
563 // Ensure that the following read at an offset is within bounds
564 assert!(op_place.layout.size >= offset + layout.size);
565 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
566 this.write_scalar(value, &value_place.into())
569 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
570 /// if the value in the `timespec` struct is invalid. Some libc functions will return
571 /// `EINVAL` in this case.
572 fn read_timespec(&mut self, tp: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx, Option<Duration>> {
573 let this = self.eval_context_mut();
574 let seconds_place = this.mplace_field(&tp, 0)?;
575 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
576 let seconds = seconds_scalar.to_machine_isize(this)?;
577 let nanoseconds_place = this.mplace_field(&tp, 1)?;
578 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
579 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
582 // tv_sec must be non-negative.
583 let seconds: u64 = seconds.try_into().ok()?;
584 // tv_nsec must be non-negative.
585 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
586 if nanoseconds >= 1_000_000_000 {
587 // tv_nsec must not be greater than 999,999,999.
590 Duration::new(seconds, nanoseconds)
594 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, &'a [u8]>
599 let this = self.eval_context_ref();
600 let size1 = Size::from_bytes(1);
602 // Step 1: determine the length.
603 let mut len = Size::ZERO;
605 // FIXME: We are re-getting the allocation each time around the loop.
606 // Would be nice if we could somehow "extend" an existing AllocRange.
607 let alloc = this.memory.get(ptr.offset(len, this)?.into(), size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
608 let byte = alloc.read_scalar(alloc_range(Size::ZERO, size1))?.to_u8()?;
616 // Step 2: get the bytes.
617 this.memory.read_bytes(ptr.into(), len)
620 fn read_wide_str(&self, mut ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, Vec<u16>> {
621 let this = self.eval_context_ref();
622 let size2 = Size::from_bytes(2);
623 let align2 = Align::from_bytes(2).unwrap();
625 let mut wchars = Vec::new();
627 // FIXME: We are re-getting the allocation each time around the loop.
628 // Would be nice if we could somehow "extend" an existing AllocRange.
629 let alloc = this.memory.get(ptr.into(), size2, align2)?.unwrap(); // not a ZST, so we will get a result
630 let wchar = alloc.read_scalar(alloc_range(Size::ZERO, size2))?.to_u16()?;
635 ptr = ptr.offset(size2, this)?;
642 /// Check that the ABI is what we expect.
643 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
644 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
646 "calling a function with ABI {} using caller ABI {}",
654 fn frame_in_std(&self) -> bool {
655 let this = self.eval_context_ref();
656 this.tcx.lang_items().start_fn().map_or(false, |start_fn| {
657 this.tcx.def_path(this.frame().instance.def_id()).krate
658 == this.tcx.def_path(start_fn).krate
662 /// Handler that should be called when unsupported functionality is encountered.
663 /// This function will either panic within the context of the emulated application
664 /// or return an error in the Miri process context
666 /// Return value of `Ok(bool)` indicates whether execution should continue.
667 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
668 let this = self.eval_context_mut();
669 if this.machine.panic_on_unsupported {
670 // message is slightly different here to make automated analysis easier
671 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
672 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
675 throw_unsup_format!("{}", error_msg.as_ref());
679 fn check_abi_and_shim_symbol_clash(
684 ) -> InterpResult<'tcx, ()> {
685 self.check_abi(abi, exp_abi)?;
686 if let Some(body) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
687 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
689 span: body.span.data(),
695 fn check_shim<'a, const N: usize>(
700 args: &'a [OpTy<'tcx, Tag>],
701 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
703 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
705 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
706 check_arg_count(args)
709 /// Mark a machine allocation that was just created as immutable.
710 fn mark_immutable(&mut self, mplace: &MemPlace<Tag>) {
711 let this = self.eval_context_mut();
713 .mark_immutable(mplace.ptr.into_pointer_or_addr().unwrap().provenance.alloc_id)
718 /// Check that the number of args is what we expect.
719 pub fn check_arg_count<'a, 'tcx, const N: usize>(
720 args: &'a [OpTy<'tcx, Tag>],
721 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
723 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
725 if let Ok(ops) = args.try_into() {
728 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
731 pub fn isolation_abort_error(name: &str) -> InterpResult<'static> {
732 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
733 "{} not available when isolation is enabled",
738 pub fn immty_from_int_checked<'tcx>(
739 int: impl Into<i128>,
740 layout: TyAndLayout<'tcx>,
741 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
742 let int = int.into();
743 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
744 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
748 pub fn immty_from_uint_checked<'tcx>(
749 int: impl Into<u128>,
750 layout: TyAndLayout<'tcx>,
751 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
752 let int = int.into();
753 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
754 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())