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