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_middle::ty::layout::LayoutOf;
13 use rustc_target::abi::{Align, Size};
17 /// Represent how path separator conversion should be done.
18 pub enum PathConversion {
24 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
29 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
30 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
31 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
35 .map(|s| s.as_bytes())
36 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
40 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
41 Ok(OsStr::from_bytes(bytes))
44 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
45 let s = std::str::from_utf8(bytes)
46 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
50 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
51 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
52 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
53 /// the Unix APIs usually handle.
54 fn read_os_str_from_c_str<'a>(
56 ptr: Pointer<Option<Tag>>,
57 ) -> InterpResult<'tcx, &'a OsStr>
62 let this = self.eval_context_ref();
63 let bytes = this.read_c_str(ptr)?;
64 bytes_to_os_str(bytes)
67 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
68 /// which is what the Windows APIs usually handle.
69 fn read_os_str_from_wide_str<'a>(
71 ptr: Pointer<Option<Tag>>,
72 ) -> InterpResult<'tcx, OsString>
78 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
79 Ok(OsString::from_wide(&u16_vec[..]))
82 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
83 let s = String::from_utf16(&u16_vec[..])
84 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
88 let u16_vec = self.eval_context_ref().read_wide_str(ptr)?;
89 u16vec_to_osstring(u16_vec)
92 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
93 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
94 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
95 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
96 /// string length returned does not include the null terminator.
97 fn write_os_str_to_c_str(
100 ptr: Pointer<Option<Tag>>,
102 ) -> InterpResult<'tcx, (bool, u64)> {
103 let bytes = os_str_to_bytes(os_str)?;
104 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
105 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
106 let string_length = u64::try_from(bytes.len()).unwrap();
107 if size <= string_length {
108 return Ok((false, string_length));
110 self.eval_context_mut()
111 .write_bytes_ptr(ptr, bytes.iter().copied().chain(iter::once(0u8)))?;
112 Ok((true, string_length))
115 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
116 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
117 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
118 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
119 /// string length returned does not include the null terminator.
120 fn write_os_str_to_wide_str(
123 ptr: Pointer<Option<Tag>>,
125 ) -> InterpResult<'tcx, (bool, u64)> {
127 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
128 Ok(os_str.encode_wide().collect())
131 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
132 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
133 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
137 .map(|s| s.encode_utf16().collect())
138 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
141 let u16_vec = os_str_to_u16vec(os_str)?;
142 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
143 // 0x0000 terminator to memory would cause an out-of-bounds access.
144 let string_length = u64::try_from(u16_vec.len()).unwrap();
145 let string_length = string_length.checked_add(1).unwrap();
146 if size < string_length {
147 return Ok((false, string_length));
150 // Store the UTF-16 string.
151 let size2 = Size::from_bytes(2);
152 let this = self.eval_context_mut();
154 .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
155 .unwrap(); // not a ZST, so we will get a result
156 for (offset, wchar) in u16_vec.into_iter().chain(iter::once(0x0000)).enumerate() {
157 let offset = u64::try_from(offset).unwrap();
159 .write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar).into())?;
161 Ok((true, string_length - 1))
164 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
165 fn alloc_os_str_as_c_str(
168 memkind: MemoryKind<MiriMemoryKind>,
169 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
170 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
171 let this = self.eval_context_mut();
173 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
174 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
175 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
179 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
180 fn alloc_os_str_as_wide_str(
183 memkind: MemoryKind<MiriMemoryKind>,
184 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
185 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
186 let this = self.eval_context_mut();
188 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
189 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
190 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
194 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
195 fn read_path_from_c_str<'a>(
197 ptr: Pointer<Option<Tag>>,
198 ) -> InterpResult<'tcx, Cow<'a, Path>>
203 let this = self.eval_context_ref();
204 let os_str = this.read_os_str_from_c_str(ptr)?;
206 Ok(match this.convert_path_separator(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
207 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
208 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
212 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
213 fn read_path_from_wide_str(&self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, PathBuf> {
214 let this = self.eval_context_ref();
215 let os_str = this.read_os_str_from_wide_str(ptr)?;
218 .convert_path_separator(Cow::Owned(os_str), PathConversion::TargetToHost)
223 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
224 /// adjusting path separators if needed.
225 fn write_path_to_c_str(
228 ptr: Pointer<Option<Tag>>,
230 ) -> InterpResult<'tcx, (bool, u64)> {
231 let this = self.eval_context_mut();
233 .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
234 this.write_os_str_to_c_str(&os_str, ptr, size)
237 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
238 /// adjusting path separators if needed.
239 fn write_path_to_wide_str(
242 ptr: Pointer<Option<Tag>>,
244 ) -> InterpResult<'tcx, (bool, u64)> {
245 let this = self.eval_context_mut();
247 .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
248 this.write_os_str_to_wide_str(&os_str, ptr, size)
251 fn convert_path_separator<'a>(
253 os_str: Cow<'a, OsStr>,
254 direction: PathConversion,
255 ) -> Cow<'a, OsStr> {
256 let this = self.eval_context_ref();
257 let target_os = &this.tcx.sess.target.os;
259 return if target_os == "windows" {
260 // Windows-on-Windows, all fine.
263 // Unix target, Windows host.
264 let (from, to) = match direction {
265 PathConversion::HostToTarget => ('\\', '/'),
266 PathConversion::TargetToHost => ('/', '\\'),
268 let converted = os_str
270 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
271 .collect::<Vec<_>>();
272 Cow::Owned(OsString::from_wide(&converted))
275 return if target_os == "windows" {
276 // Windows target, Unix host.
277 let (from, to) = match direction {
278 PathConversion::HostToTarget => ('/', '\\'),
279 PathConversion::TargetToHost => ('\\', '/'),
281 let converted = os_str
284 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
285 .collect::<Vec<_>>();
286 Cow::Owned(OsString::from_vec(converted))
288 // Unix-on-Unix, all is fine.