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