2 use std::convert::TryFrom;
3 use std::ffi::{OsStr, OsString};
5 use std::path::{Path, PathBuf};
8 use std::os::unix::ffi::{OsStrExt, OsStringExt};
10 use std::os::windows::ffi::{OsStrExt, OsStringExt};
12 use rustc_target::abi::{Align, LayoutOf, Size};
16 /// Represent how path separator conversion should be done.
17 pub enum PathConversion {
23 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
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
34 .map(|s| s.as_bytes())
35 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
39 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
40 Ok(OsStr::from_bytes(bytes))
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))?;
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>
58 let this = self.eval_context_ref();
59 let bytes = this.read_c_str(sptr)?;
60 bytes_to_os_str(bytes)
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>
71 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
72 Ok(OsString::from_wide(&u16_vec[..]))
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))?;
81 let u16_vec = self.eval_context_ref().read_wide_str(sptr)?;
82 u16vec_to_osstring(u16_vec)
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(
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));
103 self.eval_context_mut()
105 .write_bytes(sptr, bytes.iter().copied().chain(iter::once(0u8)))?;
106 Ok((true, string_length))
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(
119 ) -> InterpResult<'tcx, (bool, u64)> {
121 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
122 Ok(os_str.encode_wide().collect())
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
131 .map(|s| s.encode_utf16().collect())
132 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
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));
144 // Store the UTF-16 string.
145 let size2 = Size::from_bytes(2);
146 let this = self.eval_context_mut();
149 .get_mut(sptr, size2 * string_length, Align::from_bytes(2).unwrap())?
150 .unwrap(); // not a ZST, so we will get a result
151 for (offset, wchar) in u16_vec.into_iter().chain(iter::once(0x0000)).enumerate() {
152 let offset = u64::try_from(offset).unwrap();
154 .write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar).into())?;
156 Ok((true, string_length - 1))
159 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
160 fn alloc_os_str_as_c_str(
163 memkind: MemoryKind<MiriMemoryKind>,
164 ) -> InterpResult<'tcx, Pointer<Tag>> {
165 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
166 let this = self.eval_context_mut();
168 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
169 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
170 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
171 Ok(arg_place.ptr.assert_ptr())
174 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
175 fn alloc_os_str_as_wide_str(
178 memkind: MemoryKind<MiriMemoryKind>,
179 ) -> InterpResult<'tcx, Pointer<Tag>> {
180 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
181 let this = self.eval_context_mut();
183 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
184 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
185 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
186 Ok(arg_place.ptr.assert_ptr())
189 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
190 fn read_path_from_c_str<'a>(&'a self, sptr: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
195 let this = self.eval_context_ref();
196 let os_str = this.read_os_str_from_c_str(sptr)?;
198 Ok(match this.convert_path_separator(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
199 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
200 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
204 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
205 fn read_path_from_wide_str(&self, sptr: Scalar<Tag>) -> InterpResult<'tcx, PathBuf> {
206 let this = self.eval_context_ref();
207 let os_str = this.read_os_str_from_wide_str(sptr)?;
210 .convert_path_separator(Cow::Owned(os_str), PathConversion::TargetToHost)
215 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
216 /// adjusting path separators if needed.
217 fn write_path_to_c_str(
222 ) -> InterpResult<'tcx, (bool, u64)> {
223 let this = self.eval_context_mut();
225 .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
226 this.write_os_str_to_c_str(&os_str, sptr, size)
229 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
230 /// adjusting path separators if needed.
231 fn write_path_to_wide_str(
236 ) -> InterpResult<'tcx, (bool, u64)> {
237 let this = self.eval_context_mut();
239 .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
240 this.write_os_str_to_wide_str(&os_str, sptr, size)
243 fn convert_path_separator<'a>(
245 os_str: Cow<'a, OsStr>,
246 direction: PathConversion,
247 ) -> Cow<'a, OsStr> {
248 let this = self.eval_context_ref();
249 let target_os = &this.tcx.sess.target.os;
251 return if target_os == "windows" {
252 // Windows-on-Windows, all fine.
255 // Unix target, Windows host.
256 let (from, to) = match direction {
257 PathConversion::HostToTarget => ('\\', '/'),
258 PathConversion::TargetToHost => ('/', '\\'),
260 let converted = os_str
262 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
263 .collect::<Vec<_>>();
264 Cow::Owned(OsString::from_wide(&converted))
267 return if target_os == "windows" {
268 // Windows target, Unix host.
269 let (from, to) = match direction {
270 PathConversion::HostToTarget => ('/', '\\'),
271 PathConversion::TargetToHost => ('\\', '/'),
273 let converted = os_str
276 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
277 .collect::<Vec<_>>();
278 Cow::Owned(OsString::from_vec(converted))
280 // Unix-on-Unix, all is fine.