1 use std::ffi::{OsStr, OsString};
2 use std::path::{Path, PathBuf};
4 use std::convert::TryFrom;
8 use std::os::unix::ffi::{OsStrExt, OsStringExt};
10 use std::os::windows::ffi::{OsStrExt, OsStringExt};
15 layout::{self, LayoutOf, Size, TyLayout},
18 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
19 use rustc_span::source_map::DUMMY_SP;
25 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
27 /// Gets an instance for a path.
28 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
31 .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
33 let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX };
34 let mut items = tcx.item_children(krate);
35 let mut path_it = path.iter().skip(1).peekable();
37 while let Some(segment) = path_it.next() {
38 for item in mem::replace(&mut items, Default::default()).iter() {
39 if item.ident.name.as_str() == *segment {
40 if path_it.peek().is_none() {
41 return Some(item.res.def_id());
44 items = tcx.item_children(item.res.def_id());
53 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
54 /// Gets an instance for a path.
55 fn resolve_path(&self, path: &[&str]) -> ty::Instance<'tcx> {
56 let did = try_resolve_did(self.eval_context_ref().tcx.tcx, path)
57 .unwrap_or_else(|| panic!("failed to find required Rust item: {:?}", path));
58 ty::Instance::mono(self.eval_context_ref().tcx.tcx, did)
61 /// Evaluates the scalar at the specified path. Returns Some(val)
62 /// if the path could be resolved, and None otherwise
66 ) -> InterpResult<'tcx, ScalarMaybeUndef<Tag>> {
67 let this = self.eval_context_mut();
68 let instance = this.resolve_path(path);
69 let cid = GlobalId { instance, promoted: None };
70 let const_val = this.const_eval_raw(cid)?;
71 let const_val = this.read_scalar(const_val.into())?;
75 /// Helper function to get a `libc` constant as a `Scalar`.
76 fn eval_libc(&mut self, name: &str) -> InterpResult<'tcx, Scalar<Tag>> {
77 self.eval_context_mut()
78 .eval_path_scalar(&["libc", name])?
82 /// Helper function to get a `libc` constant as an `i32`.
83 fn eval_libc_i32(&mut self, name: &str) -> InterpResult<'tcx, i32> {
84 // TODO: Cache the result.
85 self.eval_libc(name)?.to_i32()
88 /// Helper function to get the `TyLayout` of a `libc` type
89 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
90 let this = self.eval_context_mut();
91 let ty = this.resolve_path(&["libc", name]).monomorphic_ty(*this.tcx);
95 /// Write a 0 of the appropriate size to `dest`.
96 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
97 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
100 /// Test if this immediate equals 0.
101 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
102 let this = self.eval_context_ref();
103 let null = Scalar::from_int(0, this.memory.pointer_size());
104 this.ptr_eq(val, null)
107 /// Turn a Scalar into an Option<NonNullScalar>
108 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
109 let this = self.eval_context_ref();
110 Ok(if this.is_null(val)? { None } else { Some(val) })
113 /// Get the `Place` for a local
114 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
115 let this = self.eval_context_mut();
116 let place = mir::Place { local: local, projection: List::empty() };
117 this.eval_place(&place)
120 /// Generate some random bytes, and write them to `dest`.
121 fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
122 // Some programs pass in a null pointer and a length of 0
123 // to their platform's random-generation function (e.g. getrandom())
124 // on Linux. For compatibility with these programs, we don't perform
125 // any additional checks - it's okay if the pointer is invalid,
126 // since we wouldn't actually be writing to it.
130 let this = self.eval_context_mut();
132 let mut data = vec![0; usize::try_from(len).unwrap()];
134 if this.machine.communicate {
135 // Fill the buffer using the host's rng.
136 getrandom::getrandom(&mut data)
137 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
139 let rng = this.memory.extra.rng.get_mut();
140 rng.fill_bytes(&mut data);
143 this.memory.write_bytes(ptr, data.iter().copied())
146 /// Call a function: Push the stack frame and pass the arguments.
147 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
150 f: ty::Instance<'tcx>,
151 args: &[Immediate<Tag>],
152 dest: Option<PlaceTy<'tcx, Tag>>,
153 stack_pop: StackPopCleanup,
154 ) -> InterpResult<'tcx> {
155 let this = self.eval_context_mut();
158 let mir = &*this.load_mir(f.def, None)?;
162 .and_then(Frame::current_source_info)
164 .unwrap_or(DUMMY_SP);
165 this.push_stack_frame(f, span, mir, dest, stack_pop)?;
167 // Initialize arguments.
168 let mut callee_args = this.frame().body.args_iter();
170 let callee_arg = this.local_place(
171 callee_args.next().expect("callee has fewer arguments than expected"),
173 this.write_immediate(*arg, callee_arg)?;
175 callee_args.next().expect_none("callee has more arguments than expected");
180 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
181 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
182 fn visit_freeze_sensitive(
184 place: MPlaceTy<'tcx, Tag>,
186 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
187 ) -> InterpResult<'tcx> {
188 let this = self.eval_context_ref();
189 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
192 this.size_and_align_of_mplace(place)?
193 .map(|(size, _)| size)
194 .unwrap_or_else(|| place.layout.size)
196 // Store how far we proceeded into the place so far. Everything to the left of
197 // this offset has already been handled, in the sense that the frozen parts
198 // have had `action` called on them.
199 let mut end_ptr = place.ptr.assert_ptr();
200 // Called when we detected an `UnsafeCell` at the given offset and size.
201 // Calls `action` and advances `end_ptr`.
202 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
203 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
204 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
205 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
206 // We assume that we are given the fields in increasing offset order,
207 // and nothing else changes.
208 let unsafe_cell_offset = unsafe_cell_ptr.offset;
209 let end_offset = end_ptr.offset;
210 assert!(unsafe_cell_offset >= end_offset);
211 let frozen_size = unsafe_cell_offset - end_offset;
212 // Everything between the end_ptr and this `UnsafeCell` is frozen.
213 if frozen_size != Size::ZERO {
214 action(end_ptr, frozen_size, /*frozen*/ true)?;
216 // This `UnsafeCell` is NOT frozen.
217 if unsafe_cell_size != Size::ZERO {
218 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
220 // Update end end_ptr.
221 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
227 let mut visitor = UnsafeCellVisitor {
229 unsafe_cell_action: |place| {
230 trace!("unsafe_cell_action on {:?}", place.ptr);
231 // We need a size to go on.
232 let unsafe_cell_size = this
233 .size_and_align_of_mplace(place)?
234 .map(|(size, _)| size)
235 // for extern types, just cover what we can
236 .unwrap_or_else(|| place.layout.size);
237 // Now handle this `UnsafeCell`, unless it is empty.
238 if unsafe_cell_size != Size::ZERO {
239 unsafe_cell_action(place.ptr, unsafe_cell_size)
245 visitor.visit_value(place)?;
247 // The part between the end_ptr and the end of the place is also frozen.
248 // So pretend there is a 0-sized `UnsafeCell` at the end.
249 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
253 /// Visiting the memory covered by a `MemPlace`, being aware of
254 /// whether we are inside an `UnsafeCell` or not.
255 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
257 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
259 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
260 unsafe_cell_action: F,
263 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
264 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
266 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
268 type V = MPlaceTy<'tcx, Tag>;
271 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
275 // Hook to detect `UnsafeCell`.
276 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
277 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
278 let is_unsafe_cell = match v.layout.ty.kind {
280 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
284 // We do not have to recurse further, this is an `UnsafeCell`.
285 (self.unsafe_cell_action)(v)
286 } else if self.ecx.type_is_freeze(v.layout.ty) {
287 // This is `Freeze`, there cannot be an `UnsafeCell`
290 // We want to not actually read from memory for this visit. So, before
291 // walking this value, we have to make sure it is not a
292 // `Variants::Multiple`.
293 match v.layout.variants {
294 layout::Variants::Multiple { .. } => {
295 // A multi-variant enum, or generator, or so.
296 // Treat this like a union: without reading from memory,
297 // we cannot determine the variant we are in. Reading from
298 // memory would be subject to Stacked Borrows rules, leading
299 // to all sorts of "funny" recursion.
300 // We only end up here if the type is *not* freeze, so we just call the
301 // `UnsafeCell` action.
302 (self.unsafe_cell_action)(v)
304 layout::Variants::Single { .. } => {
305 // Proceed further, try to find where exactly that `UnsafeCell`
313 // Make sure we visit aggregrates in increasing offset order.
316 place: MPlaceTy<'tcx, Tag>,
317 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
318 ) -> InterpResult<'tcx> {
319 match place.layout.fields {
320 layout::FieldPlacement::Array { .. } => {
321 // For the array layout, we know the iterator will yield sorted elements so
322 // we can avoid the allocation.
323 self.walk_aggregate(place, fields)
325 layout::FieldPlacement::Arbitrary { .. } => {
326 // Gather the subplaces and sort them before visiting.
328 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
329 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
330 self.walk_aggregate(place, places.into_iter().map(Ok))
332 layout::FieldPlacement::Union { .. } => {
334 bug!("a union is not an aggregate we should ever visit")
339 // We have to do *something* for unions.
340 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>, fields: usize) -> InterpResult<'tcx> {
341 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
343 // With unions, we fall back to whatever the type says, to hopefully be consistent
345 // FIXME: are we consistent, and is this really the behavior we want?
346 let frozen = self.ecx.type_is_freeze(v.layout.ty);
347 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
352 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
353 // different values into a struct.
354 fn write_packed_immediates(
356 place: MPlaceTy<'tcx, Tag>,
357 imms: &[ImmTy<'tcx, Tag>],
358 ) -> InterpResult<'tcx> {
359 let this = self.eval_context_mut();
361 let mut offset = Size::from_bytes(0);
364 this.write_immediate_to_mplace(
366 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
368 offset += imm.layout.size;
373 /// Helper function used inside the shims of foreign functions to check that isolation is
374 /// disabled. It returns an error using the `name` of the foreign function if this is not the
376 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
377 if !self.eval_context_ref().machine.communicate {
378 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
379 "`{}` not available when isolation is enabled",
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) {
390 self.eval_context_ref().tcx.sess.target.target.target_os,
392 "`{}` is only available on the `{}` target OS",
398 /// Sets the last error variable.
399 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
400 let this = self.eval_context_mut();
401 let errno_place = this.machine.last_error.unwrap();
402 this.write_scalar(scalar, errno_place.into())
405 /// Gets the last error variable.
406 fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
407 let this = self.eval_context_ref();
408 let errno_place = this.machine.last_error.unwrap();
409 this.read_scalar(errno_place.into())?.not_undef()
412 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
413 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
414 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
415 use std::io::ErrorKind::*;
416 let this = self.eval_context_mut();
417 let target = &this.tcx.sess.target.target;
418 let last_error = if target.options.target_family == Some("unix".to_owned()) {
419 this.eval_libc(match e.kind() {
420 ConnectionRefused => "ECONNREFUSED",
421 ConnectionReset => "ECONNRESET",
422 PermissionDenied => "EPERM",
423 BrokenPipe => "EPIPE",
424 NotConnected => "ENOTCONN",
425 ConnectionAborted => "ECONNABORTED",
426 AddrNotAvailable => "EADDRNOTAVAIL",
427 AddrInUse => "EADDRINUSE",
428 NotFound => "ENOENT",
429 Interrupted => "EINTR",
430 InvalidInput => "EINVAL",
431 TimedOut => "ETIMEDOUT",
432 AlreadyExists => "EEXIST",
433 WouldBlock => "EWOULDBLOCK",
435 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
439 // FIXME: we have to implement the Windows equivalent of this.
441 "setting the last OS error from an io::Error is unsupported for {}.",
445 this.set_last_error(last_error)
448 /// Helper function that consumes an `std::io::Result<T>` and returns an
449 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
450 /// `Ok(-1)` and sets the last OS error accordingly.
452 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
453 /// functions return different integer types (like `read`, that returns an `i64`).
454 fn try_unwrap_io_result<T: From<i32>>(
456 result: std::io::Result<T>,
457 ) -> InterpResult<'tcx, T> {
461 self.eval_context_mut().set_last_error_from_io_error(e)?;
467 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
468 /// the Unix APIs usually handle.
469 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
475 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
476 Ok(OsStr::from_bytes(bytes))
479 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
480 let s = std::str::from_utf8(bytes)
481 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
485 let this = self.eval_context_ref();
486 let bytes = this.memory.read_c_str(scalar)?;
487 bytes_to_os_str(bytes)
490 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
491 /// which is what the Windows APIs usually handle.
492 fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
498 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
499 Ok(OsString::from_wide(&u16_vec[..]))
502 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
503 let s = String::from_utf16(&u16_vec[..])
504 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
508 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
509 u16vec_to_osstring(u16_vec)
512 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
513 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
514 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
515 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
516 /// string length returned does not include the null terminator.
517 fn write_os_str_to_c_str(
522 ) -> InterpResult<'tcx, (bool, u64)> {
524 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
525 Ok(os_str.as_bytes())
528 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
529 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
530 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
534 .map(|s| s.as_bytes())
535 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
538 let bytes = os_str_to_bytes(os_str)?;
539 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
540 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
541 let string_length = u64::try_from(bytes.len()).unwrap();
542 if size <= string_length {
543 return Ok((false, string_length));
545 self.eval_context_mut()
547 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
548 Ok((true, string_length))
551 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
552 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
553 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
554 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
555 /// string length returned does not include the null terminator.
556 fn write_os_str_to_wide_str(
561 ) -> InterpResult<'tcx, (bool, u64)> {
563 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
564 Ok(os_str.encode_wide().collect())
567 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
568 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
569 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
573 .map(|s| s.encode_utf16().collect())
574 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
577 let u16_vec = os_str_to_u16vec(os_str)?;
578 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
579 // 0x0000 terminator to memory would cause an out-of-bounds access.
580 let string_length = u64::try_from(u16_vec.len()).unwrap();
581 if size <= string_length {
582 return Ok((false, string_length));
585 // Store the UTF-16 string.
586 self.eval_context_mut()
588 .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
589 Ok((true, string_length))
592 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
593 fn alloc_os_str_as_c_str(
596 memkind: MemoryKind<MiriMemoryKind>,
598 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
599 let this = self.eval_context_mut();
601 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
602 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
603 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
604 arg_place.ptr.assert_ptr()
607 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
608 fn alloc_os_str_as_wide_str(
611 memkind: MemoryKind<MiriMemoryKind>,
613 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
614 let this = self.eval_context_mut();
616 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
617 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
618 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
619 arg_place.ptr.assert_ptr()
622 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
623 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
628 let this = self.eval_context_ref();
629 let os_str = this.read_os_str_from_c_str(scalar)?;
632 return Ok(if this.tcx.sess.target.target.target_os == "windows" {
633 // Windows-on-Windows, all fine.
634 Cow::Borrowed(Path::new(os_str))
636 // Unix target, Windows host. Need to convert target '/' to host '\'.
637 let converted = os_str
639 .map(|wchar| if wchar == '/' as u16 { '\\' as u16 } else { wchar })
640 .collect::<Vec<_>>();
641 Cow::Owned(PathBuf::from(OsString::from_wide(&converted)))
644 return Ok(if this.tcx.sess.target.target.target_os == "windows" {
645 // Windows target, Unix host. Need to convert target '\' to host '/'.
646 let converted = os_str
649 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
650 .collect::<Vec<_>>();
651 Cow::Owned(PathBuf::from(OsString::from_vec(converted)))
653 // Unix-on-Unix, all is fine.
654 Cow::Borrowed(Path::new(os_str))
658 /// Write a Path to the machine memory, adjusting path separators if needed.
659 fn write_path_to_c_str(
664 ) -> InterpResult<'tcx, (bool, u64)> {
665 let this = self.eval_context_mut();
668 let os_str = if this.tcx.sess.target.target.target_os == "windows" {
669 // Windows-on-Windows, all fine.
670 Cow::Borrowed(path.as_os_str())
672 // Unix target, Windows host. Need to convert host '\\' to target '/'.
676 .map(|wchar| if wchar == '\\' as u16 { '/' as u16 } else { wchar })
677 .collect::<Vec<_>>();
678 Cow::Owned(OsString::from_wide(&converted))
681 let os_str = if this.tcx.sess.target.target.target_os == "windows" {
682 // Windows target, Unix host. Need to convert host '/' to target '\'.
687 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
688 .collect::<Vec<_>>();
689 Cow::Owned(OsString::from_vec(converted))
691 // Unix-on-Unix, all is fine.
692 Cow::Borrowed(path.as_os_str())
695 this.write_os_str_to_c_str(&os_str, scalar, size)
699 pub fn immty_from_int_checked<'tcx>(
700 int: impl Into<i128>,
701 layout: TyLayout<'tcx>,
702 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
703 let int = int.into();
704 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
705 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
709 pub fn immty_from_uint_checked<'tcx>(
710 int: impl Into<u128>,
711 layout: TyLayout<'tcx>,
712 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
713 let int = int.into();
714 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
715 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())