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