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