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