]> git.lizzy.rs Git - rust.git/blob - src/shims/os_str.rs
format much of Miri
[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::LayoutOf;
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, scalar: 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.memory.read_c_str(scalar)?;
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, scalar: 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().memory.read_wide_str(scalar)?;
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         scalar: 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(scalar, 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         scalar: 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         if size <= string_length {
140             return Ok((false, string_length));
141         }
142
143         // Store the UTF-16 string.
144         self.eval_context_mut()
145             .memory
146             .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
147         Ok((true, string_length))
148     }
149
150     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
151     fn alloc_os_str_as_c_str(
152         &mut self,
153         os_str: &OsStr,
154         memkind: MemoryKind<MiriMemoryKind>,
155     ) -> Pointer<Tag> {
156         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
157         let this = self.eval_context_mut();
158
159         let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
160         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
161         assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
162         arg_place.ptr.assert_ptr()
163     }
164
165     /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
166     fn alloc_os_str_as_wide_str(
167         &mut self,
168         os_str: &OsStr,
169         memkind: MemoryKind<MiriMemoryKind>,
170     ) -> Pointer<Tag> {
171         let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
172         let this = self.eval_context_mut();
173
174         let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
175         let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
176         assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
177         arg_place.ptr.assert_ptr()
178     }
179
180     /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
181     fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
182     where
183         'tcx: 'a,
184         'mir: 'a,
185     {
186         let this = self.eval_context_ref();
187         let os_str = this.read_os_str_from_c_str(scalar)?;
188
189         Ok(match this.convert_path_separator(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
190             Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
191             Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
192         })
193     }
194
195     /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
196     fn read_path_from_wide_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, PathBuf> {
197         let this = self.eval_context_ref();
198         let os_str = this.read_os_str_from_wide_str(scalar)?;
199
200         Ok(this
201             .convert_path_separator(Cow::Owned(os_str), PathConversion::TargetToHost)
202             .into_owned()
203             .into())
204     }
205
206     /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
207     /// adjusting path separators if needed.
208     fn write_path_to_c_str(
209         &mut self,
210         path: &Path,
211         scalar: Scalar<Tag>,
212         size: u64,
213     ) -> InterpResult<'tcx, (bool, u64)> {
214         let this = self.eval_context_mut();
215         let os_str = this
216             .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
217         this.write_os_str_to_c_str(&os_str, scalar, size)
218     }
219
220     /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
221     /// adjusting path separators if needed.
222     fn write_path_to_wide_str(
223         &mut self,
224         path: &Path,
225         scalar: Scalar<Tag>,
226         size: u64,
227     ) -> InterpResult<'tcx, (bool, u64)> {
228         let this = self.eval_context_mut();
229         let os_str = this
230             .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
231         this.write_os_str_to_wide_str(&os_str, scalar, size)
232     }
233
234     fn convert_path_separator<'a>(
235         &self,
236         os_str: Cow<'a, OsStr>,
237         direction: PathConversion,
238     ) -> Cow<'a, OsStr> {
239         let this = self.eval_context_ref();
240         let target_os = &this.tcx.sess.target.os;
241         #[cfg(windows)]
242         return if target_os == "windows" {
243             // Windows-on-Windows, all fine.
244             os_str
245         } else {
246             // Unix target, Windows host.
247             let (from, to) = match direction {
248                 PathConversion::HostToTarget => ('\\', '/'),
249                 PathConversion::TargetToHost => ('/', '\\'),
250             };
251             let converted = os_str
252                 .encode_wide()
253                 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
254                 .collect::<Vec<_>>();
255             Cow::Owned(OsString::from_wide(&converted))
256         };
257         #[cfg(unix)]
258         return if target_os == "windows" {
259             // Windows target, Unix host.
260             let (from, to) = match direction {
261                 PathConversion::HostToTarget => ('/', '\\'),
262                 PathConversion::TargetToHost => ('\\', '/'),
263             };
264             let converted = os_str
265                 .as_bytes()
266                 .iter()
267                 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
268                 .collect::<Vec<_>>();
269             Cow::Owned(OsString::from_vec(converted))
270         } else {
271             // Unix-on-Unix, all is fine.
272             os_str
273         };
274     }
275 }