1 use std::ffi::{OsStr, OsString};
4 use std::convert::TryFrom;
10 layout::{self, LayoutOf, Size, TyLayout},
13 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
14 use rustc_span::source_map::DUMMY_SP;
20 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
22 /// Gets an instance for a path.
23 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
26 .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
28 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
29 let mut items = tcx.item_children(krate);
30 let mut path_it = path.iter().skip(1).peekable();
32 while let Some(segment) = path_it.next() {
33 for item in mem::replace(&mut items, Default::default()).iter() {
34 if item.ident.name.as_str() == *segment {
35 if path_it.peek().is_none() {
36 return Some(item.res.def_id());
39 items = tcx.item_children(item.res.def_id());
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)
56 /// Evaluates the scalar at the specified path. Returns Some(val)
57 /// if the path could be resolved, and None otherwise
61 ) -> InterpResult<'tcx, ScalarMaybeUndef<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())?;
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])?
77 /// Helper function to get a `libc` constant as an `i32`.
78 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
79 self.eval_libc(name)?.to_i32()
82 /// Helper function to get the `TyLayout` of a `libc` type
83 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
84 let this = self.eval_context_mut();
85 let ty = this.resolve_path(&["libc", name]).monomorphic_ty(*this.tcx);
89 /// Write a 0 of the appropriate size to `dest`.
90 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
91 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
94 /// Test if this immediate equals 0.
95 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
96 let this = self.eval_context_ref();
97 let null = Scalar::from_int(0, this.memory.pointer_size());
98 this.ptr_eq(val, null)
101 /// Turn a Scalar into an Option<NonNullScalar>
102 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
103 let this = self.eval_context_ref();
104 Ok(if this.is_null(val)? { None } else { Some(val) })
107 /// Get the `Place` for a local
108 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
109 let this = self.eval_context_mut();
110 let place = mir::Place { local: local, projection: List::empty() };
111 this.eval_place(&place)
114 /// Generate some random bytes, and write them to `dest`.
115 fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
116 // Some programs pass in a null pointer and a length of 0
117 // to their platform's random-generation function (e.g. getrandom())
118 // on Linux. For compatibility with these programs, we don't perform
119 // any additional checks - it's okay if the pointer is invalid,
120 // since we wouldn't actually be writing to it.
124 let this = self.eval_context_mut();
126 let mut data = vec![0; usize::try_from(len).unwrap()];
128 if this.machine.communicate {
129 // Fill the buffer using the host's rng.
130 getrandom::getrandom(&mut data)
131 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
133 let rng = this.memory.extra.rng.get_mut();
134 rng.fill_bytes(&mut data);
137 this.memory.write_bytes(ptr, data.iter().copied())
140 /// Call a function: Push the stack frame and pass the arguments.
141 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
144 f: ty::Instance<'tcx>,
145 args: &[Immediate<Tag>],
146 dest: Option<PlaceTy<'tcx, Tag>>,
147 stack_pop: StackPopCleanup,
148 ) -> InterpResult<'tcx> {
149 let this = self.eval_context_mut();
152 let mir = &*this.load_mir(f.def, None)?;
156 .and_then(Frame::current_source_info)
158 .unwrap_or(DUMMY_SP);
159 this.push_stack_frame(f, span, mir, dest, stack_pop)?;
161 // Initialize arguments.
162 let mut callee_args = this.frame().body.args_iter();
164 let callee_arg = this.local_place(
165 callee_args.next().expect("callee has fewer arguments than expected"),
167 this.write_immediate(*arg, callee_arg)?;
169 callee_args.next().expect_none("callee has more arguments than expected");
174 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
175 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
176 fn visit_freeze_sensitive(
178 place: MPlaceTy<'tcx, Tag>,
180 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
181 ) -> InterpResult<'tcx> {
182 let this = self.eval_context_ref();
183 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
186 this.size_and_align_of_mplace(place)?
187 .map(|(size, _)| size)
188 .unwrap_or_else(|| place.layout.size)
190 // Store how far we proceeded into the place so far. Everything to the left of
191 // this offset has already been handled, in the sense that the frozen parts
192 // have had `action` called on them.
193 let mut end_ptr = place.ptr.assert_ptr();
194 // Called when we detected an `UnsafeCell` at the given offset and size.
195 // Calls `action` and advances `end_ptr`.
196 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
197 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
198 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
199 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
200 // We assume that we are given the fields in increasing offset order,
201 // and nothing else changes.
202 let unsafe_cell_offset = unsafe_cell_ptr.offset;
203 let end_offset = end_ptr.offset;
204 assert!(unsafe_cell_offset >= end_offset);
205 let frozen_size = unsafe_cell_offset - end_offset;
206 // Everything between the end_ptr and this `UnsafeCell` is frozen.
207 if frozen_size != Size::ZERO {
208 action(end_ptr, frozen_size, /*frozen*/ true)?;
210 // This `UnsafeCell` is NOT frozen.
211 if unsafe_cell_size != Size::ZERO {
212 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
214 // Update end end_ptr.
215 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
221 let mut visitor = UnsafeCellVisitor {
223 unsafe_cell_action: |place| {
224 trace!("unsafe_cell_action on {:?}", place.ptr);
225 // We need a size to go on.
226 let unsafe_cell_size = this
227 .size_and_align_of_mplace(place)?
228 .map(|(size, _)| size)
229 // for extern types, just cover what we can
230 .unwrap_or_else(|| place.layout.size);
231 // Now handle this `UnsafeCell`, unless it is empty.
232 if unsafe_cell_size != Size::ZERO {
233 unsafe_cell_action(place.ptr, unsafe_cell_size)
239 visitor.visit_value(place)?;
241 // The part between the end_ptr and the end of the place is also frozen.
242 // So pretend there is a 0-sized `UnsafeCell` at the end.
243 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
247 /// Visiting the memory covered by a `MemPlace`, being aware of
248 /// whether we are inside an `UnsafeCell` or not.
249 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
251 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
253 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
254 unsafe_cell_action: F,
257 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
258 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
260 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
262 type V = MPlaceTy<'tcx, Tag>;
265 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
269 // Hook to detect `UnsafeCell`.
270 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
271 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
272 let is_unsafe_cell = match v.layout.ty.kind {
274 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
278 // We do not have to recurse further, this is an `UnsafeCell`.
279 (self.unsafe_cell_action)(v)
280 } else if self.ecx.type_is_freeze(v.layout.ty) {
281 // This is `Freeze`, there cannot be an `UnsafeCell`
284 // We want to not actually read from memory for this visit. So, before
285 // walking this value, we have to make sure it is not a
286 // `Variants::Multiple`.
287 match v.layout.variants {
288 layout::Variants::Multiple { .. } => {
289 // A multi-variant enum, or generator, or so.
290 // Treat this like a union: without reading from memory,
291 // we cannot determine the variant we are in. Reading from
292 // memory would be subject to Stacked Borrows rules, leading
293 // to all sorts of "funny" recursion.
294 // We only end up here if the type is *not* freeze, so we just call the
295 // `UnsafeCell` action.
296 (self.unsafe_cell_action)(v)
298 layout::Variants::Single { .. } => {
299 // Proceed further, try to find where exactly that `UnsafeCell`
307 // Make sure we visit aggregrates in increasing offset order.
310 place: MPlaceTy<'tcx, Tag>,
311 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
312 ) -> InterpResult<'tcx> {
313 match place.layout.fields {
314 layout::FieldPlacement::Array { .. } => {
315 // For the array layout, we know the iterator will yield sorted elements so
316 // we can avoid the allocation.
317 self.walk_aggregate(place, fields)
319 layout::FieldPlacement::Arbitrary { .. } => {
320 // Gather the subplaces and sort them before visiting.
322 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
323 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
324 self.walk_aggregate(place, places.into_iter().map(Ok))
326 layout::FieldPlacement::Union { .. } => {
328 bug!("a union is not an aggregate we should ever visit")
333 // We have to do *something* for unions.
334 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>, fields: usize) -> InterpResult<'tcx> {
335 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
337 // With unions, we fall back to whatever the type says, to hopefully be consistent
339 // FIXME: are we consistent, and is this really the behavior we want?
340 let frozen = self.ecx.type_is_freeze(v.layout.ty);
341 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
346 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
347 // different values into a struct.
348 fn write_packed_immediates(
350 place: MPlaceTy<'tcx, Tag>,
351 imms: &[ImmTy<'tcx, Tag>],
352 ) -> InterpResult<'tcx> {
353 let this = self.eval_context_mut();
355 let mut offset = Size::from_bytes(0);
358 this.write_immediate_to_mplace(
360 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
362 offset += imm.layout.size;
367 /// Helper function used inside the shims of foreign functions to check that isolation is
368 /// disabled. It returns an error using the `name` of the foreign function if this is not the
370 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
371 if !self.eval_context_ref().machine.communicate {
372 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
373 "`{}` not available when isolation is enabled",
379 /// Helper function used inside the shims of foreign functions to assert that the target OS
380 /// is `target_os`. It panics showing a message with the `name` of the foreign function
381 /// if this is not the case.
382 fn assert_target_os(&self, target_os: &str, name: &str) {
384 self.eval_context_ref().tcx.sess.target.target.target_os,
386 "`{}` is only available on the `{}` target OS",
392 /// Sets the last error variable.
393 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
394 let this = self.eval_context_mut();
395 let errno_place = this.machine.last_error.unwrap();
396 this.write_scalar(scalar, errno_place.into())
399 /// Gets the last error variable.
400 fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
401 let this = self.eval_context_ref();
402 let errno_place = this.machine.last_error.unwrap();
403 this.read_scalar(errno_place.into())?.not_undef()
406 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
407 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
408 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
409 use std::io::ErrorKind::*;
410 let this = self.eval_context_mut();
411 let target = &this.tcx.tcx.sess.target.target;
412 let last_error = if target.options.target_family == Some("unix".to_owned()) {
413 this.eval_libc(match e.kind() {
414 ConnectionRefused => "ECONNREFUSED",
415 ConnectionReset => "ECONNRESET",
416 PermissionDenied => "EPERM",
417 BrokenPipe => "EPIPE",
418 NotConnected => "ENOTCONN",
419 ConnectionAborted => "ECONNABORTED",
420 AddrNotAvailable => "EADDRNOTAVAIL",
421 AddrInUse => "EADDRINUSE",
422 NotFound => "ENOENT",
423 Interrupted => "EINTR",
424 InvalidInput => "EINVAL",
425 TimedOut => "ETIMEDOUT",
426 AlreadyExists => "EEXIST",
427 WouldBlock => "EWOULDBLOCK",
429 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
433 // FIXME: we have to implement the Windows equivalent of this.
435 "setting the last OS error from an io::Error is unsupported for {}.",
439 this.set_last_error(last_error)
442 /// Helper function that consumes an `std::io::Result<T>` and returns an
443 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
444 /// `Ok(-1)` and sets the last OS error accordingly.
446 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
447 /// functions return different integer types (like `read`, that returns an `i64`).
448 fn try_unwrap_io_result<T: From<i32>>(
450 result: std::io::Result<T>,
451 ) -> InterpResult<'tcx, T> {
455 self.eval_context_mut().set_last_error_from_io_error(e)?;
461 /// Dispatches to appropriate implementations for reading an OsString from Memory,
462 /// depending on the interpretation target.
463 /// FIXME: Use `Cow` to avoid copies
464 fn read_os_str_from_target_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString> {
465 let target_os = self.eval_context_ref().tcx.sess.target.target.target_os.as_str();
467 "linux" | "macos" => self.read_os_str_from_c_str(scalar).map(|x| x.to_os_string()),
468 "windows" => self.read_os_str_from_wide_str(scalar),
469 unsupported => throw_unsup_format!("OsString support for target OS `{}` not yet available", unsupported),
473 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
474 /// the Unix APIs usually handle.
475 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
481 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
482 Ok(std::os::unix::ffi::OsStrExt::from_bytes(bytes))
485 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
486 let s = std::str::from_utf8(bytes)
487 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
491 let this = self.eval_context_ref();
492 let bytes = this.memory.read_c_str(scalar)?;
493 bytes_to_os_str(bytes)
496 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
497 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
502 let os_str = self.read_os_str_from_c_str(scalar)?;
503 Ok(Cow::Borrowed(Path::new(os_str)))
506 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
507 /// which is what the Windows APIs usually handle.
508 fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
514 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
515 Ok(std::os::windows::ffi::OsStringExt::from_wide(&u16_vec[..]))
518 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
519 let s = String::from_utf16(&u16_vec[..])
520 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
524 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
525 u16vec_to_osstring(u16_vec)
528 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
529 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
530 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
531 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
532 /// string length returned does not include the null terminator.
533 fn write_os_str_to_c_str(
538 ) -> InterpResult<'tcx, (bool, u64)> {
540 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
541 Ok(std::os::unix::ffi::OsStrExt::as_bytes(os_str))
544 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
545 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
546 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
550 .map(|s| s.as_bytes())
551 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
554 let bytes = os_str_to_bytes(os_str)?;
555 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
556 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
557 let string_length = u64::try_from(bytes.len()).unwrap();
558 if size <= string_length {
559 return Ok((false, string_length));
561 self.eval_context_mut()
563 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
564 Ok((true, string_length))
567 /// Write a Path to the machine memory, adjusting path separators if needed.
568 fn write_path_to_c_str(
573 ) -> InterpResult<'tcx, (bool, u64)> {
574 let os_str = path.as_os_str();
575 self.write_os_str_to_c_str(os_str, scalar, size)
578 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
579 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
580 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
581 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
582 /// string length returned does not include the null terminator.
583 fn write_os_str_to_wide_str(
586 mplace: MPlaceTy<'tcx, Tag>,
588 ) -> InterpResult<'tcx, (bool, u64)> {
590 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
591 Ok(std::os::windows::ffi::OsStrExt::encode_wide(os_str).collect())
594 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
595 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
596 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
600 .map(|s| s.encode_utf16().collect())
601 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
604 let u16_vec = os_str_to_u16vec(os_str)?;
605 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
606 // 0x0000 terminator to memory would cause an out-of-bounds access.
607 let string_length = u64::try_from(u16_vec.len()).unwrap();
608 if size <= string_length {
609 return Ok((false, string_length));
612 let this = self.eval_context_mut();
614 // Store the UTF-16 string.
615 let char_size = Size::from_bytes(2);
616 for (idx, c) in u16_vec.into_iter().chain(iter::once(0x0000)).enumerate() {
617 let place = this.mplace_field(mplace, idx as u64)?;
618 this.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
620 Ok((true, string_length))
623 /// Dispatches to appropriate implementations for allocating & writing OsString in Memory,
624 /// depending on the interpretation target.
625 fn alloc_os_str_as_target_str(
628 memkind: MemoryKind<MiriMemoryKind>,
629 ) -> InterpResult<'tcx, Pointer<Tag>> {
630 let target_os = self.eval_context_ref().tcx.sess.target.target.target_os.as_str();
632 "linux" | "macos" => Ok(self.alloc_os_str_as_c_str(os_str, memkind)),
633 "windows" => Ok(self.alloc_os_str_as_wide_str(os_str, memkind)),
634 unsupported => throw_unsup_format!("OsString support for target OS `{}` not yet available", unsupported),
638 fn alloc_os_str_as_c_str(
641 memkind: MemoryKind<MiriMemoryKind>,
643 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
644 let this = self.eval_context_mut();
646 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
647 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
648 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
649 arg_place.ptr.assert_ptr()
652 fn alloc_os_str_as_wide_str(
655 memkind: MemoryKind<MiriMemoryKind>,
657 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
658 let this = self.eval_context_mut();
660 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
661 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
662 assert!(self.write_os_str_to_wide_str(os_str, arg_place, size).unwrap().0);
663 arg_place.ptr.assert_ptr()
667 pub fn immty_from_int_checked<'tcx>(
668 int: impl Into<i128>,
669 layout: TyLayout<'tcx>,
670 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
671 let int = int.into();
672 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
673 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
677 pub fn immty_from_uint_checked<'tcx>(
678 int: impl Into<u128>,
679 layout: TyLayout<'tcx>,
680 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
681 let int = int.into();
682 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
683 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())