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