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