]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
route all path reading/writing through central read/write methods
[rust.git] / src / helpers.rs
1 use std::ffi::{OsStr, OsString};
2 use std::path::Path;
3 use std::{iter, mem};
4 use std::convert::TryFrom;
5 use std::borrow::Cow;
6
7 use rustc::mir;
8 use rustc::ty::{
9     self,
10     layout::{self, LayoutOf, Size, TyLayout},
11     List, TyCtxt,
12 };
13 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
14 use rustc_span::source_map::DUMMY_SP;
15
16 use rand::RngCore;
17
18 use crate::*;
19
20 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
21
22 /// Gets an instance for a path.
23 fn try_resolve_did<'mir, 'tcx>(tcx: TyCtxt<'tcx>, path: &[&str]) -> Option<DefId> {
24     tcx.crates()
25         .iter()
26         .find(|&&krate| tcx.original_crate_name(krate).as_str() == path[0])
27         .and_then(|krate| {
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();
31
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());
37                         }
38
39                         items = tcx.item_children(item.res.def_id());
40                         break;
41                     }
42                 }
43             }
44             None
45         })
46 }
47
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)
54     }
55
56     /// Evaluates the scalar at the specified path. Returns Some(val)
57     /// if the path could be resolved, and None otherwise
58     fn eval_path_scalar(
59         &mut self,
60         path: &[&str],
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())?;
67         return Ok(const_val);
68     }
69
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])?
74             .not_undef()
75     }
76
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()
80     }
81
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);
86         this.layout_of(ty)
87     }
88
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)
92     }
93
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)
99     }
100
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) })
105     }
106
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)
112     }
113
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.
121         if len == 0 {
122             return Ok(());
123         }
124         let this = self.eval_context_mut();
125
126         let mut data = vec![0; usize::try_from(len).unwrap()];
127
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))?;
132         } else {
133             let rng = this.memory.extra.rng.get_mut();
134             rng.fill_bytes(&mut data);
135         }
136
137         this.memory.write_bytes(ptr, data.iter().copied())
138     }
139
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).
142     fn call_function(
143         &mut self,
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();
150
151         // Push frame.
152         let mir = &*this.load_mir(f.def, None)?;
153         let span = this
154             .stack()
155             .last()
156             .and_then(Frame::current_source_info)
157             .map(|si| si.span)
158             .unwrap_or(DUMMY_SP);
159         this.push_stack_frame(f, span, mir, dest, stack_pop)?;
160
161         // Initialize arguments.
162         let mut callee_args = this.frame().body.args_iter();
163         for arg in args {
164             let callee_arg = this.local_place(
165                 callee_args.next().expect("callee has fewer arguments than expected"),
166             )?;
167             this.write_immediate(*arg, callee_arg)?;
168         }
169         callee_args.next().expect_none("callee has more arguments than expected");
170
171         Ok(())
172     }
173
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(
177         &self,
178         place: MPlaceTy<'tcx, Tag>,
179         size: Size,
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);
184         debug_assert_eq!(
185             size,
186             this.size_and_align_of_mplace(place)?
187                 .map(|(size, _)| size)
188                 .unwrap_or_else(|| place.layout.size)
189         );
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)?;
209             }
210             // This `UnsafeCell` is NOT frozen.
211             if unsafe_cell_size != Size::ZERO {
212                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
213             }
214             // Update end end_ptr.
215             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
216             // Done
217             Ok(())
218         };
219         // Run a visitor
220         {
221             let mut visitor = UnsafeCellVisitor {
222                 ecx: this,
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)
234                     } else {
235                         Ok(())
236                     }
237                 },
238             };
239             visitor.visit_value(place)?;
240         }
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)?;
244         // Done!
245         return Ok(());
246
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>
250         where
251             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
252         {
253             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
254             unsafe_cell_action: F,
255         }
256
257         impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
258             for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
259         where
260             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
261         {
262             type V = MPlaceTy<'tcx, Tag>;
263
264             #[inline(always)]
265             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
266                 &self.ecx
267             }
268
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 {
273                     ty::Adt(adt, _) =>
274                         Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
275                     _ => false,
276                 };
277                 if is_unsafe_cell {
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`
282                     Ok(())
283                 } else {
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)
297                         }
298                         layout::Variants::Single { .. } => {
299                             // Proceed further, try to find where exactly that `UnsafeCell`
300                             // is hiding.
301                             self.walk_value(v)
302                         }
303                     }
304                 }
305             }
306
307             // Make sure we visit aggregrates in increasing offset order.
308             fn visit_aggregate(
309                 &mut self,
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)
318                     }
319                     layout::FieldPlacement::Arbitrary { .. } => {
320                         // Gather the subplaces and sort them before visiting.
321                         let mut places =
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))
325                     }
326                     layout::FieldPlacement::Union { .. } => {
327                         // Uh, what?
328                         bug!("a union is not an aggregate we should ever visit")
329                     }
330                 }
331             }
332
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
336
337                 // With unions, we fall back to whatever the type says, to hopefully be consistent
338                 // with LLVM IR.
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) }
342             }
343         }
344     }
345
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(
349         &mut self,
350         place: MPlaceTy<'tcx, Tag>,
351         imms: &[ImmTy<'tcx, Tag>],
352     ) -> InterpResult<'tcx> {
353         let this = self.eval_context_mut();
354
355         let mut offset = Size::from_bytes(0);
356
357         for &imm in imms {
358             this.write_immediate_to_mplace(
359                 *imm,
360                 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
361             )?;
362             offset += imm.layout.size;
363         }
364         Ok(())
365     }
366
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
369     /// case.
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",
374                 name,
375             )))
376         }
377         Ok(())
378     }
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) {
383         assert_eq!(
384             self.eval_context_ref().tcx.sess.target.target.target_os,
385             target_os,
386             "`{}` is only available on the `{}` target OS",
387             name,
388             target_os,
389         )
390     }
391
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())
397     }
398
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()
404     }
405
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",
428                 _ => {
429                     throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
430                 }
431             })?
432         } else {
433             // FIXME: we have to implement the Windows equivalent of this.
434             throw_unsup_format!(
435                 "setting the last OS error from an io::Error is unsupported for {}.",
436                 target.target_os
437             )
438         };
439         this.set_last_error(last_error)
440     }
441
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.
445     ///
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>>(
449         &mut self,
450         result: std::io::Result<T>,
451     ) -> InterpResult<'tcx, T> {
452         match result {
453             Ok(ok) => Ok(ok),
454             Err(e) => {
455                 self.eval_context_mut().set_last_error_from_io_error(e)?;
456                 Ok((-1).into())
457             }
458         }
459     }
460
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();
466         match target_os {
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),
470         }
471     }
472
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>
476     where
477         'tcx: 'a,
478         'mir: 'a,
479     {
480         #[cfg(unix)]
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))
483         }
484         #[cfg(not(unix))]
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))?;
488             Ok(OsStr::new(s))
489         }
490
491         let this = self.eval_context_ref();
492         let bytes = this.memory.read_c_str(scalar)?;
493         bytes_to_os_str(bytes)
494     }
495
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>>
498     where
499         'tcx: 'a,
500         'mir: 'a,
501     {
502         let os_str = self.read_os_str_from_c_str(scalar)?;
503         Ok(Cow::Borrowed(Path::new(os_str)))
504     }
505
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>
509     where
510         'tcx: 'a,
511         'mir: 'a,
512     {
513         #[cfg(windows)]
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[..]))
516         }
517         #[cfg(not(windows))]
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))?;
521             Ok(s.into())
522         }
523
524         let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
525         u16vec_to_osstring(u16_vec)
526     }
527
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(
534         &mut self,
535         os_str: &OsStr,
536         scalar: Scalar<Tag>,
537         size: u64,
538     ) -> InterpResult<'tcx, (bool, u64)> {
539         #[cfg(unix)]
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))
542         }
543         #[cfg(not(unix))]
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
547             // valid.
548             os_str
549                 .to_str()
550                 .map(|s| s.as_bytes())
551                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
552         }
553
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));
560         }
561         self.eval_context_mut()
562             .memory
563             .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
564         Ok((true, string_length))
565     }
566
567     /// Write a Path to the machine memory, adjusting path separators if needed.
568     fn write_path_to_c_str(
569         &mut self,
570         path: &Path,
571         scalar: Scalar<Tag>,
572         size: u64,
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)
576     }
577
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(
584         &mut self,
585         os_str: &OsStr,
586         mplace: MPlaceTy<'tcx, Tag>,
587         size: u64,
588     ) -> InterpResult<'tcx, (bool, u64)> {
589         #[cfg(windows)]
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())
592         }
593         #[cfg(not(windows))]
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
597             // valid.
598             os_str
599                 .to_str()
600                 .map(|s| s.encode_utf16().collect())
601                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
602         }
603
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));
610         }
611
612         let this = self.eval_context_mut();
613
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())?;
619         }
620         Ok((true, string_length))
621     }
622
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(
626         &mut self,
627         os_str: &OsStr,
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();
631         match target_os {
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),
635         }
636     }
637
638     fn alloc_os_str_as_c_str(
639         &mut self,
640         os_str: &OsStr,
641         memkind: MemoryKind<MiriMemoryKind>,
642     ) -> Pointer<Tag> {
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();
645
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()
650     }
651
652     fn alloc_os_str_as_wide_str(
653         &mut self,
654         os_str: &OsStr,
655         memkind: MemoryKind<MiriMemoryKind>,
656     ) -> Pointer<Tag> {
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();
659
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()
664     }
665 }
666
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())
674     })?)
675 }
676
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())
684     })?)
685 }