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