]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/shims/os_str.rs
Rollup merge of #103526 - Rageking8:more-dupe-typos-again, r=Mark-Simulacrum
[rust.git] / src / tools / miri / src / shims / os_str.rs
1 use std::borrow::Cow;
2 use std::ffi::{OsStr, OsString};
3 use std::iter;
4 use std::path::{Path, PathBuf};
5
6 #[cfg(unix)]
7 use std::os::unix::ffi::{OsStrExt, OsStringExt};
8 #[cfg(windows)]
9 use std::os::windows::ffi::{OsStrExt, OsStringExt};
10
11 use rustc_middle::ty::layout::LayoutOf;
12 use rustc_target::abi::{Align, Size};
13
14 use crate::*;
15
16 /// Represent how path separator conversion should be done.
17 pub enum PathConversion {
18     HostToTarget,
19     TargetToHost,
20 }
21
22 #[cfg(unix)]
23 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
24     Ok(os_str.as_bytes())
25 }
26
27 #[cfg(not(unix))]
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
31     // valid.
32     os_str
33         .to_str()
34         .map(|s| s.as_bytes())
35         .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
36 }
37
38 #[cfg(unix)]
39 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
40     Ok(OsStr::from_bytes(bytes))
41 }
42 #[cfg(not(unix))]
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))?;
46     Ok(OsStr::new(s))
47 }
48
49 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
50 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
51     /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
52     /// the Unix APIs usually handle.
53     fn read_os_str_from_c_str<'a>(
54         &'a self,
55         ptr: Pointer<Option<Provenance>>,
56     ) -> InterpResult<'tcx, &'a OsStr>
57     where
58         'tcx: 'a,
59         'mir: 'a,
60     {
61         let this = self.eval_context_ref();
62         let bytes = this.read_c_str(ptr)?;
63         bytes_to_os_str(bytes)
64     }
65
66     /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
67     /// which is what the Windows APIs usually handle.
68     fn read_os_str_from_wide_str<'a>(
69         &'a self,
70         ptr: Pointer<Option<Provenance>>,
71     ) -> InterpResult<'tcx, OsString>
72     where
73         'tcx: 'a,
74         'mir: 'a,
75     {
76         #[cfg(windows)]
77         pub fn u16vec_to_osstring<'tcx>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
78             Ok(OsString::from_wide(&u16_vec[..]))
79         }
80         #[cfg(not(windows))]
81         pub fn u16vec_to_osstring<'tcx>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
82             let s = String::from_utf16(&u16_vec[..])
83                 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
84             Ok(s.into())
85         }
86
87         let u16_vec = self.eval_context_ref().read_wide_str(ptr)?;
88         u16vec_to_osstring(u16_vec)
89     }
90
91     /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
92     /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
93     /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
94     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
95     /// string length returned does include the null terminator.
96     fn write_os_str_to_c_str(
97         &mut self,
98         os_str: &OsStr,
99         ptr: Pointer<Option<Provenance>>,
100         size: u64,
101     ) -> InterpResult<'tcx, (bool, u64)> {
102         let bytes = os_str_to_bytes(os_str)?;
103         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
104         // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
105         let string_length = u64::try_from(bytes.len()).unwrap();
106         let string_length = string_length.checked_add(1).unwrap();
107         if size < string_length {
108             return Ok((false, string_length));
109         }
110         self.eval_context_mut()
111             .write_bytes_ptr(ptr, bytes.iter().copied().chain(iter::once(0u8)))?;
112         Ok((true, string_length))
113     }
114
115     /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
116     /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
117     /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
118     /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
119     /// string length returned does include the null terminator. Length is measured in units of
120     /// `u16.`
121     fn write_os_str_to_wide_str(
122         &mut self,
123         os_str: &OsStr,
124         ptr: Pointer<Option<Provenance>>,
125         size: u64,
126     ) -> InterpResult<'tcx, (bool, u64)> {
127         #[cfg(windows)]
128         fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
129             Ok(os_str.encode_wide().collect())
130         }
131         #[cfg(not(windows))]
132         fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
133             // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
134             // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
135             // valid.
136             os_str
137                 .to_str()
138                 .map(|s| s.encode_utf16().collect())
139                 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
140         }
141
142         let u16_vec = os_str_to_u16vec(os_str)?;
143         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
144         // 0x0000 terminator to memory would cause an out-of-bounds access.
145         let string_length = u64::try_from(u16_vec.len()).unwrap();
146         let string_length = string_length.checked_add(1).unwrap();
147         if size < string_length {
148             return Ok((false, string_length));
149         }
150
151         // Store the UTF-16 string.
152         let size2 = Size::from_bytes(2);
153         let this = self.eval_context_mut();
154         let mut alloc = this
155             .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
156             .unwrap(); // not a ZST, so we will get a result
157         for (offset, wchar) in u16_vec.into_iter().chain(iter::once(0x0000)).enumerate() {
158             let offset = u64::try_from(offset).unwrap();
159             alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
160         }
161         Ok((true, string_length))
162     }
163
164     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
165     fn alloc_os_str_as_c_str(
166         &mut self,
167         os_str: &OsStr,
168         memkind: MemoryKind<MiriMemoryKind>,
169     ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
170         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
171         let this = self.eval_context_mut();
172
173         let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
174         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
175         assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
176         Ok(arg_place.ptr)
177     }
178
179     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
180     fn alloc_os_str_as_wide_str(
181         &mut self,
182         os_str: &OsStr,
183         memkind: MemoryKind<MiriMemoryKind>,
184     ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
185         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
186         let this = self.eval_context_mut();
187
188         let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
189         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
190         assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
191         Ok(arg_place.ptr)
192     }
193
194     /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
195     fn read_path_from_c_str<'a>(
196         &'a self,
197         ptr: Pointer<Option<Provenance>>,
198     ) -> InterpResult<'tcx, Cow<'a, Path>>
199     where
200         'tcx: 'a,
201         'mir: 'a,
202     {
203         let this = self.eval_context_ref();
204         let os_str = this.read_os_str_from_c_str(ptr)?;
205
206         Ok(match this.convert_path_separator(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
207             Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
208             Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
209         })
210     }
211
212     /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
213     fn read_path_from_wide_str(
214         &self,
215         ptr: Pointer<Option<Provenance>>,
216     ) -> InterpResult<'tcx, PathBuf> {
217         let this = self.eval_context_ref();
218         let os_str = this.read_os_str_from_wide_str(ptr)?;
219
220         Ok(this
221             .convert_path_separator(Cow::Owned(os_str), PathConversion::TargetToHost)
222             .into_owned()
223             .into())
224     }
225
226     /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
227     /// adjusting path separators if needed.
228     fn write_path_to_c_str(
229         &mut self,
230         path: &Path,
231         ptr: Pointer<Option<Provenance>>,
232         size: u64,
233     ) -> InterpResult<'tcx, (bool, u64)> {
234         let this = self.eval_context_mut();
235         let os_str = this
236             .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
237         this.write_os_str_to_c_str(&os_str, ptr, size)
238     }
239
240     /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
241     /// adjusting path separators if needed.
242     fn write_path_to_wide_str(
243         &mut self,
244         path: &Path,
245         ptr: Pointer<Option<Provenance>>,
246         size: u64,
247     ) -> InterpResult<'tcx, (bool, u64)> {
248         let this = self.eval_context_mut();
249         let os_str = this
250             .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
251         this.write_os_str_to_wide_str(&os_str, ptr, size)
252     }
253
254     /// Allocate enough memory to store a Path as a null-terminated sequence of bytes,
255     /// adjusting path separators if needed.
256     fn alloc_path_as_c_str(
257         &mut self,
258         path: &Path,
259         memkind: MemoryKind<MiriMemoryKind>,
260     ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
261         let this = self.eval_context_mut();
262         let os_str = this
263             .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
264         this.alloc_os_str_as_c_str(&os_str, memkind)
265     }
266
267     fn convert_path_separator<'a>(
268         &self,
269         os_str: Cow<'a, OsStr>,
270         direction: PathConversion,
271     ) -> Cow<'a, OsStr> {
272         let this = self.eval_context_ref();
273         let target_os = &this.tcx.sess.target.os;
274         #[cfg(windows)]
275         return if target_os == "windows" {
276             // Windows-on-Windows, all fine.
277             os_str
278         } else {
279             // Unix target, Windows host.
280             let (from, to) = match direction {
281                 PathConversion::HostToTarget => ('\\', '/'),
282                 PathConversion::TargetToHost => ('/', '\\'),
283             };
284             let converted = os_str
285                 .encode_wide()
286                 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
287                 .collect::<Vec<_>>();
288             Cow::Owned(OsString::from_wide(&converted))
289         };
290         #[cfg(unix)]
291         return if target_os == "windows" {
292             // Windows target, Unix host.
293             let (from, to) = match direction {
294                 PathConversion::HostToTarget => ('/', '\\'),
295                 PathConversion::TargetToHost => ('\\', '/'),
296             };
297             let converted = os_str
298                 .as_bytes()
299                 .iter()
300                 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
301                 .collect::<Vec<_>>();
302             Cow::Owned(OsString::from_vec(converted))
303         } else {
304             // Unix-on-Unix, all is fine.
305             os_str
306         };
307     }
308 }