2 use std::ffi::{OsStr, OsString};
3 use std::path::{Path, PathBuf};
6 use std::os::unix::ffi::{OsStrExt, OsStringExt};
8 use std::os::windows::ffi::{OsStrExt, OsStringExt};
10 use rustc_middle::ty::layout::LayoutOf;
14 /// Represent how path separator conversion should be done.
15 pub enum PathConversion {
21 pub fn os_str_to_bytes<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, &[u8]> {
26 pub fn os_str_to_bytes<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, &[u8]> {
27 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
28 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
32 .map(|s| s.as_bytes())
33 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
37 pub fn bytes_to_os_str<'tcx>(bytes: &[u8]) -> InterpResult<'tcx, &OsStr> {
38 Ok(OsStr::from_bytes(bytes))
41 pub fn bytes_to_os_str<'tcx>(bytes: &[u8]) -> InterpResult<'tcx, &OsStr> {
42 let s = std::str::from_utf8(bytes)
43 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
47 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
48 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
49 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
50 /// the Unix APIs usually handle.
51 fn read_os_str_from_c_str<'a>(
53 ptr: Pointer<Option<Provenance>>,
54 ) -> InterpResult<'tcx, &'a OsStr>
59 let this = self.eval_context_ref();
60 let bytes = this.read_c_str(ptr)?;
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>(
68 ptr: Pointer<Option<Provenance>>,
69 ) -> InterpResult<'tcx, OsString>
75 pub fn u16vec_to_osstring<'tcx>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
76 Ok(OsString::from_wide(&u16_vec[..]))
79 pub fn u16vec_to_osstring<'tcx>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
80 let s = String::from_utf16(&u16_vec[..])
81 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
85 let u16_vec = self.eval_context_ref().read_wide_str(ptr)?;
86 u16vec_to_osstring(u16_vec)
89 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
90 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
91 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
92 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
93 /// string length returned does include the null terminator.
94 fn write_os_str_to_c_str(
97 ptr: Pointer<Option<Provenance>>,
99 ) -> InterpResult<'tcx, (bool, u64)> {
100 let bytes = os_str_to_bytes(os_str)?;
101 self.eval_context_mut().write_c_str(bytes, ptr, size)
104 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
105 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
106 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
107 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
108 /// string length returned does include the null terminator. Length is measured in units of
110 fn write_os_str_to_wide_str(
113 ptr: Pointer<Option<Provenance>>,
115 ) -> InterpResult<'tcx, (bool, u64)> {
117 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
118 Ok(os_str.encode_wide().collect())
121 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
122 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
123 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
127 .map(|s| s.encode_utf16().collect())
128 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
131 let u16_vec = os_str_to_u16vec(os_str)?;
132 self.eval_context_mut().write_wide_str(&u16_vec, ptr, size)
135 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
136 fn alloc_os_str_as_c_str(
139 memkind: MemoryKind<MiriMemoryKind>,
140 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
141 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
142 let this = self.eval_context_mut();
144 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
145 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
146 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
150 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
151 fn alloc_os_str_as_wide_str(
154 memkind: MemoryKind<MiriMemoryKind>,
155 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
156 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
157 let this = self.eval_context_mut();
159 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
160 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
161 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
165 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
166 fn read_path_from_c_str<'a>(
168 ptr: Pointer<Option<Provenance>>,
169 ) -> InterpResult<'tcx, Cow<'a, Path>>
174 let this = self.eval_context_ref();
175 let os_str = this.read_os_str_from_c_str(ptr)?;
177 Ok(match this.convert_path(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
178 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
179 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
183 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
184 fn read_path_from_wide_str(
186 ptr: Pointer<Option<Provenance>>,
187 ) -> InterpResult<'tcx, PathBuf> {
188 let this = self.eval_context_ref();
189 let os_str = this.read_os_str_from_wide_str(ptr)?;
191 Ok(this.convert_path(Cow::Owned(os_str), PathConversion::TargetToHost).into_owned().into())
194 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
195 /// adjusting path separators if needed.
196 fn write_path_to_c_str(
199 ptr: Pointer<Option<Provenance>>,
201 ) -> InterpResult<'tcx, (bool, u64)> {
202 let this = self.eval_context_mut();
204 this.convert_path(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
205 this.write_os_str_to_c_str(&os_str, ptr, size)
208 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
209 /// adjusting path separators if needed.
210 fn write_path_to_wide_str(
213 ptr: Pointer<Option<Provenance>>,
215 ) -> InterpResult<'tcx, (bool, u64)> {
216 let this = self.eval_context_mut();
218 this.convert_path(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
219 this.write_os_str_to_wide_str(&os_str, ptr, size)
222 /// Allocate enough memory to store a Path as a null-terminated sequence of bytes,
223 /// adjusting path separators if needed.
224 fn alloc_path_as_c_str(
227 memkind: MemoryKind<MiriMemoryKind>,
228 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
229 let this = self.eval_context_mut();
231 this.convert_path(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
232 this.alloc_os_str_as_c_str(&os_str, memkind)
235 #[allow(clippy::get_first)]
238 os_str: Cow<'a, OsStr>,
239 direction: PathConversion,
240 ) -> Cow<'a, OsStr> {
241 let this = self.eval_context_ref();
242 let target_os = &this.tcx.sess.target.os;
245 return if target_os == "windows" {
246 // Windows-on-Windows, all fine.
249 // Unix target, Windows host.
250 let (from, to) = match direction {
251 PathConversion::HostToTarget => ('\\', '/'),
252 PathConversion::TargetToHost => ('/', '\\'),
254 let mut converted = os_str
256 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
257 .collect::<Vec<_>>();
258 // We also have to ensure that absolute paths remain absolute.
260 PathConversion::HostToTarget => {
261 // If this is an absolute Windows path that starts with a drive letter (`C:/...`
262 // after separator conversion), it would not be considered absolute by Unix
264 if converted.get(1).copied() == Some(b':' as u16)
265 && converted.get(2).copied() == Some(b'/' as u16)
267 // We add a `/` at the beginning, to store the absolute Windows
268 // path in something that looks like an absolute Unix path.
269 converted.insert(0, b'/' as u16);
272 PathConversion::TargetToHost => {
273 // If the path is `\C:\`, the leading backslash was probably added by the above code
274 // and we should get rid of it again.
275 if converted.get(0).copied() == Some(b'\\' as u16)
276 && converted.get(2).copied() == Some(b':' as u16)
277 && converted.get(3).copied() == Some(b'\\' as u16)
283 Cow::Owned(OsString::from_wide(&converted))
286 return if target_os == "windows" {
287 // Windows target, Unix host.
288 let (from, to) = match direction {
289 PathConversion::HostToTarget => (b'/', b'\\'),
290 PathConversion::TargetToHost => (b'\\', b'/'),
292 let mut converted = os_str
295 .map(|&wchar| if wchar == from { to } else { wchar })
296 .collect::<Vec<_>>();
297 // We also have to ensure that absolute paths remain absolute.
299 PathConversion::HostToTarget => {
300 // If this start withs a `\`, we add `\\?` so it starts with `\\?\` which is
301 // some magic path on Windos that *is* considered absolute.
302 if converted.get(0).copied() == Some(b'\\') {
303 converted.splice(0..0, b"\\\\?".iter().copied());
306 PathConversion::TargetToHost => {
307 // If this starts with `//?/`, it was probably produced by the above code and we
308 // remove the `//?` that got added to get the Unix path back out.
309 if converted.get(0).copied() == Some(b'/')
310 && converted.get(1).copied() == Some(b'/')
311 && converted.get(2).copied() == Some(b'?')
312 && converted.get(3).copied() == Some(b'/')
314 // Remove first 3 characters
315 converted.splice(0..3, std::iter::empty());
319 Cow::Owned(OsString::from_vec(converted))
321 // Unix-on-Unix, all is fine.