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