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