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