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.
64 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
69 pub fn os_str_to_bytes<'a, 'tcx>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]> {
70 // On non-unix platforms the best we can do to transform bytes from/to OS strings is to do the
71 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
75 .map(|s| s.as_bytes())
76 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
80 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
81 Ok(OsStr::from_bytes(bytes))
84 pub fn bytes_to_os_str<'a, 'tcx>(bytes: &'a [u8]) -> InterpResult<'tcx, &'a OsStr> {
85 let s = std::str::from_utf8(bytes)
86 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", bytes))?;
90 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
91 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
93 /// Helper function to read an OsString from a null-terminated sequence of bytes, which is what
94 /// the Unix APIs usually handle.
95 fn read_os_str_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, &'a OsStr>
100 let this = self.eval_context_ref();
101 let bytes = this.memory.read_c_str(scalar)?;
102 bytes_to_os_str(bytes)
105 /// Helper function to read an OsString from a 0x0000-terminated sequence of u16,
106 /// which is what the Windows APIs usually handle.
107 fn read_os_str_from_wide_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, OsString>
113 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
114 Ok(OsString::from_wide(&u16_vec[..]))
117 pub fn u16vec_to_osstring<'tcx, 'a>(u16_vec: Vec<u16>) -> InterpResult<'tcx, OsString> {
118 let s = String::from_utf16(&u16_vec[..])
119 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-16 string", u16_vec))?;
123 let u16_vec = self.eval_context_ref().memory.read_wide_str(scalar)?;
124 u16vec_to_osstring(u16_vec)
127 /// Helper function to write an OsStr as a null-terminated sequence of bytes, which is what
128 /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
129 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
130 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
131 /// string length returned does not include the null terminator.
132 fn write_os_str_to_c_str(
137 ) -> InterpResult<'tcx, (bool, u64)> {
139 let bytes = os_str_to_bytes(os_str)?;
140 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
141 // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
142 let string_length = u64::try_from(bytes.len()).unwrap();
143 if size <= string_length {
144 return Ok((false, string_length));
146 self.eval_context_mut()
148 .write_bytes(scalar, bytes.iter().copied().chain(iter::once(0u8)))?;
149 Ok((true, string_length))
152 /// Helper function to write an OsStr as a 0x0000-terminated u16-sequence, which is what
153 /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
154 /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
155 /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
156 /// string length returned does not include the null terminator.
157 fn write_os_str_to_wide_str(
162 ) -> InterpResult<'tcx, (bool, u64)> {
164 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
165 Ok(os_str.encode_wide().collect())
168 fn os_str_to_u16vec<'tcx>(os_str: &OsStr) -> InterpResult<'tcx, Vec<u16>> {
169 // On non-Windows platforms the best we can do to transform Vec<u16> from/to OS strings is to do the
170 // intermediate transformation into strings. Which invalidates non-utf8 paths that are actually
174 .map(|s| s.encode_utf16().collect())
175 .ok_or_else(|| err_unsup_format!("{:?} is not a valid utf-8 string", os_str).into())
178 let u16_vec = os_str_to_u16vec(os_str)?;
179 // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
180 // 0x0000 terminator to memory would cause an out-of-bounds access.
181 let string_length = u64::try_from(u16_vec.len()).unwrap();
182 if size <= string_length {
183 return Ok((false, string_length));
186 // Store the UTF-16 string.
187 self.eval_context_mut()
189 .write_u16s(scalar, u16_vec.into_iter().chain(iter::once(0x0000)))?;
190 Ok((true, string_length))
193 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of bytes.
194 fn alloc_os_str_as_c_str(
197 memkind: MemoryKind<MiriMemoryKind>,
199 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
200 let this = self.eval_context_mut();
202 let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
203 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
204 assert!(self.write_os_str_to_c_str(os_str, arg_place.ptr, size).unwrap().0);
205 arg_place.ptr.assert_ptr()
208 /// Allocate enough memory to store the given `OsStr` as a null-terminated sequence of `u16`.
209 fn alloc_os_str_as_wide_str(
212 memkind: MemoryKind<MiriMemoryKind>,
214 let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0x0000` terminator.
215 let this = self.eval_context_mut();
217 let arg_type = this.tcx.mk_array(this.tcx.types.u16, size);
218 let arg_place = this.allocate(this.layout_of(arg_type).unwrap(), memkind);
219 assert!(self.write_os_str_to_wide_str(os_str, arg_place.ptr, size).unwrap().0);
220 arg_place.ptr.assert_ptr()
223 /// Read a null-terminated sequence of bytes, and perform path separator conversion if needed.
224 fn read_path_from_c_str<'a>(&'a self, scalar: Scalar<Tag>) -> InterpResult<'tcx, Cow<'a, Path>>
229 let this = self.eval_context_ref();
230 let os_str = this.read_os_str_from_c_str(scalar)?;
232 Ok(match convert_path_separator(Cow::Borrowed(os_str), &this.tcx.sess.target.target.target_os, Pathconversion::TargetToHost) {
233 Cow::Borrowed(x) => Cow::Borrowed(Path::new(x)),
234 Cow::Owned(y) => Cow::Owned(PathBuf::from(y)),
238 /// Read a null-terminated sequence of `u16`s, and perform path separator conversion if needed.
239 fn read_path_from_wide_str(&self, scalar: Scalar<Tag>) -> InterpResult<'tcx, PathBuf> {
240 let this = self.eval_context_ref();
241 let os_str = this.read_os_str_from_wide_str(scalar)?;
243 Ok(convert_path_separator(Cow::Owned(os_str), &this.tcx.sess.target.target.target_os, Pathconversion::TargetToHost).into_owned().into())
246 /// Write a Path to the machine memory (as a null-terminated sequence of bytes),
247 /// adjusting path separators if needed.
248 fn write_path_to_c_str(
253 ) -> InterpResult<'tcx, (bool, u64)> {
254 let this = self.eval_context_mut();
255 let os_str = convert_path_separator(Cow::Borrowed(path.as_os_str()), &this.tcx.sess.target.target.target_os, Pathconversion::HostToTarget);
256 this.write_os_str_to_c_str(&os_str, scalar, size)
259 /// Write a Path to the machine memory (as a null-terminated sequence of `u16`s),
260 /// adjusting path separators if needed.
261 fn write_path_to_wide_str(
266 ) -> InterpResult<'tcx, (bool, u64)> {
267 let this = self.eval_context_mut();
268 let os_str = convert_path_separator(Cow::Borrowed(path.as_os_str()), &this.tcx.sess.target.target.target_os, Pathconversion::HostToTarget);
269 this.write_os_str_to_wide_str(&os_str, scalar, size)