2 use std::num::NonZeroUsize;
3 use std::time::Duration;
7 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
9 use rustc_middle::ty::{
11 layout::{LayoutOf, TyAndLayout},
14 use rustc_span::{def_id::CrateNum, Symbol};
15 use rustc_target::abi::{Align, FieldsShape, Size, Variants};
16 use rustc_target::spec::abi::Abi;
22 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
24 /// Gets an instance for a path.
25 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
26 tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == path[0]).and_then(
28 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
29 let mut items = tcx.module_children(krate);
30 let mut path_it = path.iter().skip(1).peekable();
32 while let Some(segment) = path_it.next() {
33 for item in mem::replace(&mut items, Default::default()).iter() {
34 if item.ident.name.as_str() == *segment {
35 if path_it.peek().is_none() {
36 return Some(item.res.def_id());
39 items = tcx.module_children(item.res.def_id());
49 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
50 /// Gets an instance for a path.
51 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
52 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)
53 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path));
54 ty::Instance::mono(self.eval_context_ref().tcx.tcx, did)
57 /// Evaluates the scalar at the specified path. Returns Some(val)
58 /// if the path could be resolved, and None otherwise
59 fn eval_path_scalar(&self, path: &[&str]) -> InterpResult<'tcx, Scalar<Tag>> {
60 let this = self.eval_context_ref();
61 let instance = this.resolve_path(path);
62 let cid = GlobalId { instance, promoted: None };
63 let const_val = this.eval_to_allocation(cid)?;
64 let const_val = this.read_scalar(&const_val.into())?;
65 return Ok(const_val.check_init()?);
68 /// Helper function to get a `libc` constant as a `Scalar`.
69 fn eval_libc(&self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
70 self.eval_path_scalar(&["libc", name])
73 /// Helper function to get a `libc` constant as an `i32`.
74 fn eval_libc_i32(&self, name: &str) -> InterpResult<'tcx, i32> {
75 // TODO: Cache the result.
76 self.eval_libc(name)?.to_i32()
79 /// Helper function to get a `windows` constant as a `Scalar`.
80 fn eval_windows(&self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
81 self.eval_context_ref().eval_path_scalar(&["std", "sys", "windows", module, name])
84 /// Helper function to get a `windows` constant as a `u64`.
85 fn eval_windows_u64(&self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
86 // TODO: Cache the result.
87 self.eval_windows(module, name)?.to_u64()
90 /// Helper function to get the `TyAndLayout` of a `libc` type
91 fn libc_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
92 let this = self.eval_context_ref();
93 let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
97 /// Helper function to get the `TyAndLayout` of a `windows` type
98 fn windows_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
99 let this = self.eval_context_ref();
101 .resolve_path(&["std", "sys", "windows", "c", name])
102 .ty(*this.tcx, ty::ParamEnv::reveal_all());
106 /// Project to the given *named* field of the mplace (which must be a struct or union type).
107 fn mplace_field_named(
109 mplace: &MPlaceTy<'tcx, Tag>,
111 ) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
112 let this = self.eval_context_ref();
113 let adt = mplace.layout.ty.ty_adt_def().unwrap();
114 for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
115 if field.name.as_str() == name {
116 return this.mplace_field(mplace, idx);
119 bug!("No field named {} in type {}", name, mplace.layout.ty);
122 /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
123 /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
124 /// this method is fine for almost all integer types.
125 fn write_int(&mut self, i: impl Into<i128>, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
126 assert!(dest.layout.abi.is_scalar(), "write_int on non-scalar type {}", dest.layout.ty);
127 let val = if dest.layout.abi.is_signed() {
128 Scalar::from_int(i, dest.layout.size)
130 Scalar::from_uint(u64::try_from(i.into()).unwrap(), dest.layout.size)
132 self.eval_context_mut().write_scalar(val, dest)
135 /// Write the first N fields of the given place.
139 dest: &MPlaceTy<'tcx, Tag>,
140 ) -> InterpResult<'tcx> {
141 let this = self.eval_context_mut();
142 for (idx, &val) in values.iter().enumerate() {
143 let field = this.mplace_field(dest, idx)?;
144 this.write_int(val, &field.into())?;
149 /// Write the given fields of the given place.
150 fn write_int_fields_named(
152 values: &[(&str, i128)],
153 dest: &MPlaceTy<'tcx, Tag>,
154 ) -> InterpResult<'tcx> {
155 let this = self.eval_context_mut();
156 for &(name, val) in values.iter() {
157 let field = this.mplace_field_named(dest, name)?;
158 this.write_int(val, &field.into())?;
163 /// Write a 0 of the appropriate size to `dest`.
164 fn write_null(&mut self, dest: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
165 self.write_int(0, dest)
168 /// Test if this pointer equals 0.
169 fn ptr_is_null(&self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, bool> {
170 let this = self.eval_context_ref();
171 let null = Scalar::null_ptr(this);
172 this.ptr_eq(Scalar::from_maybe_pointer(ptr, this), null)
175 /// Get the `Place` for a local
176 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
177 let this = self.eval_context_mut();
178 let place = mir::Place { local: local, projection: List::empty() };
179 this.eval_place(place)
182 /// Generate some random bytes, and write them to `dest`.
183 fn gen_random(&mut self, ptr: Pointer<Option<Tag>>, len: u64) -> InterpResult<'tcx> {
184 // Some programs pass in a null pointer and a length of 0
185 // to their platform's random-generation function (e.g. getrandom())
186 // on Linux. For compatibility with these programs, we don't perform
187 // any additional checks - it's okay if the pointer is invalid,
188 // since we wouldn't actually be writing to it.
192 let this = self.eval_context_mut();
194 let mut data = vec![0; usize::try_from(len).unwrap()];
196 if this.machine.communicate() {
197 // Fill the buffer using the host's rng.
198 getrandom::getrandom(&mut data)
199 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
201 let rng = this.machine.rng.get_mut();
202 rng.fill_bytes(&mut data);
205 this.write_bytes_ptr(ptr, data.iter().copied())
208 /// Call a function: Push the stack frame and pass the arguments.
209 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
212 f: ty::Instance<'tcx>,
214 args: &[Immediate<Tag>],
215 dest: Option<&PlaceTy<'tcx, Tag>>,
216 stack_pop: StackPopCleanup,
217 ) -> InterpResult<'tcx> {
218 let this = self.eval_context_mut();
219 let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
220 let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
221 if this.machine.enforce_abi && callee_abi != caller_abi {
223 "calling a function with ABI {} using caller ABI {}",
230 let mir = &*this.load_mir(f.def, None)?;
231 this.push_stack_frame(f, mir, dest, stack_pop)?;
233 // Initialize arguments.
234 let mut callee_args = this.frame().body.args_iter();
236 let callee_arg = this.local_place(
239 .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
241 this.write_immediate(*arg, &callee_arg)?;
243 if callee_args.next().is_some() {
244 throw_ub_format!("callee has more arguments than expected");
250 /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
251 /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
252 /// The range is relative to `place`.
254 /// Assumes that the `place` has a proper pointer in it.
255 fn visit_freeze_sensitive(
257 place: &MPlaceTy<'tcx, Tag>,
259 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
260 ) -> InterpResult<'tcx> {
261 let this = self.eval_context_ref();
262 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
265 this.size_and_align_of_mplace(place)?
266 .map(|(size, _)| size)
267 .unwrap_or_else(|| place.layout.size)
269 // Store how far we proceeded into the place so far. Everything to the left of
270 // this offset has already been handled, in the sense that the frozen parts
271 // have had `action` called on them.
272 let ptr = place.ptr.into_pointer_or_addr().unwrap();
273 let start_offset = ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
274 let mut cur_offset = start_offset;
275 // Called when we detected an `UnsafeCell` at the given offset and size.
276 // Calls `action` and advances `cur_ptr`.
277 let mut unsafe_cell_action = |unsafe_cell_ptr: Pointer<Option<Tag>>,
278 unsafe_cell_size: Size| {
279 let unsafe_cell_ptr = unsafe_cell_ptr.into_pointer_or_addr().unwrap();
280 debug_assert_eq!(unsafe_cell_ptr.provenance, ptr.provenance);
281 // We assume that we are given the fields in increasing offset order,
282 // and nothing else changes.
283 let unsafe_cell_offset = unsafe_cell_ptr.into_parts().1 as Size; // we just compare offsets, the abs. value never matters
284 assert!(unsafe_cell_offset >= cur_offset);
285 let frozen_size = unsafe_cell_offset - cur_offset;
286 // Everything between the cur_ptr and this `UnsafeCell` is frozen.
287 if frozen_size != Size::ZERO {
288 action(alloc_range(cur_offset - start_offset, frozen_size), /*frozen*/ true)?;
290 cur_offset += frozen_size;
291 // This `UnsafeCell` is NOT frozen.
292 if unsafe_cell_size != Size::ZERO {
294 alloc_range(cur_offset - start_offset, unsafe_cell_size),
298 cur_offset += unsafe_cell_size;
304 let mut visitor = UnsafeCellVisitor {
306 unsafe_cell_action: |place| {
307 trace!("unsafe_cell_action on {:?}", place.ptr);
308 // We need a size to go on.
309 let unsafe_cell_size = this
310 .size_and_align_of_mplace(&place)?
311 .map(|(size, _)| size)
312 // for extern types, just cover what we can
313 .unwrap_or_else(|| place.layout.size);
314 // Now handle this `UnsafeCell`, unless it is empty.
315 if unsafe_cell_size != Size::ZERO {
316 unsafe_cell_action(place.ptr, unsafe_cell_size)
322 visitor.visit_value(place)?;
324 // The part between the end_ptr and the end of the place is also frozen.
325 // So pretend there is a 0-sized `UnsafeCell` at the end.
326 unsafe_cell_action(place.ptr.wrapping_offset(size, this), Size::ZERO)?;
330 /// Visiting the memory covered by a `MemPlace`, being aware of
331 /// whether we are inside an `UnsafeCell` or not.
332 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
334 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
336 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
337 unsafe_cell_action: F,
340 impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
341 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
343 F: FnMut(&MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
345 type V = MPlaceTy<'tcx, Tag>;
348 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
352 // Hook to detect `UnsafeCell`.
353 fn visit_value(&mut self, v: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
354 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
355 let is_unsafe_cell = match v.layout.ty.kind() {
357 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
361 // We do not have to recurse further, this is an `UnsafeCell`.
362 (self.unsafe_cell_action)(v)
363 } else if self.ecx.type_is_freeze(v.layout.ty) {
364 // This is `Freeze`, there cannot be an `UnsafeCell`
366 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
367 // A (non-frozen) union. We fall back to whatever the type says.
368 (self.unsafe_cell_action)(v)
370 // We want to not actually read from memory for this visit. So, before
371 // walking this value, we have to make sure it is not a
372 // `Variants::Multiple`.
373 match v.layout.variants {
374 Variants::Multiple { .. } => {
375 // A multi-variant enum, or generator, or so.
376 // Treat this like a union: without reading from memory,
377 // we cannot determine the variant we are in. Reading from
378 // memory would be subject to Stacked Borrows rules, leading
379 // to all sorts of "funny" recursion.
380 // We only end up here if the type is *not* freeze, so we just call the
381 // `UnsafeCell` action.
382 (self.unsafe_cell_action)(v)
384 Variants::Single { .. } => {
385 // Proceed further, try to find where exactly that `UnsafeCell`
393 // Make sure we visit aggregrates in increasing offset order.
396 place: &MPlaceTy<'tcx, Tag>,
397 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
398 ) -> InterpResult<'tcx> {
399 match place.layout.fields {
400 FieldsShape::Array { .. } => {
401 // For the array layout, we know the iterator will yield sorted elements so
402 // we can avoid the allocation.
403 self.walk_aggregate(place, fields)
405 FieldsShape::Arbitrary { .. } => {
406 // Gather the subplaces and sort them before visiting.
408 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
409 // we just compare offsets, the abs. value never matters
410 places.sort_by_key(|place| {
411 place.ptr.into_pointer_or_addr().unwrap().into_parts().1 as Size
413 self.walk_aggregate(place, places.into_iter().map(Ok))
415 FieldsShape::Union { .. } | FieldsShape::Primitive => {
417 bug!("unions/primitives are not aggregates we should ever visit")
424 _v: &MPlaceTy<'tcx, Tag>,
425 _fields: NonZeroUsize,
426 ) -> InterpResult<'tcx> {
427 bug!("we should have already handled unions in `visit_value`")
432 /// Helper function used inside the shims of foreign functions to check that isolation is
433 /// disabled. It returns an error using the `name` of the foreign function if this is not the
435 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
436 if !self.eval_context_ref().machine.communicate() {
437 self.reject_in_isolation(name, RejectOpWith::Abort)?;
442 /// Helper function used inside the shims of foreign functions which reject the op
443 /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
444 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
445 let this = self.eval_context_ref();
447 RejectOpWith::Abort => isolation_abort_error(op_name),
448 RejectOpWith::WarningWithoutBacktrace => {
451 .warn(&format!("{} was made to return an error due to isolation", op_name));
454 RejectOpWith::Warning => {
455 register_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
458 RejectOpWith::NoWarning => Ok(()), // no warning
462 /// Helper function used inside the shims of foreign functions to assert that the target OS
463 /// is `target_os`. It panics showing a message with the `name` of the foreign function
464 /// if this is not the case.
465 fn assert_target_os(&self, target_os: &str, name: &str) {
467 self.eval_context_ref().tcx.sess.target.os,
469 "`{}` is only available on the `{}` target OS",
475 /// Get last error variable as a place, lazily allocating thread-local storage for it if
477 fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Tag>> {
478 let this = self.eval_context_mut();
479 if let Some(errno_place) = this.active_thread_ref().last_error {
482 // Allocate new place, set initial value to 0.
483 let errno_layout = this.machine.layouts.u32;
484 let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
485 this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
486 this.active_thread_mut().last_error = Some(errno_place);
491 /// Sets the last error variable.
492 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
493 let this = self.eval_context_mut();
494 let errno_place = this.last_error_place()?;
495 this.write_scalar(scalar, &errno_place.into())
498 /// Gets the last error variable.
499 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
500 let this = self.eval_context_mut();
501 let errno_place = this.last_error_place()?;
502 this.read_scalar(&errno_place.into())?.check_init()
505 /// Sets the last OS error using a `std::io::ErrorKind`. This function tries to produce the most
506 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
507 fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
508 use std::io::ErrorKind::*;
509 let this = self.eval_context_mut();
510 let target = &this.tcx.sess.target;
511 let target_os = &target.os;
512 let last_error = if target.families.iter().any(|f| f == "unix") {
513 this.eval_libc(match err_kind {
514 ConnectionRefused => "ECONNREFUSED",
515 ConnectionReset => "ECONNRESET",
516 PermissionDenied => "EPERM",
517 BrokenPipe => "EPIPE",
518 NotConnected => "ENOTCONN",
519 ConnectionAborted => "ECONNABORTED",
520 AddrNotAvailable => "EADDRNOTAVAIL",
521 AddrInUse => "EADDRINUSE",
522 NotFound => "ENOENT",
523 Interrupted => "EINTR",
524 InvalidInput => "EINVAL",
525 TimedOut => "ETIMEDOUT",
526 AlreadyExists => "EEXIST",
527 WouldBlock => "EWOULDBLOCK",
528 DirectoryNotEmpty => "ENOTEMPTY",
531 "io error {:?} cannot be translated into a raw os error",
536 } else if target.families.iter().any(|f| f == "windows") {
537 // FIXME: we have to finish implementing the Windows equivalent of this.
541 NotFound => "ERROR_FILE_NOT_FOUND",
542 PermissionDenied => "ERROR_ACCESS_DENIED",
545 "io error {:?} cannot be translated into a raw os error",
552 "setting the last OS error from an io::Error is unsupported for {}.",
556 this.set_last_error(last_error)
559 /// Helper function that consumes an `std::io::Result<T>` and returns an
560 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
561 /// `Ok(-1)` and sets the last OS error accordingly.
563 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
564 /// functions return different integer types (like `read`, that returns an `i64`).
565 fn try_unwrap_io_result<T: From<i32>>(
567 result: std::io::Result<T>,
568 ) -> InterpResult<'tcx, T> {
572 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
578 fn read_scalar_at_offset(
580 op: &OpTy<'tcx, Tag>,
582 layout: TyAndLayout<'tcx>,
583 ) -> InterpResult<'tcx, ScalarMaybeUninit<Tag>> {
584 let this = self.eval_context_ref();
585 let op_place = this.deref_operand(op)?;
586 let offset = Size::from_bytes(offset);
587 // Ensure that the following read at an offset is within bounds
588 assert!(op_place.layout.size >= offset + layout.size);
589 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
590 this.read_scalar(&value_place.into())
593 fn write_scalar_at_offset(
595 op: &OpTy<'tcx, Tag>,
597 value: impl Into<ScalarMaybeUninit<Tag>>,
598 layout: TyAndLayout<'tcx>,
599 ) -> InterpResult<'tcx, ()> {
600 let this = self.eval_context_mut();
601 let op_place = this.deref_operand(op)?;
602 let offset = Size::from_bytes(offset);
603 // Ensure that the following read at an offset is within bounds
604 assert!(op_place.layout.size >= offset + layout.size);
605 let value_place = op_place.offset(offset, MemPlaceMeta::None, layout, this)?;
606 this.write_scalar(value, &value_place.into())
609 /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
610 /// if the value in the `timespec` struct is invalid. Some libc functions will return
611 /// `EINVAL` in this case.
612 fn read_timespec(&mut self, tp: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx, Option<Duration>> {
613 let this = self.eval_context_mut();
614 let seconds_place = this.mplace_field(&tp, 0)?;
615 let seconds_scalar = this.read_scalar(&seconds_place.into())?;
616 let seconds = seconds_scalar.to_machine_isize(this)?;
617 let nanoseconds_place = this.mplace_field(&tp, 1)?;
618 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
619 let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
622 // tv_sec must be non-negative.
623 let seconds: u64 = seconds.try_into().ok()?;
624 // tv_nsec must be non-negative.
625 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
626 if nanoseconds >= 1_000_000_000 {
627 // tv_nsec must not be greater than 999,999,999.
630 Duration::new(seconds, nanoseconds)
634 fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, &'a [u8]>
639 let this = self.eval_context_ref();
640 let size1 = Size::from_bytes(1);
642 // Step 1: determine the length.
643 let mut len = Size::ZERO;
645 // FIXME: We are re-getting the allocation each time around the loop.
646 // Would be nice if we could somehow "extend" an existing AllocRange.
648 this.get_ptr_alloc(ptr.offset(len, this)?.into(), size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
649 let byte = alloc.read_scalar(alloc_range(Size::ZERO, size1))?.to_u8()?;
657 // Step 2: get the bytes.
658 this.read_bytes_ptr(ptr.into(), len)
661 fn read_wide_str(&self, mut ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, Vec<u16>> {
662 let this = self.eval_context_ref();
663 let size2 = Size::from_bytes(2);
664 let align2 = Align::from_bytes(2).unwrap();
666 let mut wchars = Vec::new();
668 // FIXME: We are re-getting the allocation each time around the loop.
669 // Would be nice if we could somehow "extend" an existing AllocRange.
670 let alloc = this.get_ptr_alloc(ptr.into(), size2, align2)?.unwrap(); // not a ZST, so we will get a result
671 let wchar = alloc.read_scalar(alloc_range(Size::ZERO, size2))?.to_u16()?;
676 ptr = ptr.offset(size2, this)?;
683 /// Check that the ABI is what we expect.
684 fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
685 if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
687 "calling a function with ABI {} using caller ABI {}",
695 fn frame_in_std(&self) -> bool {
696 let this = self.eval_context_ref();
697 this.tcx.lang_items().start_fn().map_or(false, |start_fn| {
698 this.tcx.def_path(this.frame().instance.def_id()).krate
699 == this.tcx.def_path(start_fn).krate
703 /// Handler that should be called when unsupported functionality is encountered.
704 /// This function will either panic within the context of the emulated application
705 /// or return an error in the Miri process context
707 /// Return value of `Ok(bool)` indicates whether execution should continue.
708 fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
709 let this = self.eval_context_mut();
710 if this.machine.panic_on_unsupported {
711 // message is slightly different here to make automated analysis easier
712 let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
713 this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
716 throw_unsup_format!("{}", error_msg.as_ref());
720 fn check_abi_and_shim_symbol_clash(
725 ) -> InterpResult<'tcx, ()> {
726 self.check_abi(abi, exp_abi)?;
727 if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
728 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
730 span: body.span.data(),
736 fn check_shim<'a, const N: usize>(
741 args: &'a [OpTy<'tcx, Tag>],
742 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
744 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
746 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
747 check_arg_count(args)
750 /// Mark a machine allocation that was just created as immutable.
751 fn mark_immutable(&mut self, mplace: &MemPlace<Tag>) {
752 let this = self.eval_context_mut();
753 this.alloc_mark_immutable(mplace.ptr.into_pointer_or_addr().unwrap().provenance.alloc_id)
758 /// Check that the number of args is what we expect.
759 pub fn check_arg_count<'a, 'tcx, const N: usize>(
760 args: &'a [OpTy<'tcx, Tag>],
761 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Tag>; N]>
763 &'a [OpTy<'tcx, Tag>; N]: TryFrom<&'a [OpTy<'tcx, Tag>]>,
765 if let Ok(ops) = args.try_into() {
768 throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
771 pub fn isolation_abort_error(name: &str) -> InterpResult<'static> {
772 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
773 "{} not available when isolation is enabled",
778 /// Retrieve the list of local crates that should have been passed by cargo-miri in
779 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
780 pub fn get_local_crates(tcx: &TyCtxt<'_>) -> Vec<CrateNum> {
781 // Convert the local crate names from the passed-in config into CrateNums so that they can
782 // be looked up quickly during execution
783 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
784 .map(|crates| crates.split(",").map(|krate| krate.to_string()).collect::<Vec<_>>())
785 .unwrap_or_default();
786 let mut local_crates = Vec::new();
787 for &crate_num in tcx.crates(()) {
788 let name = tcx.crate_name(crate_num);
789 let name = name.as_str();
790 if local_crate_names.iter().any(|local_name| local_name == name) {
791 local_crates.push(crate_num);