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