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