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 self.eval_libc(name)?.to_i32()
87 /// Helper function to get the `TyLayout` of a `libc` type
88 fn libc_ty_layout(&mut self, name: &str) -> InterpResult<'tcx, TyLayout<'tcx>> {
89 let this = self.eval_context_mut();
90 let ty = this.resolve_path(&["libc", name]).monomorphic_ty(*this.tcx);
94 /// Write a 0 of the appropriate size to `dest`.
95 fn write_null(&mut self, dest: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
96 self.eval_context_mut().write_scalar(Scalar::from_int(0, dest.layout.size), dest)
99 /// Test if this immediate equals 0.
100 fn is_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, bool> {
101 let this = self.eval_context_ref();
102 let null = Scalar::from_int(0, this.memory.pointer_size());
103 this.ptr_eq(val, null)
106 /// Turn a Scalar into an Option<NonNullScalar>
107 fn test_null(&self, val: Scalar<Tag>) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
108 let this = self.eval_context_ref();
109 Ok(if this.is_null(val)? { None } else { Some(val) })
112 /// Get the `Place` for a local
113 fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx, Tag>> {
114 let this = self.eval_context_mut();
115 let place = mir::Place { local: local, projection: List::empty() };
116 this.eval_place(&place)
119 /// Generate some random bytes, and write them to `dest`.
120 fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
121 // Some programs pass in a null pointer and a length of 0
122 // to their platform's random-generation function (e.g. getrandom())
123 // on Linux. For compatibility with these programs, we don't perform
124 // any additional checks - it's okay if the pointer is invalid,
125 // since we wouldn't actually be writing to it.
129 let this = self.eval_context_mut();
131 let mut data = vec![0; usize::try_from(len).unwrap()];
133 if this.machine.communicate {
134 // Fill the buffer using the host's rng.
135 getrandom::getrandom(&mut data)
136 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
138 let rng = this.memory.extra.rng.get_mut();
139 rng.fill_bytes(&mut data);
142 this.memory.write_bytes(ptr, data.iter().copied())
145 /// Call a function: Push the stack frame and pass the arguments.
146 /// For now, arguments must be scalars (so that the caller does not have to know the layout).
149 f: ty::Instance<'tcx>,
150 args: &[Immediate<Tag>],
151 dest: Option<PlaceTy<'tcx, Tag>>,
152 stack_pop: StackPopCleanup,
153 ) -> InterpResult<'tcx> {
154 let this = self.eval_context_mut();
157 let mir = &*this.load_mir(f.def, None)?;
161 .and_then(Frame::current_source_info)
163 .unwrap_or(DUMMY_SP);
164 this.push_stack_frame(f, span, mir, dest, stack_pop)?;
166 // Initialize arguments.
167 let mut callee_args = this.frame().body.args_iter();
169 let callee_arg = this.local_place(
170 callee_args.next().expect("callee has fewer arguments than expected"),
172 this.write_immediate(*arg, callee_arg)?;
174 callee_args.next().expect_none("callee has more arguments than expected");
179 /// Visits the memory covered by `place`, sensitive to freezing: the 3rd parameter
180 /// will be true if this is frozen, false if this is in an `UnsafeCell`.
181 fn visit_freeze_sensitive(
183 place: MPlaceTy<'tcx, Tag>,
185 mut action: impl FnMut(Pointer<Tag>, Size, bool) -> InterpResult<'tcx>,
186 ) -> InterpResult<'tcx> {
187 let this = self.eval_context_ref();
188 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
191 this.size_and_align_of_mplace(place)?
192 .map(|(size, _)| size)
193 .unwrap_or_else(|| place.layout.size)
195 // Store how far we proceeded into the place so far. Everything to the left of
196 // this offset has already been handled, in the sense that the frozen parts
197 // have had `action` called on them.
198 let mut end_ptr = place.ptr.assert_ptr();
199 // Called when we detected an `UnsafeCell` at the given offset and size.
200 // Calls `action` and advances `end_ptr`.
201 let mut unsafe_cell_action = |unsafe_cell_ptr: Scalar<Tag>, unsafe_cell_size: Size| {
202 let unsafe_cell_ptr = unsafe_cell_ptr.assert_ptr();
203 debug_assert_eq!(unsafe_cell_ptr.alloc_id, end_ptr.alloc_id);
204 debug_assert_eq!(unsafe_cell_ptr.tag, end_ptr.tag);
205 // We assume that we are given the fields in increasing offset order,
206 // and nothing else changes.
207 let unsafe_cell_offset = unsafe_cell_ptr.offset;
208 let end_offset = end_ptr.offset;
209 assert!(unsafe_cell_offset >= end_offset);
210 let frozen_size = unsafe_cell_offset - end_offset;
211 // Everything between the end_ptr and this `UnsafeCell` is frozen.
212 if frozen_size != Size::ZERO {
213 action(end_ptr, frozen_size, /*frozen*/ true)?;
215 // This `UnsafeCell` is NOT frozen.
216 if unsafe_cell_size != Size::ZERO {
217 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
219 // Update end end_ptr.
220 end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
226 let mut visitor = UnsafeCellVisitor {
228 unsafe_cell_action: |place| {
229 trace!("unsafe_cell_action on {:?}", place.ptr);
230 // We need a size to go on.
231 let unsafe_cell_size = this
232 .size_and_align_of_mplace(place)?
233 .map(|(size, _)| size)
234 // for extern types, just cover what we can
235 .unwrap_or_else(|| place.layout.size);
236 // Now handle this `UnsafeCell`, unless it is empty.
237 if unsafe_cell_size != Size::ZERO {
238 unsafe_cell_action(place.ptr, unsafe_cell_size)
244 visitor.visit_value(place)?;
246 // The part between the end_ptr and the end of the place is also frozen.
247 // So pretend there is a 0-sized `UnsafeCell` at the end.
248 unsafe_cell_action(place.ptr.ptr_wrapping_offset(size, this), Size::ZERO)?;
252 /// Visiting the memory covered by a `MemPlace`, being aware of
253 /// whether we are inside an `UnsafeCell` or not.
254 struct UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
256 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
258 ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
259 unsafe_cell_action: F,
262 impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
263 for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
265 F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
267 type V = MPlaceTy<'tcx, Tag>;
270 fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
274 // Hook to detect `UnsafeCell`.
275 fn visit_value(&mut self, v: MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
276 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
277 let is_unsafe_cell = match v.layout.ty.kind {
279 Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
283 // We do not have to recurse further, this is an `UnsafeCell`.
284 (self.unsafe_cell_action)(v)
285 } else if self.ecx.type_is_freeze(v.layout.ty) {
286 // This is `Freeze`, there cannot be an `UnsafeCell`
289 // We want to not actually read from memory for this visit. So, before
290 // walking this value, we have to make sure it is not a
291 // `Variants::Multiple`.
292 match v.layout.variants {
293 layout::Variants::Multiple { .. } => {
294 // A multi-variant enum, or generator, or so.
295 // Treat this like a union: without reading from memory,
296 // we cannot determine the variant we are in. Reading from
297 // memory would be subject to Stacked Borrows rules, leading
298 // to all sorts of "funny" recursion.
299 // We only end up here if the type is *not* freeze, so we just call the
300 // `UnsafeCell` action.
301 (self.unsafe_cell_action)(v)
303 layout::Variants::Single { .. } => {
304 // Proceed further, try to find where exactly that `UnsafeCell`
312 // Make sure we visit aggregrates in increasing offset order.
315 place: MPlaceTy<'tcx, Tag>,
316 fields: impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>>,
317 ) -> InterpResult<'tcx> {
318 match place.layout.fields {
319 layout::FieldPlacement::Array { .. } => {
320 // For the array layout, we know the iterator will yield sorted elements so
321 // we can avoid the allocation.
322 self.walk_aggregate(place, fields)
324 layout::FieldPlacement::Arbitrary { .. } => {
325 // Gather the subplaces and sort them before visiting.
327 fields.collect::<InterpResult<'tcx, Vec<MPlaceTy<'tcx, Tag>>>>()?;
328 places.sort_by_key(|place| place.ptr.assert_ptr().offset);
329 self.walk_aggregate(place, places.into_iter().map(Ok))
331 layout::FieldPlacement::Union { .. } => {
333 bug!("a union is not an aggregate we should ever visit")
338 // We have to do *something* for unions.
339 fn visit_union(&mut self, v: MPlaceTy<'tcx, Tag>, fields: usize) -> InterpResult<'tcx> {
340 assert!(fields > 0); // we should never reach "pseudo-unions" with 0 fields, like primitives
342 // With unions, we fall back to whatever the type says, to hopefully be consistent
344 // FIXME: are we consistent, and is this really the behavior we want?
345 let frozen = self.ecx.type_is_freeze(v.layout.ty);
346 if frozen { Ok(()) } else { (self.unsafe_cell_action)(v) }
351 // Writes several `ImmTy`s contiguosly into memory. This is useful when you have to pack
352 // different values into a struct.
353 fn write_packed_immediates(
355 place: MPlaceTy<'tcx, Tag>,
356 imms: &[ImmTy<'tcx, Tag>],
357 ) -> InterpResult<'tcx> {
358 let this = self.eval_context_mut();
360 let mut offset = Size::from_bytes(0);
363 this.write_immediate_to_mplace(
365 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
367 offset += imm.layout.size;
372 /// Helper function used inside the shims of foreign functions to check that isolation is
373 /// disabled. It returns an error using the `name` of the foreign function if this is not the
375 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
376 if !self.eval_context_ref().machine.communicate {
377 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
378 "`{}` not available when isolation is enabled",
384 /// Helper function used inside the shims of foreign functions to assert that the target OS
385 /// is `target_os`. It panics showing a message with the `name` of the foreign function
386 /// if this is not the case.
387 fn assert_target_os(&self, target_os: &str, name: &str) {
389 self.eval_context_ref().tcx.sess.target.target.target_os,
391 "`{}` is only available on the `{}` target OS",
397 /// Sets the last error variable.
398 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
399 let this = self.eval_context_mut();
400 let errno_place = this.machine.last_error.unwrap();
401 this.write_scalar(scalar, errno_place.into())
404 /// Gets the last error variable.
405 fn get_last_error(&self) -> InterpResult<'tcx, Scalar<Tag>> {
406 let this = self.eval_context_ref();
407 let errno_place = this.machine.last_error.unwrap();
408 this.read_scalar(errno_place.into())?.not_undef()
411 /// Sets the last OS error using a `std::io::Error`. This function tries to produce the most
412 /// similar OS error from the `std::io::ErrorKind` and sets it as the last OS error.
413 fn set_last_error_from_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
414 use std::io::ErrorKind::*;
415 let this = self.eval_context_mut();
416 let target = &this.tcx.tcx.sess.target.target;
417 let last_error = if target.options.target_family == Some("unix".to_owned()) {
418 this.eval_libc(match e.kind() {
419 ConnectionRefused => "ECONNREFUSED",
420 ConnectionReset => "ECONNRESET",
421 PermissionDenied => "EPERM",
422 BrokenPipe => "EPIPE",
423 NotConnected => "ENOTCONN",
424 ConnectionAborted => "ECONNABORTED",
425 AddrNotAvailable => "EADDRNOTAVAIL",
426 AddrInUse => "EADDRINUSE",
427 NotFound => "ENOENT",
428 Interrupted => "EINTR",
429 InvalidInput => "EINVAL",
430 TimedOut => "ETIMEDOUT",
431 AlreadyExists => "EEXIST",
432 WouldBlock => "EWOULDBLOCK",
434 throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
438 // FIXME: we have to implement the Windows equivalent of this.
440 "setting the last OS error from an io::Error is unsupported for {}.",
444 this.set_last_error(last_error)
447 /// Helper function that consumes an `std::io::Result<T>` and returns an
448 /// `InterpResult<'tcx,T>::Ok` instead. In case the result is an error, this function returns
449 /// `Ok(-1)` and sets the last OS error accordingly.
451 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
452 /// functions return different integer types (like `read`, that returns an `i64`).
453 fn try_unwrap_io_result<T: From<i32>>(
455 result: std::io::Result<T>,
456 ) -> InterpResult<'tcx, T> {
460 self.eval_context_mut().set_last_error_from_io_error(e)?;
466 /// Dispatches to appropriate implementations for reading an OsString from Memory,
467 /// depending on the interpretation target.
468 /// FIXME: Use `Cow` to avoid copies
469 fn read_os_str_from_target_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString> {
470 let target_os = self.eval_context_ref().tcx.sess.target.target.target_os.as_str();
472 "linux" | "macos" => self.read_os_str_from_c_str(scalar).map(|x| x.to_os_string()),
473 "windows" => self.read_os_str_from_wide_str(scalar),
474 unsupported => throw_unsup_format!("OsString support for target OS `{}` not yet available", unsupported),
478 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
479 /// the Unix APIs usually handle.
480 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
486 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
487 Ok(OsStr::from_bytes(bytes))
490 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
491 let s = std::str::from_utf8(bytes)
492 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
496 let this = self.eval_context_ref();
497 let bytes = this.memory.read_c_str(scalar)?;
498 bytes_to_os_str(bytes)
501 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
502 /// which is what the Windows APIs usually handle.
503 fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
509 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
510 Ok(OsString::from_wide(&u16_vec[..]))
513 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
514 let s = String::from_utf16(&u16_vec[..])
515 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
519 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
520 u16vec_to_osstring(u16_vec)
523 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
524 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
525 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
526 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
527 /// string length returned does not include the null terminator.
528 fn write_os_str_to_c_str(
533 ) -> InterpResult<'tcx, (bool, u64)> {
535 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
536 Ok(os_str.as_bytes())
539 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
540 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
541 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
545 .map(|s| s.as_bytes())
546 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
549 let bytes = os_str_to_bytes(os_str)?;
550 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
551 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
552 let string_length = u64::try_from(bytes.len()).unwrap();
553 if size <= string_length {
554 return Ok((false, string_length));
556 self.eval_context_mut()
558 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
559 Ok((true, string_length))
562 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
563 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
564 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
565 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
566 /// string length returned does not include the null terminator.
567 fn write_os_str_to_wide_str(
570 mplace: MPlaceTy<'tcx, Tag>,
572 ) -> InterpResult<'tcx, (bool, u64)> {
574 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
575 Ok(os_str.encode_wide().collect())
578 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
579 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
580 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
584 .map(|s| s.encode_utf16().collect())
585 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
588 let u16_vec = os_str_to_u16vec(os_str)?;
589 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
590 // 0x0000 terminator to memory would cause an out-of-bounds access.
591 let string_length = u64::try_from(u16_vec.len()).unwrap();
592 if size <= string_length {
593 return Ok((false, string_length));
596 let this = self.eval_context_mut();
598 // Store the UTF-16 string.
599 let char_size = Size::from_bytes(2);
600 for (idx, c) in u16_vec.into_iter().chain(iter::once(0x0000)).enumerate() {
601 let place = this.mplace_field(mplace, u64::try_from(idx).unwrap())?;
602 this.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
604 Ok((true, string_length))
607 /// Dispatches to appropriate implementations for allocating & writing OsString in Memory,
608 /// depending on the interpretation target.
609 fn alloc_os_str_as_target_str(
612 memkind: MemoryKind<MiriMemoryKind>,
613 ) -> InterpResult<'tcx, Pointer<Tag>> {
614 let target_os = self.eval_context_ref().tcx.sess.target.target.target_os.as_str();
616 "linux" | "macos" => Ok(self.alloc_os_str_as_c_str(os_str, memkind)),
617 "windows" => Ok(self.alloc_os_str_as_wide_str(os_str, memkind)),
618 unsupported => throw_unsup_format!("OsString support for target OS `{}` not yet available", unsupported),
622 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
623 fn alloc_os_str_as_c_str(
626 memkind: MemoryKind<MiriMemoryKind>,
628 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
629 let this = self.eval_context_mut();
631 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
632 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
633 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
634 arg_place.ptr.assert_ptr()
637 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
638 fn alloc_os_str_as_wide_str(
641 memkind: MemoryKind<MiriMemoryKind>,
643 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
644 let this = self.eval_context_mut();
646 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
647 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
648 assert!(self.write_os_str_to_wide_str(os_str, arg_place, size).unwrap().0);
649 arg_place.ptr.assert_ptr()
652 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
653 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
658 let this = self.eval_context_ref();
659 let os_str = this.read_os_str_from_c_str(scalar)?;
662 return Ok(if this.tcx.sess.target.target.target_os == "windows" {
663 // Windows-on-Windows, all fine.
664 Cow::Borrowed(Path::new(os_str))
666 // Unix target, Windows host. Need to convert target '/' to host '\'.
667 let converted = os_str
669 .map(|wchar| if wchar == '/' as u16 { '\\' as u16 } else { wchar })
670 .collect::<Vec<_>>();
671 Cow::Owned(PathBuf::from(OsString::from_wide(&converted)))
674 return Ok(if this.tcx.sess.target.target.target_os == "windows" {
675 // Windows target, Unix host. Need to convert target '\' to host '/'.
676 let converted = os_str
679 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
680 .collect::<Vec<_>>();
681 Cow::Owned(PathBuf::from(OsString::from_vec(converted)))
683 // Unix-on-Unix, all is fine.
684 Cow::Borrowed(Path::new(os_str))
688 /// Write a Path to the machine memory, adjusting path separators if needed.
689 fn write_path_to_c_str(
694 ) -> InterpResult<'tcx, (bool, u64)> {
695 let this = self.eval_context_mut();
698 let os_str = if this.tcx.sess.target.target.target_os == "windows" {
699 // Windows-on-Windows, all fine.
700 Cow::Borrowed(path.as_os_str())
702 // Unix target, Windows host. Need to convert host '\\' to target '/'.
706 .map(|wchar| if wchar == '\\' as u16 { '/' as u16 } else { wchar })
707 .collect::<Vec<_>>();
708 Cow::Owned(OsString::from_wide(&converted))
711 let os_str = if this.tcx.sess.target.target.target_os == "windows" {
712 // Windows target, Unix host. Need to convert host '/' to target '\'.
717 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
718 .collect::<Vec<_>>();
719 Cow::Owned(OsString::from_vec(converted))
721 // Unix-on-Unix, all is fine.
722 Cow::Borrowed(path.as_os_str())
725 this.write_os_str_to_c_str(&os_str, scalar, size)
729 pub fn immty_from_int_checked<'tcx>(
730 int: impl Into<i128>,
731 layout: TyLayout<'tcx>,
732 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
733 let int = int.into();
734 Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
735 err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
739 pub fn immty_from_uint_checked<'tcx>(
740 int: impl Into<u128>,
741 layout: TyLayout<'tcx>,
742 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
743 let int = int.into();
744 Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
745 err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())