2 use std::convert::TryFrom;
3 use std::ffi::{OsStr, OsString};
5 use std::path::{Path, PathBuf};
8 use std::os::unix::ffi::{OsStrExt, OsStringExt};
10 use std::os::windows::ffi::{OsStrExt, OsStringExt};
12 use rustc::ty::layout::LayoutOf;
16 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
17 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
18 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
19 /// the Unix APIs usually handle.
20 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
26 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
27 Ok(OsStr::from_bytes(bytes))
30 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
31 let s = std::str::from_utf8(bytes)
32 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
36 let this = self.eval_context_ref();
37 let bytes = this.memory.read_c_str(scalar)?;
38 bytes_to_os_str(bytes)
41 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
42 /// which is what the Windows APIs usually handle.
43 fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
49 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
50 Ok(OsString::from_wide(&u16_vec[..]))
53 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
54 let s = String::from_utf16(&u16_vec[..])
55 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
59 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
60 u16vec_to_osstring(u16_vec)
63 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
64 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
65 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
66 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
67 /// string length returned does not include the null terminator.
68 fn write_os_str_to_c_str(
73 ) -> InterpResult<'tcx, (bool, u64)> {
75 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
79 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
80 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
81 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
85 .map(|s| s.as_bytes())
86 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
89 let bytes = os_str_to_bytes(os_str)?;
90 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
91 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
92 let string_length = u64::try_from(bytes.len()).unwrap();
93 if size <= string_length {
94 return Ok((false, string_length));
96 self.eval_context_mut()
98 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
99 Ok((true, string_length))
102 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
103 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
104 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
105 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
106 /// string length returned does not include the null terminator.
107 fn write_os_str_to_wide_str(
112 ) -> InterpResult<'tcx, (bool, u64)> {
114 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
115 Ok(os_str.encode_wide().collect())
118 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
119 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
120 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
124 .map(|s| s.encode_utf16().collect())
125 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
128 let u16_vec = os_str_to_u16vec(os_str)?;
129 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
130 // 0x0000 terminator to memory would cause an out-of-bounds access.
131 let string_length = u64::try_from(u16_vec.len()).unwrap();
132 if size <= string_length {
133 return Ok((false, string_length));
136 // Store the UTF-16 string.
137 self.eval_context_mut()
139 .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
140 Ok((true, string_length))
143 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
144 fn alloc_os_str_as_c_str(
147 memkind: MemoryKind<MiriMemoryKind>,
149 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
150 let this = self.eval_context_mut();
152 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
153 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
154 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
155 arg_place.ptr.assert_ptr()
158 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
159 fn alloc_os_str_as_wide_str(
162 memkind: MemoryKind<MiriMemoryKind>,
164 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
165 let this = self.eval_context_mut();
167 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
168 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
169 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
170 arg_place.ptr.assert_ptr()
173 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
174 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
179 let this = self.eval_context_ref();
180 let os_str = this.read_os_str_from_c_str(scalar)?;
183 return Ok(if this.tcx.sess.target.target.target_os == "windows" {
184 // Windows-on-Windows, all fine.
185 Cow::Borrowed(Path::new(os_str))
187 // Unix target, Windows host. Need to convert target '/' to host '\'.
188 let converted = os_str
190 .map(|wchar| if wchar == '/' as u16 { '\\' as u16 } else { wchar })
191 .collect::<Vec<_>>();
192 Cow::Owned(PathBuf::from(OsString::from_wide(&converted)))
195 return Ok(if this.tcx.sess.target.target.target_os == "windows" {
196 // Windows target, Unix host. Need to convert target '\' to host '/'.
197 let converted = os_str
200 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
201 .collect::<Vec<_>>();
202 Cow::Owned(PathBuf::from(OsString::from_vec(converted)))
204 // Unix-on-Unix, all is fine.
205 Cow::Borrowed(Path::new(os_str))
209 /// Write a Path to the machine memory, adjusting path separators if needed.
210 fn write_path_to_c_str(
215 ) -> InterpResult<'tcx, (bool, u64)> {
216 let this = self.eval_context_mut();
219 let os_str = if this.tcx.sess.target.target.target_os == "windows" {
220 // Windows-on-Windows, all fine.
221 Cow::Borrowed(path.as_os_str())
223 // Unix target, Windows host. Need to convert host '\\' to target '/'.
227 .map(|wchar| if wchar == '\\' as u16 { '/' as u16 } else { wchar })
228 .collect::<Vec<_>>();
229 Cow::Owned(OsString::from_wide(&converted))
232 let os_str = if this.tcx.sess.target.target.target_os == "windows" {
233 // Windows target, Unix host. Need to convert host '/' to target '\'.
238 .map(|&wchar| if wchar == '/' as u8 { '\\' as u8 } else { wchar })
239 .collect::<Vec<_>>();
240 Cow::Owned(OsString::from_vec(converted))
242 // Unix-on-Unix, all is fine.
243 Cow::Borrowed(path.as_os_str())
246 this.write_os_str_to_c_str(&os_str, scalar, size)