]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
8e379065b07eb68a3fba7f045e35c0dfc17befd6
[rust.git] / src / helpers.rs
1 use std::ffi::{OsStr, OsString};
2 use std::path::{Path, PathBuf};
3 use std::{iter, mem};
4 use std::convert::TryFrom;
5 use std::borrow::Cow;
6
7 #[cfg(unix)]
8 use std::os::unix::ffi::{OsStrExt, OsStringExt};
9 #[cfg(windows)]
10 use std::os::windows::ffi::{OsStrExt, OsStringExt};
11
12 use rustc::mir;
13 use rustc::ty::{
14     self,
15     layout::{self, LayoutOf, Size, TyLayout},
16     List, TyCtxt,
17 };
18 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
19 use rustc_span::source_map::DUMMY_SP;
20
21 use rand::RngCore;
22
23 use crate::*;
24
25 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
26
27 /// Gets an instance for a path.
28 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
29     tcx.crates()
30         .iter()
31         .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
32         .and_then(|krate| {
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();
36
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());
42                         }
43
44                         items = tcx.item_children(item.res.def_id());
45                         break;
46                     }
47                 }
48             }
49             None
50         })
51 }
52
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)
59     }
60
61     /// Evaluates the scalar at the specified path. Returns Some(val)
62     /// if the path could be resolved, and None otherwise
63     fn eval_path_scalar(
64         &mut self,
65         path: &[&str],
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())?;
72         return Ok(const_val);
73     }
74
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])?
79             .not_undef()
80     }
81
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()
86     }
87
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);
92         this.layout_of(ty)
93     }
94
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)
98     }
99
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)
105     }
106
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) })
111     }
112
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)
118     }
119
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.
127         if len == 0 {
128             return Ok(());
129         }
130         let this = self.eval_context_mut();
131
132         let mut data = vec![0; usize::try_from(len).unwrap()];
133
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))?;
138         } else {
139             let rng = this.memory.extra.rng.get_mut();
140             rng.fill_bytes(&mut data);
141         }
142
143         this.memory.write_bytes(ptr, data.iter().copied())
144     }
145
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).
148     fn call_function(
149         &mut self,
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();
156
157         // Push frame.
158         let mir = &*this.load_mir(f.def, None)?;
159         let span = this
160             .stack()
161             .last()
162             .and_then(Frame::current_source_info)
163             .map(|si| si.span)
164             .unwrap_or(DUMMY_SP);
165         this.push_stack_frame(f, span, mir, dest, stack_pop)?;
166
167         // Initialize arguments.
168         let mut callee_args = this.frame().body.args_iter();
169         for arg in args {
170             let callee_arg = this.local_place(
171                 callee_args.next().expect("callee has fewer arguments than expected"),
172             )?;
173             this.write_immediate(*arg, callee_arg)?;
174         }
175         callee_args.next().expect_none("callee has more arguments than expected");
176
177         Ok(())
178     }
179
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(
183         &self,
184         place: MPlaceTy<'tcx, Tag>,
185         size: Size,
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);
190         debug_assert_eq!(
191             size,
192             this.size_and_align_of_mplace(place)?
193                 .map(|(size, _)| size)
194                 .unwrap_or_else(|| place.layout.size)
195         );
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)?;
215             }
216             // This `UnsafeCell` is NOT frozen.
217             if unsafe_cell_size != Size::ZERO {
218                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
219             }
220             // Update end end_ptr.
221             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
222             // Done
223             Ok(())
224         };
225         // Run a visitor
226         {
227             let mut visitor = UnsafeCellVisitor {
228                 ecx: this,
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)
240                     } else {
241                         Ok(())
242                     }
243                 },
244             };
245             visitor.visit_value(place)?;
246         }
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)?;
250         // Done!
251         return Ok(());
252
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>
256         where
257             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
258         {
259             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
260             unsafe_cell_action: F,
261         }
262
263         impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
264             for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
265         where
266             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
267         {
268             type V = MPlaceTy<'tcx, Tag>;
269
270             #[inline(always)]
271             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
272                 &self.ecx
273             }
274
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 {
279                     ty::Adt(adt, _) =>
280                         Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
281                     _ => false,
282                 };
283                 if is_unsafe_cell {
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`
288                     Ok(())
289                 } else {
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)
303                         }
304                         layout::Variants::Single { .. } => {
305                             // Proceed further, try to find where exactly that `UnsafeCell`
306                             // is hiding.
307                             self.walk_value(v)
308                         }
309                     }
310                 }
311             }
312
313             // Make sure we visit aggregrates in increasing offset order.
314             fn visit_aggregate(
315                 &mut self,
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)
324                     }
325                     layout::FieldPlacement::Arbitrary { .. } => {
326                         // Gather the subplaces and sort them before visiting.
327                         let mut places =
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))
331                     }
332                     layout::FieldPlacement::Union { .. } => {
333                         // Uh, what?
334                         bug!("a union is not an aggregate we should ever visit")
335                     }
336                 }
337             }
338
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
342
343                 // With unions, we fall back to whatever the type says, to hopefully be consistent
344                 // with LLVM IR.
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) }
348             }
349         }
350     }
351
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(
355         &mut self,
356         place: MPlaceTy<'tcx, Tag>,
357         imms: &[ImmTy<'tcx, Tag>],
358     ) -> InterpResult<'tcx> {
359         let this = self.eval_context_mut();
360
361         let mut offset = Size::from_bytes(0);
362
363         for &imm in imms {
364             this.write_immediate_to_mplace(
365                 *imm,
366                 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
367             )?;
368             offset += imm.layout.size;
369         }
370         Ok(())
371     }
372
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
375     /// case.
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",
380                 name,
381             )))
382         }
383         Ok(())
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.target.target_os,
391             target_os,
392             "`{}` is only available on the `{}` target OS",
393             name,
394             target_os,
395         )
396     }
397
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())
403     }
404
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()
410     }
411
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",
434                 _ => {
435                     throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
436                 }
437             })?
438         } else {
439             // FIXME: we have to implement the Windows equivalent of this.
440             throw_unsup_format!(
441                 "setting the last OS error from an io::Error is unsupported for {}.",
442                 target.target_os
443             )
444         };
445         this.set_last_error(last_error)
446     }
447
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.
451     ///
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>>(
455         &mut self,
456         result: std::io::Result<T>,
457     ) -> InterpResult<'tcx, T> {
458         match result {
459             Ok(ok) => Ok(ok),
460             Err(e) => {
461                 self.eval_context_mut().set_last_error_from_io_error(e)?;
462                 Ok((-1).into())
463             }
464         }
465     }
466
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>
470     where
471         'tcx: 'a,
472         'mir: 'a,
473     {
474         #[cfg(unix)]
475         fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
476             Ok(OsStr::from_bytes(bytes))
477         }
478         #[cfg(not(unix))]
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))?;
482             Ok(OsStr::new(s))
483         }
484
485         let this = self.eval_context_ref();
486         let bytes = this.memory.read_c_str(scalar)?;
487         bytes_to_os_str(bytes)
488     }
489
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>
493     where
494         'tcx: 'a,
495         'mir: 'a,
496     {
497         #[cfg(windows)]
498         pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
499             Ok(OsString::from_wide(&u16_vec[..]))
500         }
501         #[cfg(not(windows))]
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))?;
505             Ok(s.into())
506         }
507
508         let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
509         u16vec_to_osstring(u16_vec)
510     }
511
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(
518         &mut self,
519         os_str: &OsStr,
520         scalar: Scalar<Tag>,
521         size: u64,
522     ) -> InterpResult<'tcx, (bool, u64)> {
523         #[cfg(unix)]
524         fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
525             Ok(os_str.as_bytes())
526         }
527         #[cfg(not(unix))]
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
531             // valid.
532             os_str
533                 .to_str()
534                 .map(|s| s.as_bytes())
535                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
536         }
537
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));
544         }
545         self.eval_context_mut()
546             .memory
547             .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
548         Ok((true, string_length))
549     }
550
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(
557         &mut self,
558         os_str: &OsStr,
559         scalar: Scalar<Tag>,
560         size: u64,
561     ) -> InterpResult<'tcx, (bool, u64)> {
562         #[cfg(windows)]
563         fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
564             Ok(os_str.encode_wide().collect())
565         }
566         #[cfg(not(windows))]
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
570             // valid.
571             os_str
572                 .to_str()
573                 .map(|s| s.encode_utf16().collect())
574                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
575         }
576
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));
583         }
584
585         // Store the UTF-16 string.
586         self.eval_context_mut()
587             .memory
588             .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
589         Ok((true, string_length))
590     }
591
592     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
593     fn alloc_os_str_as_c_str(
594         &mut self,
595         os_str: &OsStr,
596         memkind: MemoryKind<MiriMemoryKind>,
597     ) -> Pointer<Tag> {
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();
600
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()
605     }
606
607     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
608     fn alloc_os_str_as_wide_str(
609         &mut self,
610         os_str: &OsStr,
611         memkind: MemoryKind<MiriMemoryKind>,
612     ) -> Pointer<Tag> {
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();
615
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()
620     }
621
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>>
624     where
625         'tcx: 'a,
626         'mir: 'a,
627     {
628         let this = self.eval_context_ref();
629         let os_str = this.read_os_str_from_c_str(scalar)?;
630
631         #[cfg(windows)]
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))
635         } else {
636             // Unix target, Windows host. Need to convert target '/' to host '\'.
637             let converted = os_str
638                 .encode_wide()
639                 .map(|wchar| if wchar == '/' as u16 { '\\' as u16 } else { wchar })
640                 .collect::<Vec<_>>();
641             Cow::Owned(PathBuf::from(OsString::from_wide(&converted)))
642         });
643         #[cfg(unix)]
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
647                 .as_bytes()
648                 .iter()
649                 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
650                 .collect::<Vec<_>>();
651             Cow::Owned(PathBuf::from(OsString::from_vec(converted)))
652         } else {
653             // Unix-on-Unix, all is fine.
654             Cow::Borrowed(Path::new(os_str))
655         });
656     }
657
658     /// Write a Path to the machine memory, adjusting path separators if needed.
659     fn write_path_to_c_str(
660         &mut self,
661         path: &Path,
662         scalar: Scalar<Tag>,
663         size: u64,
664     ) -> InterpResult<'tcx, (bool, u64)> {
665         let this = self.eval_context_mut();
666
667         #[cfg(windows)]
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())
671         } else {
672             // Unix target, Windows host. Need to convert host '\\' to target '/'.
673             let converted = path
674                 .as_os_str()
675                 .encode_wide()
676                 .map(|wchar| if wchar == '\\' as u16 { '/' as u16 } else { wchar })
677                 .collect::<Vec<_>>();
678             Cow::Owned(OsString::from_wide(&converted))
679         };
680         #[cfg(unix)]
681         let os_str = if this.tcx.sess.target.target.target_os == "windows" {
682             // Windows target, Unix host. Need to convert host '/' to target '\'.
683             let converted = path
684                 .as_os_str()
685                 .as_bytes()
686                 .iter()
687                 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
688                 .collect::<Vec<_>>();
689             Cow::Owned(OsString::from_vec(converted))
690         } else {
691             // Unix-on-Unix, all is fine.
692             Cow::Borrowed(path.as_os_str())
693         };
694
695         this.write_os_str_to_c_str(&os_str, scalar, size)
696     }
697 }
698
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())
706     })?)
707 }
708
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())
716     })?)
717 }