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