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::{def_id::CrateNum, 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(&self, path: &[&str]) -> InterpResult<'tcx, Scalar<Tag>> {
61 let this = self.eval_context_ref();
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(&self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
71 self.eval_path_scalar(&["libc", name])
74 /// Helper function to get a `libc` constant as an `i32`.
75 fn eval_libc_i32(&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(&self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
82 self.eval_context_ref().eval_path_scalar(&["std", "sys", "windows", module, name])
85 /// Helper function to get a `windows` constant as a `u64`.
86 fn eval_windows_u64(&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(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
93 let this = self.eval_context_ref();
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(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
100 let this = self.eval_context_ref();
102 .resolve_path(&["std", "sys", "windows", "c", name])
103 .ty(*this.tcx, ty::ParamEnv::reveal_all());
107 /// Project to the given *named* field of the mplace (which must be a struct or union type).
108 fn mplace_field_named(
110 mplace: &MPlaceTy<'tcx, Tag>,
112 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
113 let this = self.eval_context_ref();
114 let adt = mplace.layout.ty.ty_adt_def().unwrap();
115 for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
116 if field.name.as_str() == name {
117 return this.mplace_field(mplace, idx);
120 bug!("No field named {} in type {}", name, mplace.layout.ty);
123 /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
124 /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
125 /// this method is fine for almost all integer types.
126 fn write_int(&mut self, i: impl Into<i128>, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
127 assert!(dest.layout.abi.is_scalar(), "write_int on non-scalar type {}", dest.layout.ty);
128 let val = if dest.layout.abi.is_signed() {
129 Scalar::from_int(i, dest.layout.size)
131 Scalar::from_uint(u64::try_from(i.into()).unwrap(), dest.layout.size)
133 self.eval_context_mut().write_scalar(val, dest)
136 /// Write the first N fields of the given place.
140 dest: &MPlaceTy<'tcx, Tag>,
141 ) -> InterpResult<'tcx> {
142 let this = self.eval_context_mut();
143 for (idx, &val) in values.iter().enumerate() {
144 let field = this.mplace_field(dest, idx)?;
145 this.write_int(val, &field.into())?;
150 /// Write the given fields of the given place.
151 fn write_int_fields_named(
153 values: &[(&str, i128)],
154 dest: &MPlaceTy<'tcx, Tag>,
155 ) -> InterpResult<'tcx> {
156 let this = self.eval_context_mut();
157 for &(name, val) in values.iter() {
158 let field = this.mplace_field_named(dest, name)?;
159 this.write_int(val, &field.into())?;
164 /// Write a 0 of the appropriate size to `dest`.
165 fn write_null(&mut self, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
166 self.write_int(0, dest)
169 /// Test if this pointer equals 0.
170 fn ptr_is_null(&self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, bool> {
171 let this = self.eval_context_ref();
172 let null = Scalar::null_ptr(this);
173 this.ptr_eq(Scalar::from_maybe_pointer(ptr, this), null)
176 /// Get the `Place` for a local
177 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
178 let this = self.eval_context_mut();
179 let place = mir::Place { local: local, projection: List::empty() };
180 this.eval_place(place)
183 /// Generate some random bytes, and write them to `dest`.
184 fn gen_random(&mut self, ptr: Pointer<Option<Tag>>, len: u64) -> InterpResult<'tcx> {
185 // Some programs pass in a null pointer and a length of 0
186 // to their platform's random-generation function (e.g. getrandom())
187 // on Linux. For compatibility with these programs, we don't perform
188 // any additional checks - it's okay if the pointer is invalid,
189 // since we wouldn't actually be writing to it.
193 let this = self.eval_context_mut();
195 let mut data = vec![0; usize::try_from(len).unwrap()];
197 if this.machine.communicate() {
198 // Fill the buffer using the host's rng.
199 getrandom::getrandom(&mut data)
200 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
202 let rng = this.machine.rng.get_mut();
203 rng.fill_bytes(&mut data);
206 this.write_bytes_ptr(ptr, data.iter().copied())
209 /// Call a function: Push the stack frame and pass the arguments.
210 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
213 f: ty::Instance<'tcx>,
215 args: &[Immediate<Tag>],
216 dest: Option<&PlaceTy<'tcx, Tag>>,
217 stack_pop: StackPopCleanup,
218 ) -> InterpResult<'tcx> {
219 let this = self.eval_context_mut();
220 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
221 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
222 if this.machine.enforce_abi && callee_abi != caller_abi {
224 "calling a function with ABI {} using caller ABI {}",
231 let mir = &*this.load_mir(f.def, None)?;
232 this.push_stack_frame(f, mir, dest, stack_pop)?;
234 // Initialize arguments.
235 let mut callee_args = this.frame().body.args_iter();
237 let callee_arg = this.local_place(
240 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
242 this.write_immediate(*arg, &callee_arg)?;
244 if callee_args.next().is_some() {
245 throw_ub_format!("callee has more arguments than expected");
251 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
252 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
253 /// The range is relative to `place`.
255 /// Assumes that the `place` has a proper pointer in it.
256 fn visit_freeze_sensitive(
258 place: &MPlaceTy<'tcx, Tag>,
260 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
261 ) -> InterpResult<'tcx> {
262 let this = self.eval_context_ref();
263 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
266 this.size_and_align_of_mplace(place)?
267 .map(|(size, _)| size)
268 .unwrap_or_else(|| place.layout.size)
270 // Store how far we proceeded into the place so far. Everything to the left of
271 // this offset has already been handled, in the sense that the frozen parts
272 // have had `action` called on them.
273 let ptr = place.ptr.into_pointer_or_addr().unwrap();
274 let start_offset = ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
275 let mut cur_offset = start_offset;
276 // Called when we detected an `UnsafeCell` at the given offset and size.
277 // Calls `action` and advances `cur_ptr`.
278 let mut unsafe_cell_action = |unsafe_cell_ptr: Pointer<Option<Tag>>,
279 unsafe_cell_size: Size| {
280 let unsafe_cell_ptr = unsafe_cell_ptr.into_pointer_or_addr().unwrap();
281 debug_assert_eq!(unsafe_cell_ptr.provenance, ptr.provenance);
282 // We assume that we are given the fields in increasing offset order,
283 // and nothing else changes.
284 let unsafe_cell_offset = unsafe_cell_ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
285 assert!(unsafe_cell_offset >= cur_offset);
286 let frozen_size = unsafe_cell_offset - cur_offset;
287 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
288 if frozen_size != Size::ZERO {
289 action(alloc_range(cur_offset - start_offset, frozen_size), /*frozen*/ true)?;
291 cur_offset += frozen_size;
292 // This `UnsafeCell` is NOT frozen.
293 if unsafe_cell_size != Size::ZERO {
295 alloc_range(cur_offset - start_offset, unsafe_cell_size),
299 cur_offset += unsafe_cell_size;
305 let mut visitor = UnsafeCellVisitor {
307 unsafe_cell_action: |place| {
308 trace!("unsafe_cell_action on {:?}", place.ptr);
309 // We need a size to go on.
310 let unsafe_cell_size = this
311 .size_and_align_of_mplace(&place)?
312 .map(|(size, _)| size)
313 // for extern types, just cover what we can
314 .unwrap_or_else(|| place.layout.size);
315 // Now handle this `UnsafeCell`, unless it is empty.
316 if unsafe_cell_size != Size::ZERO {
317 unsafe_cell_action(place.ptr, unsafe_cell_size)
323 visitor.visit_value(place)?;
325 // The part between the end_ptr and the end of the place is also frozen.
326 // So pretend there is a 0-sized `UnsafeCell` at the end.
327 unsafe_cell_action(place.ptr.wrapping_offset(size, this), Size::ZERO)?;
331 /// Visiting the memory covered by a `MemPlace`, being aware of
332 /// whether we are inside an `UnsafeCell` or not.
333 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
335 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
337 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
338 unsafe_cell_action: F,
341 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
342 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
344 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
346 type V = MPlaceTy<'tcx, Tag>;
349 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
353 // Hook to detect `UnsafeCell`.
354 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
355 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
356 let is_unsafe_cell = match v.layout.ty.kind() {
358 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
362 // We do not have to recurse further, this is an `UnsafeCell`.
363 (self.unsafe_cell_action)(v)
364 } else if self.ecx.type_is_freeze(v.layout.ty) {
365 // This is `Freeze`, there cannot be an `UnsafeCell`
367 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
368 // A (non-frozen) union. We fall back to whatever the type says.
369 (self.unsafe_cell_action)(v)
371 // We want to not actually read from memory for this visit. So, before
372 // walking this value, we have to make sure it is not a
373 // `Variants::Multiple`.
374 match v.layout.variants {
375 Variants::Multiple { .. } => {
376 // A multi-variant enum, or generator, or so.
377 // Treat this like a union: without reading from memory,
378 // we cannot determine the variant we are in. Reading from
379 // memory would be subject to Stacked Borrows rules, leading
380 // to all sorts of "funny" recursion.
381 // We only end up here if the type is *not* freeze, so we just call the
382 // `UnsafeCell` action.
383 (self.unsafe_cell_action)(v)
385 Variants::Single { .. } => {
386 // Proceed further, try to find where exactly that `UnsafeCell`
394 // Make sure we visit aggregrates in increasing offset order.
397 place: &MPlaceTy<'tcx, Tag>,
398 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
399 ) -> InterpResult<'tcx> {
400 match place.layout.fields {
401 FieldsShape::Array { .. } => {
402 // For the array layout, we know the iterator will yield sorted elements so
403 // we can avoid the allocation.
404 self.walk_aggregate(place, fields)
406 FieldsShape::Arbitrary { .. } => {
407 // Gather the subplaces and sort them before visiting.
409 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
410 // we just compare offsets, the abs. value never matters
411 places.sort_by_key(|place| {
412 place.ptr.into_pointer_or_addr().unwrap().into_parts().1 as Size
414 self.walk_aggregate(place, places.into_iter().map(Ok))
416 FieldsShape::Union { .. } | FieldsShape::Primitive => {
418 bug!("unions/primitives are not aggregates we should ever visit")
425 _v: &MPlaceTy<'tcx, Tag>,
426 _fields: NonZeroUsize,
427 ) -> InterpResult<'tcx> {
428 bug!("we should have already handled unions in `visit_value`")
433 /// Helper function used inside the shims of foreign functions to check that isolation is
434 /// disabled. It returns an error using the `name` of the foreign function if this is not the
436 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
437 if !self.eval_context_ref().machine.communicate() {
438 self.reject_in_isolation(name, RejectOpWith::Abort)?;
443 /// Helper function used inside the shims of foreign functions which reject the op
444 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
445 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
446 let this = self.eval_context_ref();
448 RejectOpWith::Abort => isolation_abort_error(op_name),
449 RejectOpWith::WarningWithoutBacktrace => {
452 .warn(&format!("{} was made to return an error due to isolation", op_name));
455 RejectOpWith::Warning => {
456 register_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
459 RejectOpWith::NoWarning => Ok(()), // no warning
463 /// Helper function used inside the shims of foreign functions to assert that the target OS
464 /// is `target_os`. It panics showing a message with the `name` of the foreign function
465 /// if this is not the case.
466 fn assert_target_os(&self, target_os: &str, name: &str) {
468 self.eval_context_ref().tcx.sess.target.os,
470 "`{}` is only available on the `{}` target OS",
476 /// Get last error variable as a place, lazily allocating thread-local storage for it if
478 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
479 let this = self.eval_context_mut();
480 if let Some(errno_place) = this.active_thread_ref().last_error {
483 // Allocate new place, set initial value to 0.
484 let errno_layout = this.machine.layouts.u32;
485 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
486 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
487 this.active_thread_mut().last_error = Some(errno_place);
492 /// Sets the last error variable.
493 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
494 let this = self.eval_context_mut();
495 let errno_place = this.last_error_place()?;
496 this.write_scalar(scalar, &errno_place.into())
499 /// Gets the last error variable.
500 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
501 let this = self.eval_context_mut();
502 let errno_place = this.last_error_place()?;
503 this.read_scalar(&errno_place.into())?.check_init()
506 /// Sets the last OS error using a `std::io::ErrorKind`. This function tries to produce the most
507 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
508 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
509 use std::io::ErrorKind::*;
510 let this = self.eval_context_mut();
511 let target = &this.tcx.sess.target;
512 let target_os = &target.os;
513 let last_error = if target.families.iter().any(|f| f == "unix") {
514 this.eval_libc(match err_kind {
515 ConnectionRefused => "ECONNREFUSED",
516 ConnectionReset => "ECONNRESET",
517 PermissionDenied => "EPERM",
518 BrokenPipe => "EPIPE",
519 NotConnected => "ENOTCONN",
520 ConnectionAborted => "ECONNABORTED",
521 AddrNotAvailable => "EADDRNOTAVAIL",
522 AddrInUse => "EADDRINUSE",
523 NotFound => "ENOENT",
524 Interrupted => "EINTR",
525 InvalidInput => "EINVAL",
526 TimedOut => "ETIMEDOUT",
527 AlreadyExists => "EEXIST",
528 WouldBlock => "EWOULDBLOCK",
529 DirectoryNotEmpty => "ENOTEMPTY",
532 "io error {:?} cannot be translated into a raw os error",
537 } else if target.families.iter().any(|f| f == "windows") {
538 // FIXME: we have to finish implementing the Windows equivalent of this.
542 NotFound => "ERROR_FILE_NOT_FOUND",
543 PermissionDenied => "ERROR_ACCESS_DENIED",
546 "io error {:?} cannot be translated into a raw os error",
553 "setting the last OS error from an io::Error is unsupported for {}.",
557 this.set_last_error(last_error)
560 /// Helper function that consumes an `std::io::Result<T>` and returns an
561 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
562 /// `Ok(-1)` and sets the last OS error accordingly.
564 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
565 /// functions return different integer types (like `read`, that returns an `i64`).
566 fn try_unwrap_io_result<T: From<i32>>(
568 result: std::io::Result<T>,
569 ) -> InterpResult<'tcx, T> {
573 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
579 fn read_scalar_at_offset(
581 op: &OpTy<'tcx, Tag>,
583 layout: TyAndLayout<'tcx>,
584 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
585 let this = self.eval_context_ref();
586 let op_place = this.deref_operand(op)?;
587 let offset = Size::from_bytes(offset);
588 // Ensure that the following read at an offset is within bounds
589 assert!(op_place.layout.size >= offset + layout.size);
590 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
591 this.read_scalar(&value_place.into())
594 fn write_scalar_at_offset(
596 op: &OpTy<'tcx, Tag>,
598 value: impl Into<ScalarMaybeUninit<Tag>>,
599 layout: TyAndLayout<'tcx>,
600 ) -> InterpResult<'tcx, ()> {
601 let this = self.eval_context_mut();
602 let op_place = this.deref_operand(op)?;
603 let offset = Size::from_bytes(offset);
604 // Ensure that the following read at an offset is within bounds
605 assert!(op_place.layout.size >= offset + layout.size);
606 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
607 this.write_scalar(value, &value_place.into())
610 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
611 /// if the value in the `timespec` struct is invalid. Some libc functions will return
612 /// `EINVAL` in this case.
613 fn read_timespec(&mut self, tp: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx, Option<Duration>> {
614 let this = self.eval_context_mut();
615 let seconds_place = this.mplace_field(&tp, 0)?;
616 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
617 let seconds = seconds_scalar.to_machine_isize(this)?;
618 let nanoseconds_place = this.mplace_field(&tp, 1)?;
619 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
620 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
623 // tv_sec must be non-negative.
624 let seconds: u64 = seconds.try_into().ok()?;
625 // tv_nsec must be non-negative.
626 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
627 if nanoseconds >= 1_000_000_000 {
628 // tv_nsec must not be greater than 999,999,999.
631 Duration::new(seconds, nanoseconds)
635 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, &'a [u8]>
640 let this = self.eval_context_ref();
641 let size1 = Size::from_bytes(1);
643 // Step 1: determine the length.
644 let mut len = Size::ZERO;
646 // FIXME: We are re-getting the allocation each time around the loop.
647 // Would be nice if we could somehow "extend" an existing AllocRange.
649 this.get_ptr_alloc(ptr.offset(len, this)?.into(), size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
650 let byte = alloc.read_scalar(alloc_range(Size::ZERO, size1))?.to_u8()?;
658 // Step 2: get the bytes.
659 this.read_bytes_ptr(ptr.into(), len)
662 fn read_wide_str(&self, mut ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, Vec<u16>> {
663 let this = self.eval_context_ref();
664 let size2 = Size::from_bytes(2);
665 let align2 = Align::from_bytes(2).unwrap();
667 let mut wchars = Vec::new();
669 // FIXME: We are re-getting the allocation each time around the loop.
670 // Would be nice if we could somehow "extend" an existing AllocRange.
671 let alloc = this.get_ptr_alloc(ptr.into(), size2, align2)?.unwrap(); // not a ZST, so we will get a result
672 let wchar = alloc.read_scalar(alloc_range(Size::ZERO, size2))?.to_u16()?;
677 ptr = ptr.offset(size2, this)?;
684 /// Check that the ABI is what we expect.
685 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
686 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
688 "calling a function with ABI {} using caller ABI {}",
696 fn frame_in_std(&self) -> bool {
697 let this = self.eval_context_ref();
698 this.tcx.lang_items().start_fn().map_or(false, |start_fn| {
699 this.tcx.def_path(this.frame().instance.def_id()).krate
700 == this.tcx.def_path(start_fn).krate
704 /// Handler that should be called when unsupported functionality is encountered.
705 /// This function will either panic within the context of the emulated application
706 /// or return an error in the Miri process context
708 /// Return value of `Ok(bool)` indicates whether execution should continue.
709 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
710 let this = self.eval_context_mut();
711 if this.machine.panic_on_unsupported {
712 // message is slightly different here to make automated analysis easier
713 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
714 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
717 throw_unsup_format!("{}", error_msg.as_ref());
721 fn check_abi_and_shim_symbol_clash(
726 ) -> InterpResult<'tcx, ()> {
727 self.check_abi(abi, exp_abi)?;
728 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
729 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
731 span: body.span.data(),
737 fn check_shim<'a, const N: usize>(
742 args: &'a [OpTy<'tcx, Tag>],
743 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
745 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
747 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
748 check_arg_count(args)
751 /// Mark a machine allocation that was just created as immutable.
752 fn mark_immutable(&mut self, mplace: &MemPlace<Tag>) {
753 let this = self.eval_context_mut();
754 this.alloc_mark_immutable(mplace.ptr.into_pointer_or_addr().unwrap().provenance.alloc_id)
759 /// Check that the number of args is what we expect.
760 pub fn check_arg_count<'a, 'tcx, const N: usize>(
761 args: &'a [OpTy<'tcx, Tag>],
762 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
764 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
766 if let Ok(ops) = args.try_into() {
769 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
772 pub fn isolation_abort_error(name: &str) -> InterpResult<'static> {
773 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
774 "{} not available when isolation is enabled",
779 /// Retrieve the list of local crates that should have been passed by cargo-miri in
780 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
781 pub fn get_local_crates(tcx: &TyCtxt<'_>) -> Vec<CrateNum> {
782 // Convert the local crate names from the passed-in config into CrateNums so that they can
783 // be looked up quickly during execution
784 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
785 .map(|crates| crates.split(",").map(|krate| krate.to_string()).collect::<Vec<_>>())
786 .unwrap_or_default();
787 let mut local_crates = Vec::new();
788 for &crate_num in tcx.crates(()) {
789 let name = tcx.crate_name(crate_num);
790 let name = name.as_str();
791 if local_crate_names.iter().any(|local_name| local_name == name) {
792 local_crates.push(crate_num);