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