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_target::abi::LayoutOf;
16 /// Represent how path separator conversion should be done.
17 pub enum PathConversion {
23 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
28 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
29 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
30 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
34 .map(|s| s.as_bytes())
35 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
39 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
40 Ok(OsStr::from_bytes(bytes))
43 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
44 let s = std::str::from_utf8(bytes)
45 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
49 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
50 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
52 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
53 /// the Unix APIs usually handle.
54 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
59 let this = self.eval_context_ref();
60 let bytes = this.memory.read_c_str(scalar)?;
61 bytes_to_os_str(bytes)
64 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
65 /// which is what the Windows APIs usually handle.
66 fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
72 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
73 Ok(OsString::from_wide(&u16_vec[..]))
76 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
77 let s = String::from_utf16(&u16_vec[..])
78 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
82 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
83 u16vec_to_osstring(u16_vec)
86 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
87 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
88 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
89 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
90 /// string length returned does not include the null terminator.
91 fn write_os_str_to_c_str(
96 ) -> InterpResult<'tcx, (bool, u64)> {
98 let bytes = os_str_to_bytes(os_str)?;
99 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
100 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
101 let string_length = u64::try_from(bytes.len()).unwrap();
102 if size <= string_length {
103 return Ok((false, string_length));
105 self.eval_context_mut()
107 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
108 Ok((true, string_length))
111 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
112 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
113 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
114 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
115 /// string length returned does not include the null terminator.
116 fn write_os_str_to_wide_str(
121 ) -> InterpResult<'tcx, (bool, u64)> {
123 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
124 Ok(os_str.encode_wide().collect())
127 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
128 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
129 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
133 .map(|s| s.encode_utf16().collect())
134 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
137 let u16_vec = os_str_to_u16vec(os_str)?;
138 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
139 // 0x0000 terminator to memory would cause an out-of-bounds access.
140 let string_length = u64::try_from(u16_vec.len()).unwrap();
141 if size <= string_length {
142 return Ok((false, string_length));
145 // Store the UTF-16 string.
146 self.eval_context_mut()
148 .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
149 Ok((true, string_length))
152 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
153 fn alloc_os_str_as_c_str(
156 memkind: MemoryKind<MiriMemoryKind>,
158 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
159 let this = self.eval_context_mut();
161 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
162 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
163 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
164 arg_place.ptr.assert_ptr()
167 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
168 fn alloc_os_str_as_wide_str(
171 memkind: MemoryKind<MiriMemoryKind>,
173 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
174 let this = self.eval_context_mut();
176 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
177 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
178 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
179 arg_place.ptr.assert_ptr()
182 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
183 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
188 let this = self.eval_context_ref();
189 let os_str = this.read_os_str_from_c_str(scalar)?;
191 Ok(match this.convert_path_separator(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
192 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
193 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
197 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
198 fn read_path_from_wide_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, PathBuf> {
199 let this = self.eval_context_ref();
200 let os_str = this.read_os_str_from_wide_str(scalar)?;
202 Ok(this.convert_path_separator(Cow::Owned(os_str), PathConversion::TargetToHost).into_owned().into())
205 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
206 /// adjusting path separators if needed.
207 fn write_path_to_c_str(
212 ) -> InterpResult<'tcx, (bool, u64)> {
213 let this = self.eval_context_mut();
214 let os_str = this.convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
215 this.write_os_str_to_c_str(&os_str, scalar, size)
218 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
219 /// adjusting path separators if needed.
220 fn write_path_to_wide_str(
225 ) -> InterpResult<'tcx, (bool, u64)> {
226 let this = self.eval_context_mut();
227 let os_str = this.convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
228 this.write_os_str_to_wide_str(&os_str, scalar, size)
231 fn convert_path_separator<'a>(
233 os_str: Cow<'a, OsStr>,
234 direction: PathConversion,
235 ) -> Cow<'a, OsStr> {
236 let this = self.eval_context_ref();
237 let target_os = &this.tcx.sess.target.target.target_os;
239 return if target_os == "windows" {
240 // Windows-on-Windows, all fine.
243 // Unix target, Windows host.
244 let (from, to) = match direction {
245 PathConversion::HostToTarget => ('\\', '/'),
246 PathConversion::TargetToHost => ('/', '\\'),
248 let converted = os_str
250 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
251 .collect::<Vec<_>>();
252 Cow::Owned(OsString::from_wide(&converted))
255 return if target_os == "windows" {
256 // Windows target, Unix host.
257 let (from, to) = match direction {
258 PathConversion::HostToTarget => ('/', '\\'),
259 PathConversion::TargetToHost => ('\\', '/'),
261 let converted = os_str
264 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
265 .collect::<Vec<_>>();
266 Cow::Owned(OsString::from_vec(converted))
268 // Unix-on-Unix, all is fine.