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