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