]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/helpers.rs
for now, do not do fake reads on non-Unpin mutable references
[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             "`{name}` is only available on the `{target_os}` target OS",
558         )
559     }
560
561     /// Helper function used inside the shims of foreign functions to assert that the target OS
562     /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
563     /// if this is not the case.
564     fn assert_target_os_is_unix(&self, name: &str) {
565         assert!(
566             target_os_is_unix(self.eval_context_ref().tcx.sess.target.os.as_ref()),
567             "`{name}` is only available for supported UNIX family targets",
568         );
569     }
570
571     /// Get last error variable as a place, lazily allocating thread-local storage for it if
572     /// necessary.
573     fn last_error_place(&mut self) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
574         let this = self.eval_context_mut();
575         if let Some(errno_place) = this.active_thread_ref().last_error {
576             Ok(errno_place)
577         } else {
578             // Allocate new place, set initial value to 0.
579             let errno_layout = this.machine.layouts.u32;
580             let errno_place = this.allocate(errno_layout, MiriMemoryKind::Machine.into())?;
581             this.write_scalar(Scalar::from_u32(0), &errno_place.into())?;
582             this.active_thread_mut().last_error = Some(errno_place);
583             Ok(errno_place)
584         }
585     }
586
587     /// Sets the last error variable.
588     fn set_last_error(&mut self, scalar: Scalar<Provenance>) -> InterpResult<'tcx> {
589         let this = self.eval_context_mut();
590         let errno_place = this.last_error_place()?;
591         this.write_scalar(scalar, &errno_place.into())
592     }
593
594     /// Gets the last error variable.
595     fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Provenance>> {
596         let this = self.eval_context_mut();
597         let errno_place = this.last_error_place()?;
598         this.read_scalar(&errno_place.into())
599     }
600
601     /// This function tries to produce the most similar OS error from the `std::io::ErrorKind`
602     /// as a platform-specific errnum.
603     fn io_error_to_errnum(
604         &self,
605         err_kind: std::io::ErrorKind,
606     ) -> InterpResult<'tcx, Scalar<Provenance>> {
607         let this = self.eval_context_ref();
608         let target = &this.tcx.sess.target;
609         if target.families.iter().any(|f| f == "unix") {
610             for &(name, kind) in UNIX_IO_ERROR_TABLE {
611                 if err_kind == kind {
612                     return this.eval_libc(name);
613                 }
614             }
615             throw_unsup_format!("io error {:?} cannot be translated into a raw os error", err_kind)
616         } else if target.families.iter().any(|f| f == "windows") {
617             // FIXME: we have to finish implementing the Windows equivalent of this.
618             use std::io::ErrorKind::*;
619             this.eval_windows(
620                 "c",
621                 match err_kind {
622                     NotFound => "ERROR_FILE_NOT_FOUND",
623                     PermissionDenied => "ERROR_ACCESS_DENIED",
624                     _ =>
625                         throw_unsup_format!(
626                             "io error {:?} cannot be translated into a raw os error",
627                             err_kind
628                         ),
629                 },
630             )
631         } else {
632             throw_unsup_format!(
633                 "converting io::Error into errnum is unsupported for OS {}",
634                 target.os
635             )
636         }
637     }
638
639     /// The inverse of `io_error_to_errnum`.
640     #[allow(clippy::needless_return)]
641     fn try_errnum_to_io_error(
642         &self,
643         errnum: Scalar<Provenance>,
644     ) -> InterpResult<'tcx, Option<std::io::ErrorKind>> {
645         let this = self.eval_context_ref();
646         let target = &this.tcx.sess.target;
647         if target.families.iter().any(|f| f == "unix") {
648             let errnum = errnum.to_i32()?;
649             for &(name, kind) in UNIX_IO_ERROR_TABLE {
650                 if errnum == this.eval_libc_i32(name)? {
651                     return Ok(Some(kind));
652                 }
653             }
654             // Our table is as complete as the mapping in std, so we are okay with saying "that's a
655             // strange one" here.
656             return Ok(None);
657         } else {
658             throw_unsup_format!(
659                 "converting errnum into io::Error is unsupported for OS {}",
660                 target.os
661             )
662         }
663     }
664
665     /// Sets the last OS error using a `std::io::ErrorKind`.
666     fn set_last_error_from_io_error(&mut self, err_kind: std::io::ErrorKind) -> InterpResult<'tcx> {
667         self.set_last_error(self.io_error_to_errnum(err_kind)?)
668     }
669
670     /// Helper function that consumes an `std::io::Result<T>` and returns an
671     /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
672     /// `Ok(-1)` and sets the last OS error accordingly.
673     ///
674     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
675     /// functions return different integer types (like `read`, that returns an `i64`).
676     fn try_unwrap_io_result<T: From<i32>>(
677         &mut self,
678         result: std::io::Result<T>,
679     ) -> InterpResult<'tcx, T> {
680         match result {
681             Ok(ok) => Ok(ok),
682             Err(e) => {
683                 self.eval_context_mut().set_last_error_from_io_error(e.kind())?;
684                 Ok((-1).into())
685             }
686         }
687     }
688
689     /// Calculates the MPlaceTy given the offset and layout of an access on an operand
690     fn deref_operand_and_offset(
691         &self,
692         op: &OpTy<'tcx, Provenance>,
693         offset: u64,
694         layout: TyAndLayout<'tcx>,
695     ) -> InterpResult<'tcx, MPlaceTy<'tcx, Provenance>> {
696         let this = self.eval_context_ref();
697         let op_place = this.deref_operand(op)?; // FIXME: we still deref with the original type!
698         let offset = Size::from_bytes(offset);
699
700         // Ensure that the access is within bounds.
701         assert!(op_place.layout.size >= offset + layout.size);
702         let value_place = op_place.offset(offset, layout, this)?;
703         Ok(value_place)
704     }
705
706     fn read_scalar_at_offset(
707         &self,
708         op: &OpTy<'tcx, Provenance>,
709         offset: u64,
710         layout: TyAndLayout<'tcx>,
711     ) -> InterpResult<'tcx, Scalar<Provenance>> {
712         let this = self.eval_context_ref();
713         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
714         this.read_scalar(&value_place.into())
715     }
716
717     fn write_scalar_at_offset(
718         &mut self,
719         op: &OpTy<'tcx, Provenance>,
720         offset: u64,
721         value: impl Into<Scalar<Provenance>>,
722         layout: TyAndLayout<'tcx>,
723     ) -> InterpResult<'tcx, ()> {
724         let this = self.eval_context_mut();
725         let value_place = this.deref_operand_and_offset(op, offset, layout)?;
726         this.write_scalar(value, &value_place.into())
727     }
728
729     /// Parse a `timespec` struct and return it as a `std::time::Duration`. It returns `None`
730     /// if the value in the `timespec` struct is invalid. Some libc functions will return
731     /// `EINVAL` in this case.
732     fn read_timespec(
733         &mut self,
734         tp: &MPlaceTy<'tcx, Provenance>,
735     ) -> InterpResult<'tcx, Option<Duration>> {
736         let this = self.eval_context_mut();
737         let seconds_place = this.mplace_field(tp, 0)?;
738         let seconds_scalar = this.read_scalar(&seconds_place.into())?;
739         let seconds = seconds_scalar.to_machine_isize(this)?;
740         let nanoseconds_place = this.mplace_field(tp, 1)?;
741         let nanoseconds_scalar = this.read_scalar(&nanoseconds_place.into())?;
742         let nanoseconds = nanoseconds_scalar.to_machine_isize(this)?;
743
744         Ok(try {
745             // tv_sec must be non-negative.
746             let seconds: u64 = seconds.try_into().ok()?;
747             // tv_nsec must be non-negative.
748             let nanoseconds: u32 = nanoseconds.try_into().ok()?;
749             if nanoseconds >= 1_000_000_000 {
750                 // tv_nsec must not be greater than 999,999,999.
751                 None?
752             }
753             Duration::new(seconds, nanoseconds)
754         })
755     }
756
757     /// Read a sequence of bytes until the first null terminator.
758     fn read_c_str<'a>(&'a self, ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, &'a [u8]>
759     where
760         'tcx: 'a,
761         'mir: 'a,
762     {
763         let this = self.eval_context_ref();
764         let size1 = Size::from_bytes(1);
765
766         // Step 1: determine the length.
767         let mut len = Size::ZERO;
768         loop {
769             // FIXME: We are re-getting the allocation each time around the loop.
770             // Would be nice if we could somehow "extend" an existing AllocRange.
771             let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1, Align::ONE)?.unwrap(); // not a ZST, so we will get a result
772             let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
773             if byte == 0 {
774                 break;
775             } else {
776                 len += size1;
777             }
778         }
779
780         // Step 2: get the bytes.
781         this.read_bytes_ptr_strip_provenance(ptr, len)
782     }
783
784     /// Helper function to write a sequence of bytes with an added null-terminator, which is what
785     /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
786     /// to write if `size` is not large enough to fit the contents of `c_str` plus a null
787     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
788     /// string length returned does include the null terminator.
789     fn write_c_str(
790         &mut self,
791         c_str: &[u8],
792         ptr: Pointer<Option<Provenance>>,
793         size: u64,
794     ) -> InterpResult<'tcx, (bool, u64)> {
795         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
796         // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
797         let string_length = u64::try_from(c_str.len()).unwrap();
798         let string_length = string_length.checked_add(1).unwrap();
799         if size < string_length {
800             return Ok((false, string_length));
801         }
802         self.eval_context_mut()
803             .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
804         Ok((true, string_length))
805     }
806
807     /// Read a sequence of u16 until the first null terminator.
808     fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {
809         let this = self.eval_context_ref();
810         let size2 = Size::from_bytes(2);
811         let align2 = Align::from_bytes(2).unwrap();
812
813         let mut wchars = Vec::new();
814         loop {
815             // FIXME: We are re-getting the allocation each time around the loop.
816             // Would be nice if we could somehow "extend" an existing AllocRange.
817             let alloc = this.get_ptr_alloc(ptr, size2, align2)?.unwrap(); // not a ZST, so we will get a result
818             let wchar = alloc.read_integer(alloc_range(Size::ZERO, size2))?.to_u16()?;
819             if wchar == 0 {
820                 break;
821             } else {
822                 wchars.push(wchar);
823                 ptr = ptr.offset(size2, this)?;
824             }
825         }
826
827         Ok(wchars)
828     }
829
830     /// Helper function to write a sequence of u16 with an added 0x0000-terminator, which is what
831     /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
832     /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
833     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
834     /// string length returned does include the null terminator. Length is measured in units of
835     /// `u16.`
836     fn write_wide_str(
837         &mut self,
838         wide_str: &[u16],
839         ptr: Pointer<Option<Provenance>>,
840         size: u64,
841     ) -> InterpResult<'tcx, (bool, u64)> {
842         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
843         // 0x0000 terminator to memory would cause an out-of-bounds access.
844         let string_length = u64::try_from(wide_str.len()).unwrap();
845         let string_length = string_length.checked_add(1).unwrap();
846         if size < string_length {
847             return Ok((false, string_length));
848         }
849
850         // Store the UTF-16 string.
851         let size2 = Size::from_bytes(2);
852         let this = self.eval_context_mut();
853         let mut alloc = this
854             .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
855             .unwrap(); // not a ZST, so we will get a result
856         for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
857             let offset = u64::try_from(offset).unwrap();
858             alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
859         }
860         Ok((true, string_length))
861     }
862
863     /// Check that the ABI is what we expect.
864     fn check_abi<'a>(&self, abi: Abi, exp_abi: Abi) -> InterpResult<'a, ()> {
865         if self.eval_context_ref().machine.enforce_abi && abi != exp_abi {
866             throw_ub_format!(
867                 "calling a function with ABI {} using caller ABI {}",
868                 exp_abi.name(),
869                 abi.name()
870             )
871         }
872         Ok(())
873     }
874
875     fn frame_in_std(&self) -> bool {
876         let this = self.eval_context_ref();
877         let Some(start_fn) = this.tcx.lang_items().start_fn() else {
878             // no_std situations
879             return false;
880         };
881         let frame = this.frame();
882         // Make an attempt to get at the instance of the function this is inlined from.
883         let instance: Option<_> = try {
884             let scope = frame.current_source_info()?.scope;
885             let inlined_parent = frame.body.source_scopes[scope].inlined_parent_scope?;
886             let source = &frame.body.source_scopes[inlined_parent];
887             source.inlined.expect("inlined_parent_scope points to scope without inline info").0
888         };
889         // Fall back to the instance of the function itself.
890         let instance = instance.unwrap_or(frame.instance);
891         // Now check if this is in the same crate as start_fn.
892         // As a special exception we also allow unit tests from
893         // <https://github.com/rust-lang/miri-test-libstd/tree/master/std_miri_test> to call these
894         // shims.
895         let frame_crate = this.tcx.def_path(instance.def_id()).krate;
896         frame_crate == this.tcx.def_path(start_fn).krate
897             || this.tcx.crate_name(frame_crate).as_str() == "std_miri_test"
898     }
899
900     /// Handler that should be called when unsupported functionality is encountered.
901     /// This function will either panic within the context of the emulated application
902     /// or return an error in the Miri process context
903     ///
904     /// Return value of `Ok(bool)` indicates whether execution should continue.
905     fn handle_unsupported<S: AsRef<str>>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> {
906         let this = self.eval_context_mut();
907         if this.machine.panic_on_unsupported {
908             // message is slightly different here to make automated analysis easier
909             let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref());
910             this.start_panic(error_msg.as_ref(), StackPopUnwind::Skip)?;
911             Ok(())
912         } else {
913             throw_unsup_format!("{}", error_msg.as_ref());
914         }
915     }
916
917     fn check_abi_and_shim_symbol_clash(
918         &mut self,
919         abi: Abi,
920         exp_abi: Abi,
921         link_name: Symbol,
922     ) -> InterpResult<'tcx, ()> {
923         self.check_abi(abi, exp_abi)?;
924         if let Some((body, _)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
925             throw_machine_stop!(TerminationInfo::SymbolShimClashing {
926                 link_name,
927                 span: body.span.data(),
928             })
929         }
930         Ok(())
931     }
932
933     fn check_shim<'a, const N: usize>(
934         &mut self,
935         abi: Abi,
936         exp_abi: Abi,
937         link_name: Symbol,
938         args: &'a [OpTy<'tcx, Provenance>],
939     ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
940     where
941         &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
942     {
943         self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
944         check_arg_count(args)
945     }
946
947     /// Mark a machine allocation that was just created as immutable.
948     fn mark_immutable(&mut self, mplace: &MemPlace<Provenance>) {
949         let this = self.eval_context_mut();
950         // This got just allocated, so there definitely is a pointer here.
951         let provenance = mplace.ptr.into_pointer_or_addr().unwrap().provenance;
952         this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
953     }
954
955     fn item_link_name(&self, def_id: DefId) -> Symbol {
956         let tcx = self.eval_context_ref().tcx;
957         match tcx.get_attrs(def_id, sym::link_name).filter_map(|a| a.value_str()).next() {
958             Some(name) => name,
959             None => tcx.item_name(def_id),
960         }
961     }
962 }
963
964 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
965     /// Get the current span in the topmost function which is workspace-local and not
966     /// `#[track_caller]`.
967     /// This function is backed by a cache, and can be assumed to be very fast.
968     /// It will work even when the stack is empty.
969     pub fn current_span(&self) -> Span {
970         self.top_user_relevant_frame()
971             .map(|frame_idx| self.stack()[frame_idx].current_span())
972             .unwrap_or(rustc_span::DUMMY_SP)
973     }
974
975     /// Returns the span of the *caller* of the current operation, again
976     /// walking down the stack to find the closest frame in a local crate, if the caller of the
977     /// current operation is not in a local crate.
978     /// This is useful when we are processing something which occurs on function-entry and we want
979     /// to point at the call to the function, not the function definition generally.
980     pub fn caller_span(&self) -> Span {
981         // We need to go down at least to the caller (len - 2), or however
982         // far we have to go to find a frame in a local crate which is also not #[track_caller].
983         let frame_idx = self.top_user_relevant_frame().unwrap();
984         let frame_idx = cmp::min(frame_idx, self.stack().len().checked_sub(2).unwrap());
985         self.stack()[frame_idx].current_span()
986     }
987
988     fn stack(&self) -> &[Frame<'mir, 'tcx, Provenance, machine::FrameExtra<'tcx>>] {
989         self.threads.active_thread_stack()
990     }
991
992     fn top_user_relevant_frame(&self) -> Option<usize> {
993         self.threads.active_thread_ref().top_user_relevant_frame()
994     }
995
996     /// This is the source of truth for the `is_user_relevant` flag in our `FrameExtra`.
997     pub fn is_user_relevant(&self, frame: &Frame<'mir, 'tcx, Provenance>) -> bool {
998         let def_id = frame.instance.def_id();
999         (def_id.is_local() || self.local_crates.contains(&def_id.krate))
1000             && !frame.instance.def.requires_caller_location(self.tcx)
1001     }
1002 }
1003
1004 /// Check that the number of args is what we expect.
1005 pub fn check_arg_count<'a, 'tcx, const N: usize>(
1006     args: &'a [OpTy<'tcx, Provenance>],
1007 ) -> InterpResult<'tcx, &'a [OpTy<'tcx, Provenance>; N]>
1008 where
1009     &'a [OpTy<'tcx, Provenance>; N]: TryFrom<&'a [OpTy<'tcx, Provenance>]>,
1010 {
1011     if let Ok(ops) = args.try_into() {
1012         return Ok(ops);
1013     }
1014     throw_ub_format!("incorrect number of arguments: got {}, expected {}", args.len(), N)
1015 }
1016
1017 pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1018     throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1019         "{name} not available when isolation is enabled",
1020     )))
1021 }
1022
1023 /// Retrieve the list of local crates that should have been passed by cargo-miri in
1024 /// MIRI_LOCAL_CRATES and turn them into `CrateNum`s.
1025 pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
1026     // Convert the local crate names from the passed-in config into CrateNums so that they can
1027     // be looked up quickly during execution
1028     let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
1029         .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
1030         .unwrap_or_default();
1031     let mut local_crates = Vec::new();
1032     for &crate_num in tcx.crates(()) {
1033         let name = tcx.crate_name(crate_num);
1034         let name = name.as_str();
1035         if local_crate_names.iter().any(|local_name| local_name == name) {
1036             local_crates.push(crate_num);
1037         }
1038     }
1039     local_crates
1040 }
1041
1042 /// Helper function used inside the shims of foreign functions to check that
1043 /// `target_os` is a supported UNIX OS.
1044 pub fn target_os_is_unix(target_os: &str) -> bool {
1045     matches!(target_os, "linux" | "macos" | "freebsd" | "android")
1046 }