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: &'a OsStr = this.read_os_str_from_c_str(scalar)?;
182 Ok(match convert_path_separator(os_str, &this.tcx.sess.target.target.target_os, false) {
183 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
184 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
188 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
189 fn read_path_from_wide_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, PathBuf> {
190 let this = self.eval_context_ref();
191 let os_str: OsString = this.read_os_str_from_wide_str(scalar)?;
193 Ok(PathBuf::from(&convert_path_separator(&os_str, &this.tcx.sess.target.target.target_os, false)))
196 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
197 /// adjusting path separators if needed.
198 fn write_path_to_c_str(
203 ) -> InterpResult<'tcx, (bool, u64)> {
204 let this = self.eval_context_mut();
205 let os_str = convert_path_separator(path.as_os_str(), &this.tcx.sess.target.target.target_os, true);
206 this.write_os_str_to_c_str(&os_str, scalar, size)
209 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
210 /// adjusting path separators if needed.
211 fn write_path_to_wide_str(
216 ) -> InterpResult<'tcx, (bool, u64)> {
217 let this = self.eval_context_mut();
218 let os_str = convert_path_separator(path.as_os_str(), &this.tcx.sess.target.target.target_os, true);
219 this.write_os_str_to_wide_str(&os_str, scalar, size)
223 /// Perform path separator conversion if needed.
224 /// if direction == true, Convert from 'host' to 'target'.
225 /// if direction == false, Convert from 'target' to 'host'.
226 fn convert_path_separator<'a>(
230 ) -> Cow<'a, OsStr> {
232 return if target_os == "windows" {
233 // Windows-on-Windows, all fine.
234 Cow::Borrowed(os_str)
236 // Unix target, Windows host.
237 let (from, to) = if direction { ('\\', '/') } else { ('/', '\\') };
238 let converted = os_str
240 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
241 .collect::<Vec<_>>();
242 Cow::Owned(OsString::from_wide(&converted))
245 return if target_os == "windows" {
246 // Windows target, Unix host.
247 let (from, to) = if direction { ('/', '\\') } else { ('\\', '/') };
248 let converted = os_str
251 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
252 .collect::<Vec<_>>();
253 Cow::Owned(OsString::from_vec(converted))
255 // Unix-on-Unix, all is fine.
256 Cow::Borrowed(os_str)