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