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