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