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::LayoutOf;
16 /// Represent how path separator conversion should be done.
22 /// Perform path separator conversion if needed.
23 fn convert_path_separator<'a>(
24 os_str: Cow<'a, OsStr>,
26 direction: Pathconversion,
29 return if target_os == "windows" {
30 // Windows-on-Windows, all fine.
33 // Unix target, Windows host.
34 let (from, to) = match direction {
35 Pathconversion::HostToTarget => ('\\', '/'),
36 Pathconversion::TargetToHost => ('/', '\\'),
38 let converted = os_str
40 .map(|wchar| if wchar == from as u16 { to as u16 } else { wchar })
42 Cow::Owned(OsString::from_wide(&converted))
45 return if target_os == "windows" {
46 // Windows target, Unix host.
47 let (from, to) = match direction {
48 Pathconversion::HostToTarget => ('/', '\\'),
49 Pathconversion::TargetToHost => ('\\', '/'),
51 let converted = os_str
54 .map(|&wchar| if wchar == from as u8 { to as u8 } else { wchar })
56 Cow::Owned(OsString::from_vec(converted))
58 // Unix-on-Unix, all is fine.
63 impl<'mir, 'tcx> 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>
73 fn bytes_to_os_str<'tcx, 'a>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
74 Ok(OsStr::from_bytes(bytes))
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))?;
83 let this = self.eval_context_ref();
84 let bytes = this.memory.read_c_str(scalar)?;
85 bytes_to_os_str(bytes)
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>
96 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
97 Ok(OsString::from_wide(&u16_vec[..]))
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))?;
106 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
107 u16vec_to_osstring(u16_vec)
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(
120 ) -> InterpResult<'tcx, (bool, u64)> {
122 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
123 Ok(os_str.as_bytes())
126 fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
127 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
128 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
132 .map(|s| s.as_bytes())
133 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
136 let bytes = os_str_to_bytes(os_str)?;
137 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
138 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
139 let string_length = u64::try_from(bytes.len()).unwrap();
140 if size <= string_length {
141 return Ok((false, string_length));
143 self.eval_context_mut()
145 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
146 Ok((true, string_length))
149 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
150 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
151 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
152 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
153 /// string length returned does not include the null terminator.
154 fn write_os_str_to_wide_str(
159 ) -> InterpResult<'tcx, (bool, u64)> {
161 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
162 Ok(os_str.encode_wide().collect())
165 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
166 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
167 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
171 .map(|s| s.encode_utf16().collect())
172 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
175 let u16_vec = os_str_to_u16vec(os_str)?;
176 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
177 // 0x0000 terminator to memory would cause an out-of-bounds access.
178 let string_length = u64::try_from(u16_vec.len()).unwrap();
179 if size <= string_length {
180 return Ok((false, string_length));
183 // Store the UTF-16 string.
184 self.eval_context_mut()
186 .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
187 Ok((true, string_length))
190 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
191 fn alloc_os_str_as_c_str(
194 memkind: MemoryKind<MiriMemoryKind>,
196 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
197 let this = self.eval_context_mut();
199 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
200 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
201 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
202 arg_place.ptr.assert_ptr()
205 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
206 fn alloc_os_str_as_wide_str(
209 memkind: MemoryKind<MiriMemoryKind>,
211 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
212 let this = self.eval_context_mut();
214 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
215 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
216 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
217 arg_place.ptr.assert_ptr()
220 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
221 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
226 let this = self.eval_context_ref();
227 let os_str = this.read_os_str_from_c_str(scalar)?;
229 Ok(match convert_path_separator(Cow::Borrowed(os_str), &this.tcx.sess.target.target.target_os, Pathconversion::TargetToHost) {
230 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
231 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
235 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
236 fn read_path_from_wide_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, PathBuf> {
237 let this = self.eval_context_ref();
238 let os_str = this.read_os_str_from_wide_str(scalar)?;
240 Ok(convert_path_separator(Cow::Owned(os_str), &this.tcx.sess.target.target.target_os, Pathconversion::TargetToHost).into_owned().into())
243 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
244 /// adjusting path separators if needed.
245 fn write_path_to_c_str(
250 ) -> InterpResult<'tcx, (bool, u64)> {
251 let this = self.eval_context_mut();
252 let os_str = convert_path_separator(Cow::Borrowed(path.as_os_str()), &this.tcx.sess.target.target.target_os, Pathconversion::HostToTarget);
253 this.write_os_str_to_c_str(&os_str, scalar, size)
256 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
257 /// adjusting path separators if needed.
258 fn write_path_to_wide_str(
263 ) -> InterpResult<'tcx, (bool, u64)> {
264 let this = self.eval_context_mut();
265 let os_str = convert_path_separator(Cow::Borrowed(path.as_os_str()), &this.tcx.sess.target.target.target_os, Pathconversion::HostToTarget);
266 this.write_os_str_to_wide_str(&os_str, scalar, size)