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