]> git.lizzy.rs Git - rust.git/blob - src/helpers.rs
run Windows TLS dtor function
[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         self.eval_libc(name)?.to_i32()
85     }
86
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);
91         this.layout_of(ty)
92     }
93
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)
97     }
98
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)
104     }
105
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) })
110     }
111
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)
117     }
118
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.
126         if len == 0 {
127             return Ok(());
128         }
129         let this = self.eval_context_mut();
130
131         let mut data = vec![0; usize::try_from(len).unwrap()];
132
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))?;
137         } else {
138             let rng = this.memory.extra.rng.get_mut();
139             rng.fill_bytes(&mut data);
140         }
141
142         this.memory.write_bytes(ptr, data.iter().copied())
143     }
144
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).
147     fn call_function(
148         &mut self,
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();
155
156         // Push frame.
157         let mir = &*this.load_mir(f.def, None)?;
158         let span = this
159             .stack()
160             .last()
161             .and_then(Frame::current_source_info)
162             .map(|si| si.span)
163             .unwrap_or(DUMMY_SP);
164         this.push_stack_frame(f, span, mir, dest, stack_pop)?;
165
166         // Initialize arguments.
167         let mut callee_args = this.frame().body.args_iter();
168         for arg in args {
169             let callee_arg = this.local_place(
170                 callee_args.next().expect("callee has fewer arguments than expected"),
171             )?;
172             this.write_immediate(*arg, callee_arg)?;
173         }
174         callee_args.next().expect_none("callee has more arguments than expected");
175
176         Ok(())
177     }
178
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(
182         &self,
183         place: MPlaceTy<'tcx, Tag>,
184         size: Size,
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);
189         debug_assert_eq!(
190             size,
191             this.size_and_align_of_mplace(place)?
192                 .map(|(size, _)| size)
193                 .unwrap_or_else(|| place.layout.size)
194         );
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)?;
214             }
215             // This `UnsafeCell` is NOT frozen.
216             if unsafe_cell_size != Size::ZERO {
217                 action(unsafe_cell_ptr, unsafe_cell_size, /*frozen*/ false)?;
218             }
219             // Update end end_ptr.
220             end_ptr = unsafe_cell_ptr.wrapping_offset(unsafe_cell_size, this);
221             // Done
222             Ok(())
223         };
224         // Run a visitor
225         {
226             let mut visitor = UnsafeCellVisitor {
227                 ecx: this,
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)
239                     } else {
240                         Ok(())
241                     }
242                 },
243             };
244             visitor.visit_value(place)?;
245         }
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)?;
249         // Done!
250         return Ok(());
251
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>
255         where
256             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
257         {
258             ecx: &'ecx MiriEvalContext<'mir, 'tcx>,
259             unsafe_cell_action: F,
260         }
261
262         impl<'ecx, 'mir, 'tcx, F> ValueVisitor<'mir, 'tcx, Evaluator<'tcx>>
263             for UnsafeCellVisitor<'ecx, 'mir, 'tcx, F>
264         where
265             F: FnMut(MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx>,
266         {
267             type V = MPlaceTy<'tcx, Tag>;
268
269             #[inline(always)]
270             fn ecx(&self) -> &MiriEvalContext<'mir, 'tcx> {
271                 &self.ecx
272             }
273
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 {
278                     ty::Adt(adt, _) =>
279                         Some(adt.did) == self.ecx.tcx.lang_items().unsafe_cell_type(),
280                     _ => false,
281                 };
282                 if is_unsafe_cell {
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`
287                     Ok(())
288                 } else {
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)
302                         }
303                         layout::Variants::Single { .. } => {
304                             // Proceed further, try to find where exactly that `UnsafeCell`
305                             // is hiding.
306                             self.walk_value(v)
307                         }
308                     }
309                 }
310             }
311
312             // Make sure we visit aggregrates in increasing offset order.
313             fn visit_aggregate(
314                 &mut self,
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)
323                     }
324                     layout::FieldPlacement::Arbitrary { .. } => {
325                         // Gather the subplaces and sort them before visiting.
326                         let mut places =
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))
330                     }
331                     layout::FieldPlacement::Union { .. } => {
332                         // Uh, what?
333                         bug!("a union is not an aggregate we should ever visit")
334                     }
335                 }
336             }
337
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
341
342                 // With unions, we fall back to whatever the type says, to hopefully be consistent
343                 // with LLVM IR.
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) }
347             }
348         }
349     }
350
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(
354         &mut self,
355         place: MPlaceTy<'tcx, Tag>,
356         imms: &[ImmTy<'tcx, Tag>],
357     ) -> InterpResult<'tcx> {
358         let this = self.eval_context_mut();
359
360         let mut offset = Size::from_bytes(0);
361
362         for &imm in imms {
363             this.write_immediate_to_mplace(
364                 *imm,
365                 place.offset(offset, MemPlaceMeta::None, imm.layout, &*this.tcx)?,
366             )?;
367             offset += imm.layout.size;
368         }
369         Ok(())
370     }
371
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
374     /// case.
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",
379                 name,
380             )))
381         }
382         Ok(())
383     }
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) {
388         assert_eq!(
389             self.eval_context_ref().tcx.sess.target.target.target_os,
390             target_os,
391             "`{}` is only available on the `{}` target OS",
392             name,
393             target_os,
394         )
395     }
396
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())
402     }
403
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()
409     }
410
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.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",
433                 _ => {
434                     throw_unsup_format!("io error {} cannot be transformed into a raw os error", e)
435                 }
436             })?
437         } else {
438             // FIXME: we have to implement the Windows equivalent of this.
439             throw_unsup_format!(
440                 "setting the last OS error from an io::Error is unsupported for {}.",
441                 target.target_os
442             )
443         };
444         this.set_last_error(last_error)
445     }
446
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.
450     ///
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>>(
454         &mut self,
455         result: std::io::Result<T>,
456     ) -> InterpResult<'tcx, T> {
457         match result {
458             Ok(ok) => Ok(ok),
459             Err(e) => {
460                 self.eval_context_mut().set_last_error_from_io_error(e)?;
461                 Ok((-1).into())
462             }
463         }
464     }
465
466     /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
467     /// the Unix APIs usually handle.
468     fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
469     where
470         'tcx: 'a,
471         'mir: 'a,
472     {
473         #[cfg(unix)]
474         fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
475             Ok(OsStr::from_bytes(bytes))
476         }
477         #[cfg(not(unix))]
478         fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
479             let s = std::str::from_utf8(bytes)
480                 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
481             Ok(OsStr::new(s))
482         }
483
484         let this = self.eval_context_ref();
485         let bytes = this.memory.read_c_str(scalar)?;
486         bytes_to_os_str(bytes)
487     }
488
489     /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
490     /// which is what the Windows APIs usually handle.
491     fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
492     where
493         'tcx: 'a,
494         'mir: 'a,
495     {
496         #[cfg(windows)]
497         pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
498             Ok(OsString::from_wide(&u16_vec[..]))
499         }
500         #[cfg(not(windows))]
501         pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
502             let s = String::from_utf16(&u16_vec[..])
503                 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
504             Ok(s.into())
505         }
506
507         let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
508         u16vec_to_osstring(u16_vec)
509     }
510
511     /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
512     /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
513     /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
514     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
515     /// string length returned does not include the null terminator.
516     fn write_os_str_to_c_str(
517         &mut self,
518         os_str: &OsStr,
519         scalar: Scalar<Tag>,
520         size: u64,
521     ) -> InterpResult<'tcx, (bool, u64)> {
522         #[cfg(unix)]
523         fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
524             Ok(os_str.as_bytes())
525         }
526         #[cfg(not(unix))]
527         fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
528             // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
529             // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
530             // valid.
531             os_str
532                 .to_str()
533                 .map(|s| s.as_bytes())
534                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
535         }
536
537         let bytes = os_str_to_bytes(os_str)?;
538         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
539         // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
540         let string_length = u64::try_from(bytes.len()).unwrap();
541         if size <= string_length {
542             return Ok((false, string_length));
543         }
544         self.eval_context_mut()
545             .memory
546             .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
547         Ok((true, string_length))
548     }
549
550     /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
551     /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
552     /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
553     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
554     /// string length returned does not include the null terminator.
555     fn write_os_str_to_wide_str(
556         &mut self,
557         os_str: &OsStr,
558         scalar: Scalar<Tag>,
559         size: u64,
560     ) -> InterpResult<'tcx, (bool, u64)> {
561         #[cfg(windows)]
562         fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
563             Ok(os_str.encode_wide().collect())
564         }
565         #[cfg(not(windows))]
566         fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
567             // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
568             // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
569             // valid.
570             os_str
571                 .to_str()
572                 .map(|s| s.encode_utf16().collect())
573                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
574         }
575
576         let u16_vec = os_str_to_u16vec(os_str)?;
577         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
578         // 0x0000 terminator to memory would cause an out-of-bounds access.
579         let string_length = u64::try_from(u16_vec.len()).unwrap();
580         if size <= string_length {
581             return Ok((false, string_length));
582         }
583
584         // Store the UTF-16 string.
585         self.eval_context_mut()
586             .memory
587             .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
588         Ok((true, string_length))
589     }
590
591     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
592     fn alloc_os_str_as_c_str(
593         &mut self,
594         os_str: &OsStr,
595         memkind: MemoryKind<MiriMemoryKind>,
596     ) -> Pointer<Tag> {
597         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
598         let this = self.eval_context_mut();
599
600         let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
601         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
602         assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
603         arg_place.ptr.assert_ptr()
604     }
605
606     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
607     fn alloc_os_str_as_wide_str(
608         &mut self,
609         os_str: &OsStr,
610         memkind: MemoryKind<MiriMemoryKind>,
611     ) -> Pointer<Tag> {
612         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
613         let this = self.eval_context_mut();
614
615         let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
616         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
617         assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
618         arg_place.ptr.assert_ptr()
619     }
620
621     /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
622     fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
623     where
624         'tcx: 'a,
625         'mir: 'a,
626     {
627         let this = self.eval_context_ref();
628         let os_str = this.read_os_str_from_c_str(scalar)?;
629
630         #[cfg(windows)]
631         return Ok(if this.tcx.sess.target.target.target_os == "windows" {
632             // Windows-on-Windows, all fine.
633             Cow::Borrowed(Path::new(os_str))
634         } else {
635             // Unix target, Windows host. Need to convert target '/' to host '\'.
636             let converted = os_str
637                 .encode_wide()
638                 .map(|wchar| if wchar == '/' as u16 { '\\' as u16 } else { wchar })
639                 .collect::<Vec<_>>();
640             Cow::Owned(PathBuf::from(OsString::from_wide(&converted)))
641         });
642         #[cfg(unix)]
643         return Ok(if this.tcx.sess.target.target.target_os == "windows" {
644             // Windows target, Unix host. Need to convert target '\' to host '/'.
645             let converted = os_str
646                 .as_bytes()
647                 .iter()
648                 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
649                 .collect::<Vec<_>>();
650             Cow::Owned(PathBuf::from(OsString::from_vec(converted)))
651         } else {
652             // Unix-on-Unix, all is fine.
653             Cow::Borrowed(Path::new(os_str))
654         });
655     }
656
657     /// Write a Path to the machine memory, adjusting path separators if needed.
658     fn write_path_to_c_str(
659         &mut self,
660         path: &Path,
661         scalar: Scalar<Tag>,
662         size: u64,
663     ) -> InterpResult<'tcx, (bool, u64)> {
664         let this = self.eval_context_mut();
665
666         #[cfg(windows)]
667         let os_str = if this.tcx.sess.target.target.target_os == "windows" {
668             // Windows-on-Windows, all fine.
669             Cow::Borrowed(path.as_os_str())
670         } else {
671             // Unix target, Windows host. Need to convert host '\\' to target '/'.
672             let converted = path
673                 .as_os_str()
674                 .encode_wide()
675                 .map(|wchar| if wchar == '\\' as u16 { '/' as u16 } else { wchar })
676                 .collect::<Vec<_>>();
677             Cow::Owned(OsString::from_wide(&converted))
678         };
679         #[cfg(unix)]
680         let os_str = if this.tcx.sess.target.target.target_os == "windows" {
681             // Windows target, Unix host. Need to convert host '/' to target '\'.
682             let converted = path
683                 .as_os_str()
684                 .as_bytes()
685                 .iter()
686                 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
687                 .collect::<Vec<_>>();
688             Cow::Owned(OsString::from_vec(converted))
689         } else {
690             // Unix-on-Unix, all is fine.
691             Cow::Borrowed(path.as_os_str())
692         };
693
694         this.write_os_str_to_c_str(&os_str, scalar, size)
695     }
696 }
697
698 pub fn immty_from_int_checked<'tcx>(
699     int: impl Into<i128>,
700     layout: TyLayout<'tcx>,
701 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
702     let int = int.into();
703     Ok(ImmTy::try_from_int(int, layout).ok_or_else(|| {
704         err_unsup_format!("signed value {:#x} does not fit in {} bits", int, layout.size.bits())
705     })?)
706 }
707
708 pub fn immty_from_uint_checked<'tcx>(
709     int: impl Into<u128>,
710     layout: TyLayout<'tcx>,
711 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
712     let int = int.into();
713     Ok(ImmTy::try_from_uint(int, layout).ok_or_else(|| {
714         err_unsup_format!("unsigned value {:#x} does not fit in {} bits", int, layout.size.bits())
715     })?)
716 }