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