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