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