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