]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/helpers.rs
Auto merge of #99099 - Stargateur:phantomdata_debug, r=joshtriplett
[rust.git] / src / tools / miri / src / helpers.rs
1 pub mod convert;
2
3 use std::mem;
4 use std::num::NonZeroUsize;
5 use std::time::Duration;
6
7 use log::trace;
8
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_middle::mir;
11 use rustc_middle::ty::{
12     self,
13     layout::{LayoutOf, TyAndLayout},
14     List, TyCtxt,
15 };
16 use rustc_span::{def_id::CrateNum, sym, Span, Symbol};
17 use rustc_target::abi::{Align, FieldsShape, Size, Variants};
18 use rustc_target::spec::abi::Abi;
19
20 use rand::RngCore;
21
22 use crate::*;
23
24 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
25
26 // This mapping should match `decode_error_kind` in
27 // <https://github.com/rust-lang/rust/blob/master/library/std/src/sys/unix/mod.rs>.
28 const UNIX_IO_ERROR_TABLE: &[(&str, std::io::ErrorKind)] = {
29     use std::io::ErrorKind::*;
30     &[
31         ("E2BIG", ArgumentListTooLong),
32         ("EADDRINUSE", AddrInUse),
33         ("EADDRNOTAVAIL", AddrNotAvailable),
34         ("EBUSY", ResourceBusy),
35         ("ECONNABORTED", ConnectionAborted),
36         ("ECONNREFUSED", ConnectionRefused),
37         ("ECONNRESET", ConnectionReset),
38         ("EDEADLK", Deadlock),
39         ("EDQUOT", FilesystemQuotaExceeded),
40         ("EEXIST", AlreadyExists),
41         ("EFBIG", FileTooLarge),
42         ("EHOSTUNREACH", HostUnreachable),
43         ("EINTR", Interrupted),
44         ("EINVAL", InvalidInput),
45         ("EISDIR", IsADirectory),
46         ("ELOOP", FilesystemLoop),
47         ("ENOENT", NotFound),
48         ("ENOMEM", OutOfMemory),
49         ("ENOSPC", StorageFull),
50         ("ENOSYS", Unsupported),
51         ("EMLINK", TooManyLinks),
52         ("ENAMETOOLONG", InvalidFilename),
53         ("ENETDOWN", NetworkDown),
54         ("ENETUNREACH", NetworkUnreachable),
55         ("ENOTCONN", NotConnected),
56         ("ENOTDIR", NotADirectory),
57         ("ENOTEMPTY", DirectoryNotEmpty),
58         ("EPIPE", BrokenPipe),
59         ("EROFS", ReadOnlyFilesystem),
60         ("ESPIPE", NotSeekable),
61         ("ESTALE", StaleNetworkFileHandle),
62         ("ETIMEDOUT", TimedOut),
63         ("ETXTBSY", ExecutableFileBusy),
64         ("EXDEV", CrossesDevices),
65         // The following have two valid options. We have both for the forwards mapping; only the
66         // first one will be used for the backwards mapping.
67         ("EPERM", PermissionDenied),
68         ("EACCES", PermissionDenied),
69         ("EWOULDBLOCK", WouldBlock),
70         ("EAGAIN", WouldBlock),
71     ]
72 };
73
74 /// Gets an instance for a path.
75 fn try_resolve_did<'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
76     tcx.crates(()).iter().find(|&&krate| tcx.crate_name(krate).as_str() == path[0]).and_then(
77         |krate| {
78             let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
79             let mut items = tcx.module_children(krate);
80             let mut path_it = path.iter().skip(1).peekable();
81
82             while let Some(segment) = path_it.next() {
83                 for item in mem::take(&mut items).iter() {
84                     if item.ident.name.as_str() == *segment {
85                         if path_it.peek().is_none() {
86                             return Some(item.res.def_id());
87                         }
88
89                         items = tcx.module_children(item.res.def_id());
90                         break;
91                     }
92                 }
93             }
94             None
95         },
96     )
97 }
98
99 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
100     /// Gets an instance for a path; fails gracefully if the path does not exist.
101     fn try_resolve_path(&self, path: &[&str]) -> Option<ty::Instance<'tcx>> {
102         let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)?;
103         Some(ty::Instance::mono(self.eval_context_ref().tcx.tcx, did))
104     }
105
106     /// Gets an instance for a path.
107     fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
108         self.try_resolve_path(path)
109             .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path))
110     }
111
112     /// Evaluates the scalar at the specified path. Returns Some(val)
113     /// if the path could be resolved, and None otherwise
114     fn eval_path_scalar(&self, path: &[&str]) -> InterpResult<'tcx, Scalar<Provenance>> {
115         let this = self.eval_context_ref();
116         let instance = this.resolve_path(path);
117         let cid = GlobalId { instance, promoted: None };
118         let const_val = this.eval_to_allocation(cid)?;
119         this.read_scalar(&const_val.into())
120     }
121
122     /// Helper function to get a `libc` constant as a `Scalar`.
123     fn eval_libc(&self, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
124         self.eval_path_scalar(&["libc", name])
125     }
126
127     /// Helper function to get a `libc` constant as an `i32`.
128     fn eval_libc_i32(&self, name: &str) -> InterpResult<'tcx, i32> {
129         // TODO: Cache the result.
130         self.eval_libc(name)?.to_i32()
131     }
132
133     /// Helper function to get a `windows` constant as a `Scalar`.
134     fn eval_windows(&self, module: &str, name: &str) -> InterpResult<'tcx, Scalar<Provenance>> {
135         self.eval_context_ref().eval_path_scalar(&["std", "sys", "windows", module, name])
136     }
137
138     /// Helper function to get a `windows` constant as a `u64`.
139     fn eval_windows_u64(&self, module: &str, name: &str) -> InterpResult<'tcx, u64> {
140         // TODO: Cache the result.
141         self.eval_windows(module, name)?.to_u64()
142     }
143
144     /// Helper function to get the `TyAndLayout` of a `libc` type
145     fn libc_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
146         let this = self.eval_context_ref();
147         let ty = this.resolve_path(&["libc", name]).ty(*this.tcx, ty::ParamEnv::reveal_all());
148         this.layout_of(ty)
149     }
150
151     /// Helper function to get the `TyAndLayout` of a `windows` type
152     fn windows_ty_layout(&self, name: &str) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
153         let this = self.eval_context_ref();
154         let ty = this
155             .resolve_path(&["std", "sys", "windows", "c", name])
156             .ty(*this.tcx, ty::ParamEnv::reveal_all());
157         this.layout_of(ty)
158     }
159
160     /// Project to the given *named* field of the mplace (which must be a struct or union type).
161     fn mplace_field_named(
162         &self,
163         mplace: &MPlaceTy<'tcx, Provenance>,
164         name: &str,
165     ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
166         let this = self.eval_context_ref();
167         let adt = mplace.layout.ty.ty_adt_def().unwrap();
168         for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
169             if field.name.as_str() == name {
170                 return this.mplace_field(mplace, idx);
171             }
172         }
173         bug!("No field named {} in type {}", name, mplace.layout.ty);
174     }
175
176     /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
177     /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
178     /// this method is fine for almost all integer types.
179     fn write_int(
180         &mut self,
181         i: impl Into<i128>,
182         dest: &PlaceTy<'tcx, Provenance>,
183     ) -> InterpResult<'tcx> {
184         assert!(dest.layout.abi.is_scalar(), "write_int on non-scalar type {}", dest.layout.ty);
185         let val = if dest.layout.abi.is_signed() {
186             Scalar::from_int(i, dest.layout.size)
187         } else {
188             Scalar::from_uint(u64::try_from(i.into()).unwrap(), dest.layout.size)
189         };
190         self.eval_context_mut().write_scalar(val, dest)
191     }
192
193     /// Write the first N fields of the given place.
194     fn write_int_fields(
195         &mut self,
196         values: &[i128],
197         dest: &MPlaceTy<'tcx, Provenance>,
198     ) -> InterpResult<'tcx> {
199         let this = self.eval_context_mut();
200         for (idx, &val) in values.iter().enumerate() {
201             let field = this.mplace_field(dest, idx)?;
202             this.write_int(val, &field.into())?;
203         }
204         Ok(())
205     }
206
207     /// Write the given fields of the given place.
208     fn write_int_fields_named(
209         &mut self,
210         values: &[(&str, i128)],
211         dest: &MPlaceTy<'tcx, Provenance>,
212     ) -> InterpResult<'tcx> {
213         let this = self.eval_context_mut();
214         for &(name, val) in values.iter() {
215             let field = this.mplace_field_named(dest, name)?;
216             this.write_int(val, &field.into())?;
217         }
218         Ok(())
219     }
220
221     /// Write a 0 of the appropriate size to `dest`.
222     fn write_null(&mut self, dest: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
223         self.write_int(0, dest)
224     }
225
226     /// Test if this pointer equals 0.
227     fn ptr_is_null(&self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, bool> {
228         Ok(ptr.addr().bytes() == 0)
229     }
230
231     /// Get the `Place` for a local
232     fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Provenance>> {
233         let this = self.eval_context_mut();
234         let place = mir::Place { local, projection: List::empty() };
235         this.eval_place(place)
236     }
237
238     /// Generate some random bytes, and write them to `dest`.
239     fn gen_random(&mut self, ptr: Pointer<Option<Provenance>>, len: u64) -> InterpResult<'tcx> {
240         // Some programs pass in a null pointer and a length of 0
241         // to their platform's random-generation function (e.g. getrandom())
242         // on Linux. For compatibility with these programs, we don't perform
243         // any additional checks - it's okay if the pointer is invalid,
244         // since we wouldn't actually be writing to it.
245         if len == 0 {
246             return Ok(());
247         }
248         let this = self.eval_context_mut();
249
250         let mut data = vec![0; usize::try_from(len).unwrap()];
251
252         if this.machine.communicate() {
253             // Fill the buffer using the host's rng.
254             getrandom::getrandom(&mut data)
255                 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
256         } else {
257             let rng = this.machine.rng.get_mut();
258             rng.fill_bytes(&mut data);
259         }
260
261         this.write_bytes_ptr(ptr, data.iter().copied())
262     }
263
264     /// Call a function: Push the stack frame and pass the arguments.
265     /// For now, arguments must be scalars (so that the caller does not have to know the layout).
266     ///
267     /// If you do not provie a return place, a dangling zero-sized place will be created
268     /// for your convenience.
269     fn call_function(
270         &mut self,
271         f: ty::Instance<'tcx>,
272         caller_abi: Abi,
273         args: &[Immediate<Provenance>],
274         dest: Option<&PlaceTy<'tcx, Provenance>>,
275         stack_pop: StackPopCleanup,
276     ) -> InterpResult<'tcx> {
277         let this = self.eval_context_mut();
278         let param_env = ty::ParamEnv::reveal_all(); // in Miri this is always the param_env we use... and this.param_env is private.
279         let callee_abi = f.ty(*this.tcx, param_env).fn_sig(*this.tcx).abi();
280         if this.machine.enforce_abi && callee_abi != caller_abi {
281             throw_ub_format!(
282                 "calling a function with ABI {} using caller ABI {}",
283                 callee_abi.name(),
284                 caller_abi.name()
285             )
286         }
287
288         // Push frame.
289         let mir = this.load_mir(f.def, None)?;
290         let dest = match dest {
291             Some(dest) => dest.clone(),
292             None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?).into(),
293         };
294         this.push_stack_frame(f, mir, &dest, stack_pop)?;
295
296         // Initialize arguments.
297         let mut callee_args = this.frame().body.args_iter();
298         for arg in args {
299             let callee_arg = this.local_place(
300                 callee_args
301                     .next()
302                     .ok_or_else(|| err_ub_format!("callee has fewer arguments than expected"))?,
303             )?;
304             this.write_immediate(*arg, &callee_arg)?;
305         }
306         if callee_args.next().is_some() {
307             throw_ub_format!("callee has more arguments than expected");
308         }
309
310         Ok(())
311     }
312
313     /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
314     /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
315     /// The range is relative to `place`.
316     fn visit_freeze_sensitive(
317         &self,
318         place: &MPlaceTy<'tcx, Provenance>,
319         size: Size,
320         mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
321     ) -> InterpResult<'tcx> {
322         let this = self.eval_context_ref();
323         trace!("visit_frozen(place={:?}, size={:?})", *place, size);
324         debug_assert_eq!(
325             size,
326             this.size_and_align_of_mplace(place)?
327                 .map(|(size, _)| size)
328                 .unwrap_or_else(|| place.layout.size)
329         );
330         // Store how far we proceeded into the place so far. Everything to the left of
331         // this offset has already been handled, in the sense that the frozen parts
332         // have had `action` called on them.
333         let start_addr = place.ptr.addr();
334         let mut cur_addr = start_addr;
335         // Called when we detected an `UnsafeCell` at the given offset and size.
336         // Calls `action` and advances `cur_ptr`.
337         let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer<Option<Provenance>>,
338                                       unsafe_cell_size: Size| {
339             // We assume that we are given the fields in increasing offset order,
340             // and nothing else changes.
341             let unsafe_cell_addr = unsafe_cell_ptr.addr();
342             assert!(unsafe_cell_addr >= cur_addr);
343             let frozen_size = unsafe_cell_addr - cur_addr;
344             // Everything between the cur_ptr and this `UnsafeCell` is frozen.
345             if frozen_size != Size::ZERO {
346                 action(alloc_range(cur_addr - start_addr, frozen_size), /*frozen*/ true)?;
347             }
348             cur_addr += frozen_size;
349             // This `UnsafeCell` is NOT frozen.
350             if unsafe_cell_size != Size::ZERO {
351                 action(
352                     alloc_range(cur_addr - start_addr, unsafe_cell_size),
353                     /*frozen*/ false,
354                 )?;
355             }
356             cur_addr += unsafe_cell_size;
357             // Done
358             Ok(())
359         };
360         // Run a visitor
361         {
362             let mut visitor = UnsafeCellVisitor {
363                 ecx: this,
364                 unsafe_cell_action: |place| {
365                     trace!("unsafe_cell_action on {:?}", place.ptr);
366                     // We need a size to go on.
367                     let unsafe_cell_size = this
368                         .size_and_align_of_mplace(place)?
369                         .map(|(size, _)| size)
370                         // for extern types, just cover what we can
371                         .unwrap_or_else(|| place.layout.size);
372                     // Now handle this `UnsafeCell`, unless it is empty.
373                     if unsafe_cell_size != Size::ZERO {
374                         unsafe_cell_action(&place.ptr, unsafe_cell_size)
375                     } else {
376                         Ok(())
377                     }
378                 },
379             };
380             visitor.visit_value(place)?;
381         }
382         // The part between the end_ptr and the end of the place is also frozen.
383         // So pretend there is a 0-sized `UnsafeCell` at the end.
384         unsafe_cell_action(&place.ptr.offset(size, this)?, Size::ZERO)?;
385         // Done!
386         return Ok(());
387
388         /// Visiting the memory covered by a `MemPlace`, being aware of
389         /// whether we are inside an `UnsafeCell` or not.
390         struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
391         where
392             F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
393         {
394             ecx: &'ecx MiriInterpCx<'mir, 'tcx>,
395             unsafe_cell_action: F,
396         }
397
398         impl<'ecx, 'mir, 'tcx: 'mir, F> ValueVisitor<'mir, 'tcx, MiriMachine<'mir, 'tcx>>
399             for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
400         where
401             F: FnMut(&MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx>,
402         {
403             type V = MPlaceTy<'tcx, Provenance>;
404
405             #[inline(always)]
406             fn ecx(&self) -> &MiriInterpCx<'mir, 'tcx> {
407                 self.ecx
408             }
409
410             // Hook to detect `UnsafeCell`.
411             fn visit_value(&mut self, v: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
412                 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
413                 let is_unsafe_cell = match v.layout.ty.kind() {
414                     ty::Adt(adt, _) =>
415                         Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
416                     _ => false,
417                 };
418                 if is_unsafe_cell {
419                     // We do not have to recurse further, this is an `UnsafeCell`.
420                     (self.unsafe_cell_action)(v)
421                 } else if self.ecx.type_is_freeze(v.layout.ty) {
422                     // This is `Freeze`, there cannot be an `UnsafeCell`
423                     Ok(())
424                 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
425                     // A (non-frozen) union. We fall back to whatever the type says.
426                     (self.unsafe_cell_action)(v)
427                 } else {
428                     // We want to not actually read from memory for this visit. So, before
429                     // walking this value, we have to make sure it is not a
430                     // `Variants::Multiple`.
431                     match v.layout.variants {
432                         Variants::Multiple { .. } => {
433                             // A multi-variant enum, or generator, or so.
434                             // Treat this like a union: without reading from memory,
435                             // we cannot determine the variant we are in. Reading from
436                             // memory would be subject to Stacked Borrows rules, leading
437                             // to all sorts of "funny" recursion.
438                             // We only end up here if the type is *not* freeze, so we just call the
439                             // `UnsafeCell` action.
440                             (self.unsafe_cell_action)(v)
441                         }
442                         Variants::Single { .. } => {
443                             // Proceed further, try to find where exactly that `UnsafeCell`
444                             // is hiding.
445                             self.walk_value(v)
446                         }
447                     }
448                 }
449             }
450
451             // Make sure we visit aggregrates in increasing offset order.
452             fn visit_aggregate(
453                 &mut self,
454                 place: &MPlaceTy<'tcx, Provenance>,
455                 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Provenance>>>,
456             ) -> InterpResult<'tcx> {
457                 match place.layout.fields {
458                     FieldsShape::Array { .. } => {
459                         // For the array layout, we know the iterator will yield sorted elements so
460                         // we can avoid the allocation.
461                         self.walk_aggregate(place, fields)
462                     }
463                     FieldsShape::Arbitrary { .. } => {
464                         // Gather the subplaces and sort them before visiting.
465                         let mut places = fields
466                             .collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Provenance>>>>()?;
467                         // we just compare offsets, the abs. value never matters
468                         places.sort_by_key(|place| place.ptr.addr());
469                         self.walk_aggregate(place, places.into_iter().map(Ok))
470                     }
471                     FieldsShape::Union { .. } | FieldsShape::Primitive => {
472                         // Uh, what?
473                         bug!("unions/primitives are not aggregates we should ever visit")
474                     }
475                 }
476             }
477
478             fn visit_union(
479                 &mut self,
480                 _v: &MPlaceTy<'tcx, Provenance>,
481                 _fields: NonZeroUsize,
482             ) -> InterpResult<'tcx> {
483                 bug!("we should have already handled unions in `visit_value`")
484             }
485         }
486     }
487
488     /// Helper function used inside the shims of foreign functions to check that isolation is
489     /// disabled. It returns an error using the `name` of the foreign function if this is not the
490     /// case.
491     fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
492         if !self.eval_context_ref().machine.communicate() {
493             self.reject_in_isolation(name, RejectOpWith::Abort)?;
494         }
495         Ok(())
496     }
497
498     /// Helper function used inside the shims of foreign functions which reject the op
499     /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
500     fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
501         let this = self.eval_context_ref();
502         match reject_with {
503             RejectOpWith::Abort => isolation_abort_error(op_name),
504             RejectOpWith::WarningWithoutBacktrace => {
505                 this.tcx
506                     .sess
507                     .warn(&format!("{} was made to return an error due to isolation", op_name));
508                 Ok(())
509             }
510             RejectOpWith::Warning => {
511                 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
512                 Ok(())
513             }
514             RejectOpWith::NoWarning => Ok(()), // no warning
515         }
516     }
517
518     /// Helper function used inside the shims of foreign functions to assert that the target OS
519     /// is `target_os`. It panics showing a message with the `name` of the foreign function
520     /// if this is not the case.
521     fn assert_target_os(&self, target_os: &str, name: &str) {
522         assert_eq!(
523             self.eval_context_ref().tcx.sess.target.os,
524             target_os,
525             "`{}` is only available on the `{}` target OS",
526             name,
527             target_os,
528         )
529     }
530
531     /// Helper function used inside the shims of foreign functions to assert that the target OS
532     /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
533     /// if this is not the case.
534     fn assert_target_os_is_unix(&self, name: &str) {
535         assert!(
536             target_os_is_unix(self.eval_context_ref().tcx.sess.target.os.as_ref()),
537             "`{}` is only available for supported UNIX family targets",
538             name,
539         );
540     }
541
542     /// Get last error variable as a place, lazily allocating thread-local storage for it if
543     /// necessary.
544     fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
545         let this = self.eval_context_mut();
546         if let Some(errno_place) = this.active_thread_ref().last_error {
547             Ok(errno_place)
548         } else {
549             // Allocate new place, set initial value to 0.
550             let errno_layout = this.machine.layouts.u32;
551             let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
552             this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
553             this.active_thread_mut().last_error = Some(errno_place);
554             Ok(errno_place)
555         }
556     }
557
558     /// Sets the last error variable.
559     fn set_last_error(&mut self, scalar: Scalar<Provenance>) -> InterpResult<'tcx> {
560         let this = self.eval_context_mut();
561         let errno_place = this.last_error_place()?;
562         this.write_scalar(scalar, &errno_place.into())
563     }
564
565     /// Gets the last error variable.
566     fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Provenance>> {
567         let this = self.eval_context_mut();
568         let errno_place = this.last_error_place()?;
569         this.read_scalar(&errno_place.into())
570     }
571
572     /// This function tries to produce the most similar OS error from the `std::io::ErrorKind`
573     /// as a platform-specific errnum.
574     fn io_error_to_errnum(
575         &self,
576         err_kind: std::io::ErrorKind,
577     ) -> InterpResult<'tcx, Scalar<Provenance>> {
578         let this = self.eval_context_ref();
579         let target = &this.tcx.sess.target;
580         if target.families.iter().any(|f| f == "unix") {
581             for &(name, kind) in UNIX_IO_ERROR_TABLE {
582                 if err_kind == kind {
583                     return this.eval_libc(name);
584                 }
585             }
586             throw_unsup_format!("io error {:?} cannot be translated into a raw os error", err_kind)
587         } else if target.families.iter().any(|f| f == "windows") {
588             // FIXME: we have to finish implementing the Windows equivalent of this.
589             use std::io::ErrorKind::*;
590             this.eval_windows(
591                 "c",
592                 match err_kind {
593                     NotFound => "ERROR_FILE_NOT_FOUND",
594                     PermissionDenied => "ERROR_ACCESS_DENIED",
595                     _ =>
596                         throw_unsup_format!(
597                             "io error {:?} cannot be translated into a raw os error",
598                             err_kind
599                         ),
600                 },
601             )
602         } else {
603             throw_unsup_format!(
604                 "converting io::Error into errnum is unsupported for OS {}",
605                 target.os
606             )
607         }
608     }
609
610     /// The inverse of `io_error_to_errnum`.
611     #[allow(clippy::needless_return)]
612     fn try_errnum_to_io_error(
613         &self,
614         errnum: Scalar<Provenance>,
615     ) -> InterpResult<'tcx, Option<std::io::ErrorKind>> {
616         let this = self.eval_context_ref();
617         let target = &this.tcx.sess.target;
618         if target.families.iter().any(|f| f == "unix") {
619             let errnum = errnum.to_i32()?;
620             for &(name, kind) in UNIX_IO_ERROR_TABLE {
621                 if errnum == this.eval_libc_i32(name)? {
622                     return Ok(Some(kind));
623                 }
624             }
625             // Our table is as complete as the mapping in std, so we are okay with saying "that's a
626             // strange one" here.
627             return Ok(None);
628         } else {
629             throw_unsup_format!(
630                 "converting errnum into io::Error is unsupported for OS {}",
631                 target.os
632             )
633         }
634     }
635
636     /// Sets the last OS error using a `std::io::ErrorKind`.
637     fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
638         self.set_last_error(self.io_error_to_errnum(err_kind)?)
639     }
640
641     /// Helper function that consumes an `std::io::Result<T>` and returns an
642     /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
643     /// `Ok(-1)` and sets the last OS error accordingly.
644     ///
645     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
646     /// functions return different integer types (like `read`, that returns an `i64`).
647     fn try_unwrap_io_result<T: From<i32>>(
648         &mut self,
649         result: std::io::Result<T>,
650     ) -> InterpResult<'tcx, T> {
651         match result {
652             Ok(ok) => Ok(ok),
653             Err(e) => {
654                 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
655                 Ok((-1).into())
656             }
657         }
658     }
659
660     /// Calculates the MPlaceTy given the offset and layout of an access on an operand
661     fn deref_operand_and_offset(
662         &self,
663         op: &OpTy<'tcx, Provenance>,
664         offset: u64,
665         layout: TyAndLayout<'tcx>,
666     ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
667         let this = self.eval_context_ref();
668         let op_place = this.deref_operand(op)?;
669         let offset = Size::from_bytes(offset);
670
671         // Ensure that the access is within bounds.
672         assert!(op_place.layout.size >= offset + layout.size);
673         let value_place = op_place.offset(offset, layout, this)?;
674         Ok(value_place)
675     }
676
677     fn read_scalar_at_offset(
678         &self,
679         op: &OpTy<'tcx, Provenance>,
680         offset: u64,
681         layout: TyAndLayout<'tcx>,
682     ) -> InterpResult<'tcx, Scalar<Provenance>> {
683         let this = self.eval_context_ref();
684         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
685         this.read_scalar(&value_place.into())
686     }
687
688     fn write_immediate_at_offset(
689         &mut self,
690         op: &OpTy<'tcx, Provenance>,
691         offset: u64,
692         value: &ImmTy<'tcx, Provenance>,
693     ) -> InterpResult<'tcx, ()> {
694         let this = self.eval_context_mut();
695         let value_place = this.deref_operand_and_offset(op, offset, value.layout)?;
696         this.write_immediate(**value, &value_place.into())
697     }
698
699     fn write_scalar_at_offset(
700         &mut self,
701         op: &OpTy<'tcx, Provenance>,
702         offset: u64,
703         value: impl Into<Scalar<Provenance>>,
704         layout: TyAndLayout<'tcx>,
705     ) -> InterpResult<'tcx, ()> {
706         self.write_immediate_at_offset(op, offset, &ImmTy::from_scalar(value.into(), layout))
707     }
708
709     /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
710     /// if the value in the `timespec` struct is invalid. Some libc functions will return
711     /// `EINVAL` in this case.
712     fn read_timespec(
713         &mut self,
714         tp: &MPlaceTy<'tcx, Provenance>,
715     ) -> InterpResult<'tcx, Option<Duration>> {
716         let this = self.eval_context_mut();
717         let seconds_place = this.mplace_field(tp, 0)?;
718         let seconds_scalar = this.read_scalar(&seconds_place.into())?;
719         let seconds = seconds_scalar.to_machine_isize(this)?;
720         let nanoseconds_place = this.mplace_field(tp, 1)?;
721         let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
722         let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
723
724         Ok(try {
725             // tv_sec must be non-negative.
726             let seconds: u64 = seconds.try_into().ok()?;
727             // tv_nsec must be non-negative.
728             let nanoseconds: u32 = nanoseconds.try_into().ok()?;
729             if nanoseconds >= 1_000_000_000 {
730                 // tv_nsec must not be greater than 999,999,999.
731                 None?
732             }
733             Duration::new(seconds, nanoseconds)
734         })
735     }
736
737     fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, &'a [u8]>
738     where
739         'tcx: 'a,
740         'mir: 'a,
741     {
742         let this = self.eval_context_ref();
743         let size1 = Size::from_bytes(1);
744
745         // Step 1: determine the length.
746         let mut len = Size::ZERO;
747         loop {
748             // FIXME: We are re-getting the allocation each time around the loop.
749             // Would be nice if we could somehow "extend" an existing AllocRange.
750             let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
751             let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
752             if byte == 0 {
753                 break;
754             } else {
755                 len += size1;
756             }
757         }
758
759         // Step 2: get the bytes.
760         this.read_bytes_ptr_strip_provenance(ptr, len)
761     }
762
763     fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {
764         let this = self.eval_context_ref();
765         let size2 = Size::from_bytes(2);
766         let align2 = Align::from_bytes(2).unwrap();
767
768         let mut wchars = Vec::new();
769         loop {
770             // FIXME: We are re-getting the allocation each time around the loop.
771             // Would be nice if we could somehow "extend" an existing AllocRange.
772             let alloc = this.get_ptr_alloc(ptr, size2, align2)?.unwrap(); // not a ZST, so we will get a result
773             let wchar = alloc.read_integer(alloc_range(Size::ZERO, size2))?.to_u16()?;
774             if wchar == 0 {
775                 break;
776             } else {
777                 wchars.push(wchar);
778                 ptr = ptr.offset(size2, this)?;
779             }
780         }
781
782         Ok(wchars)
783     }
784
785     /// Check that the ABI is what we expect.
786     fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
787         if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
788             throw_ub_format!(
789                 "calling a function with ABI {} using caller ABI {}",
790                 exp_abi.name(),
791                 abi.name()
792             )
793         }
794         Ok(())
795     }
796
797     fn frame_in_std(&self) -> bool {
798         let this = self.eval_context_ref();
799         let Some(start_fn) = this.tcx.lang_items().start_fn() else {
800             // no_std situations
801             return false;
802         };
803         let frame = this.frame();
804         // Make an attempt to get at the instance of the function this is inlined from.
805         let instance: Option<_> = try {
806             let scope = frame.current_source_info()?.scope;
807             let inlined_parent = frame.body.source_scopes[scope].inlined_parent_scope?;
808             let source = &frame.body.source_scopes[inlined_parent];
809             source.inlined.expect("inlined_parent_scope points to scope without inline info").0
810         };
811         // Fall back to the instance of the function itself.
812         let instance = instance.unwrap_or(frame.instance);
813         // Now check if this is in the same crate as start_fn.
814         // As a special exception we also allow unit tests from
815         // <https://github.com/rust-lang/miri-test-libstd/tree/master/std_miri_test> to call these
816         // shims.
817         let frame_crate = this.tcx.def_path(instance.def_id()).krate;
818         frame_crate == this.tcx.def_path(start_fn).krate
819             || this.tcx.crate_name(frame_crate).as_str() == "std_miri_test"
820     }
821
822     /// Handler that should be called when unsupported functionality is encountered.
823     /// This function will either panic within the context of the emulated application
824     /// or return an error in the Miri process context
825     ///
826     /// Return value of `Ok(bool)` indicates whether execution should continue.
827     fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
828         let this = self.eval_context_mut();
829         if this.machine.panic_on_unsupported {
830             // message is slightly different here to make automated analysis easier
831             let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
832             this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
833             Ok(())
834         } else {
835             throw_unsup_format!("{}", error_msg.as_ref());
836         }
837     }
838
839     fn check_abi_and_shim_symbol_clash(
840         &mut self,
841         abi: Abi,
842         exp_abi: Abi,
843         link_name: Symbol,
844     ) -> InterpResult<'tcx, ()> {
845         self.check_abi(abi, exp_abi)?;
846         if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
847             throw_machine_stop!(TerminationInfo::SymbolShimClashing {
848                 link_name,
849                 span: body.span.data(),
850             })
851         }
852         Ok(())
853     }
854
855     fn check_shim<'a, const N: usize>(
856         &mut self,
857         abi: Abi,
858         exp_abi: Abi,
859         link_name: Symbol,
860         args: &'a [OpTy<'tcx, Provenance>],
861     ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
862     where
863         &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
864     {
865         self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
866         check_arg_count(args)
867     }
868
869     /// Mark a machine allocation that was just created as immutable.
870     fn mark_immutable(&mut self, mplace: &MemPlace<Provenance>) {
871         let this = self.eval_context_mut();
872         // This got just allocated, so there definitely is a pointer here.
873         let provenance = mplace.ptr.into_pointer_or_addr().unwrap().provenance;
874         this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
875     }
876
877     fn item_link_name(&self, def_id: DefId) -> Symbol {
878         let tcx = self.eval_context_ref().tcx;
879         match tcx.get_attrs(def_id, sym::link_name).filter_map(|a| a.value_str()).next() {
880             Some(name) => name,
881             None => tcx.item_name(def_id),
882         }
883     }
884 }
885
886 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
887     pub fn current_span(&self) -> CurrentSpan<'_, 'mir, 'tcx> {
888         CurrentSpan { current_frame_idx: None, machine: self }
889     }
890 }
891
892 /// A `CurrentSpan` should be created infrequently (ideally once) per interpreter step. It does
893 /// nothing on creation, but when `CurrentSpan::get` is called, searches the current stack for the
894 /// topmost frame which corresponds to a local crate, and returns the current span in that frame.
895 /// The result of that search is cached so that later calls are approximately free.
896 #[derive(Clone)]
897 pub struct CurrentSpan<'a, 'mir, 'tcx> {
898     current_frame_idx: Option<usize>,
899     machine: &'a MiriMachine<'mir, 'tcx>,
900 }
901
902 impl<'a, 'mir: 'a, 'tcx: 'a + 'mir> CurrentSpan<'a, 'mir, 'tcx> {
903     pub fn machine(&self) -> &'a MiriMachine<'mir, 'tcx> {
904         self.machine
905     }
906
907     /// Get the current span, skipping non-local frames.
908     /// This function is backed by a cache, and can be assumed to be very fast.
909     pub fn get(&mut self) -> Span {
910         let idx = self.current_frame_idx();
911         Self::frame_span(self.machine, idx)
912     }
913
914     /// Similar to `CurrentSpan::get`, but retrieves the parent frame of the first non-local frame.
915     /// This is useful when we are processing something which occurs on function-entry and we want
916     /// to point at the call to the function, not the function definition generally.
917     pub fn get_parent(&mut self) -> Span {
918         let idx = self.current_frame_idx();
919         Self::frame_span(self.machine, idx.wrapping_sub(1))
920     }
921
922     fn frame_span(machine: &MiriMachine<'_, '_>, idx: usize) -> Span {
923         machine
924             .threads
925             .active_thread_stack()
926             .get(idx)
927             .map(Frame::current_span)
928             .unwrap_or(rustc_span::DUMMY_SP)
929     }
930
931     fn current_frame_idx(&mut self) -> usize {
932         *self
933             .current_frame_idx
934             .get_or_insert_with(|| Self::compute_current_frame_index(self.machine))
935     }
936
937     // Find the position of the inner-most frame which is part of the crate being
938     // compiled/executed, part of the Cargo workspace, and is also not #[track_caller].
939     #[inline(never)]
940     fn compute_current_frame_index(machine: &MiriMachine<'_, '_>) -> usize {
941         machine
942             .threads
943             .active_thread_stack()
944             .iter()
945             .enumerate()
946             .rev()
947             .find_map(|(idx, frame)| {
948                 let def_id = frame.instance.def_id();
949                 if (def_id.is_local() || machine.local_crates.contains(&def_id.krate))
950                     && !frame.instance.def.requires_caller_location(machine.tcx)
951                 {
952                     Some(idx)
953                 } else {
954                     None
955                 }
956             })
957             .unwrap_or(0)
958     }
959 }
960
961 /// Check that the number of args is what we expect.
962 pub fn check_arg_count<'a, 'tcx, const N: usize>(
963     args: &'a [OpTy<'tcx, Provenance>],
964 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
965 where
966     &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
967 {
968     if let Ok(ops) = args.try_into() {
969         return Ok(ops);
970     }
971     throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
972 }
973
974 pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
975     throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
976         "{} not available when isolation is enabled",
977         name,
978     )))
979 }
980
981 /// Retrieve the list of local crates that should have been passed by cargo-miri in
982 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
983 pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
984     // Convert the local crate names from the passed-in config into CrateNums so that they can
985     // be looked up quickly during execution
986     let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
987         .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
988         .unwrap_or_default();
989     let mut local_crates = Vec::new();
990     for &crate_num in tcx.crates(()) {
991         let name = tcx.crate_name(crate_num);
992         let name = name.as_str();
993         if local_crate_names.iter().any(|local_name| local_name == name) {
994             local_crates.push(crate_num);
995         }
996     }
997     local_crates
998 }
999
1000 /// Helper function used inside the shims of foreign functions to check that
1001 /// `target_os` is a supported UNIX OS.
1002 pub fn target_os_is_unix(target_os: &str) -> bool {
1003     matches!(target_os, "linux" | "macos" | "freebsd" | "android")
1004 }