2 use std::ffi::{OsStr, OsString};
4 use std::path::{Path, PathBuf};
7 use std::os::unix::ffi::{OsStrExt, OsStringExt};
9 use std::os::windows::ffi::{OsStrExt, OsStringExt};
11 use rustc_middle::ty::layout::LayoutOf;
12 use rustc_target::abi::{Align, 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>(
55 ptr: Pointer<Option<Tag>>,
56 ) -> InterpResult<'tcx, &'a OsStr>
61 let this = self.eval_context_ref();
62 let bytes = this.read_c_str(ptr)?;
63 bytes_to_os_str(bytes)
66 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
67 /// which is what the Windows APIs usually handle.
68 fn read_os_str_from_wide_str<'a>(
70 ptr: Pointer<Option<Tag>>,
71 ) -> InterpResult<'tcx, OsString>
77 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
78 Ok(OsString::from_wide(&u16_vec[..]))
81 pub fn u16vec_to_osstring<'tcx>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
82 let s = String::from_utf16(&u16_vec[..])
83 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
87 let u16_vec = self.eval_context_ref().read_wide_str(ptr)?;
88 u16vec_to_osstring(u16_vec)
91 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
92 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
93 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
94 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
95 /// string length returned does not include the null terminator.
96 fn write_os_str_to_c_str(
99 ptr: Pointer<Option<Tag>>,
101 ) -> InterpResult<'tcx, (bool, u64)> {
102 let bytes = os_str_to_bytes(os_str)?;
103 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
104 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
105 let string_length = u64::try_from(bytes.len()).unwrap();
106 if size <= string_length {
107 return Ok((false, string_length));
109 self.eval_context_mut()
110 .write_bytes_ptr(ptr, bytes.iter().copied().chain(iter::once(0u8)))?;
111 Ok((true, string_length))
114 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
115 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
116 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
117 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
118 /// string length returned does not include the null terminator.
119 fn write_os_str_to_wide_str(
122 ptr: Pointer<Option<Tag>>,
124 ) -> InterpResult<'tcx, (bool, u64)> {
126 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
127 Ok(os_str.encode_wide().collect())
130 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
131 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
132 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
136 .map(|s| s.encode_utf16().collect())
137 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
140 let u16_vec = os_str_to_u16vec(os_str)?;
141 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
142 // 0x0000 terminator to memory would cause an out-of-bounds access.
143 let string_length = u64::try_from(u16_vec.len()).unwrap();
144 let string_length = string_length.checked_add(1).unwrap();
145 if size < string_length {
146 return Ok((false, string_length));
149 // Store the UTF-16 string.
150 let size2 = Size::from_bytes(2);
151 let this = self.eval_context_mut();
153 .get_ptr_alloc_mut(ptr, size2 * string_length, Align::from_bytes(2).unwrap())?
154 .unwrap(); // not a ZST, so we will get a result
155 for (offset, wchar) in u16_vec.into_iter().chain(iter::once(0x0000)).enumerate() {
156 let offset = u64::try_from(offset).unwrap();
158 .write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar).into())?;
160 Ok((true, string_length - 1))
163 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
164 fn alloc_os_str_as_c_str(
167 memkind: MemoryKind<MiriMemoryKind>,
168 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
169 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
170 let this = self.eval_context_mut();
172 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
173 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
174 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
178 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
179 fn alloc_os_str_as_wide_str(
182 memkind: MemoryKind<MiriMemoryKind>,
183 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
184 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
185 let this = self.eval_context_mut();
187 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
188 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind)?;
189 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
193 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
194 fn read_path_from_c_str<'a>(
196 ptr: Pointer<Option<Tag>>,
197 ) -> InterpResult<'tcx, Cow<'a, Path>>
202 let this = self.eval_context_ref();
203 let os_str = this.read_os_str_from_c_str(ptr)?;
205 Ok(match this.convert_path_separator(Cow::Borrowed(os_str), PathConversion::TargetToHost) {
206 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
207 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
211 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
212 fn read_path_from_wide_str(&self, ptr: Pointer<Option<Tag>>) -> InterpResult<'tcx, PathBuf> {
213 let this = self.eval_context_ref();
214 let os_str = this.read_os_str_from_wide_str(ptr)?;
217 .convert_path_separator(Cow::Owned(os_str), PathConversion::TargetToHost)
222 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
223 /// adjusting path separators if needed.
224 fn write_path_to_c_str(
227 ptr: Pointer<Option<Tag>>,
229 ) -> InterpResult<'tcx, (bool, u64)> {
230 let this = self.eval_context_mut();
232 .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
233 this.write_os_str_to_c_str(&os_str, ptr, size)
236 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
237 /// adjusting path separators if needed.
238 fn write_path_to_wide_str(
241 ptr: Pointer<Option<Tag>>,
243 ) -> InterpResult<'tcx, (bool, u64)> {
244 let this = self.eval_context_mut();
246 .convert_path_separator(Cow::Borrowed(path.as_os_str()), PathConversion::HostToTarget);
247 this.write_os_str_to_wide_str(&os_str, ptr, size)
250 fn convert_path_separator<'a>(
252 os_str: Cow<'a, OsStr>,
253 direction: PathConversion,
254 ) -> Cow<'a, OsStr> {
255 let this = self.eval_context_ref();
256 let target_os = &this.tcx.sess.target.os;
258 return if target_os == "windows" {
259 // Windows-on-Windows, all fine.
262 // Unix target, Windows host.
263 let (from, to) = match direction {
264 PathConversion::HostToTarget => ('\\', '/'),
265 PathConversion::TargetToHost => ('/', '\\'),
267 let converted = os_str
269 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
270 .collect::<Vec<_>>();
271 Cow::Owned(OsString::from_wide(&converted))
274 return if target_os == "windows" {
275 // Windows target, Unix host.
276 let (from, to) = match direction {
277 PathConversion::HostToTarget => ('/', '\\'),
278 PathConversion::TargetToHost => ('\\', '/'),
280 let converted = os_str
283 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
284 .collect::<Vec<_>>();
285 Cow::Owned(OsString::from_vec(converted))
287 // Unix-on-Unix, all is fine.