Skip to content

Commit d4da2cc

Browse files
committed
Auto merge of #3466 - RalfJung:GetFullPathNameW, r=RalfJung
add some basic support for GetFullPathNameW This is the last missing piece to make std `path::` tests work on Windows.
2 parents f250781 + f592764 commit d4da2cc

File tree

6 files changed

+174
-22
lines changed

6 files changed

+174
-22
lines changed

src/helpers.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,3 +1285,18 @@ pub(crate) fn simd_element_to_bool(elem: ImmTy<'_, Provenance>) -> InterpResult<
12851285
_ => throw_ub_format!("each element of a SIMD mask must be all-0-bits or all-1-bits"),
12861286
})
12871287
}
1288+
1289+
/// Check whether an operation that writes to a target buffer was successful.
1290+
/// Accordingly select return value.
1291+
/// Local helper function to be used in Windows shims.
1292+
pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1293+
if success {
1294+
// If the function succeeds, the return value is the number of characters stored in the target buffer,
1295+
// not including the terminating null character.
1296+
u32::try_from(len.checked_sub(1).unwrap()).unwrap()
1297+
} else {
1298+
// If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
1299+
// required to hold the string and its terminating null character.
1300+
u32::try_from(len).unwrap()
1301+
}
1302+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#![feature(let_chains)]
1414
#![feature(lint_reasons)]
1515
#![feature(trait_upcasting)]
16+
#![feature(absolute_path)]
1617
// Configure clippy and other lints
1718
#![allow(
1819
clippy::collapsible_else_if,

src/shims/env.rs

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,7 @@ use rustc_middle::ty::Ty;
99
use rustc_target::abi::Size;
1010

1111
use crate::*;
12-
13-
/// Check whether an operation that writes to a target buffer was successful.
14-
/// Accordingly select return value.
15-
/// Local helper function to be used in Windows shims.
16-
fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
17-
if success {
18-
// If the function succeeds, the return value is the number of characters stored in the target buffer,
19-
// not including the terminating null character.
20-
u32::try_from(len.checked_sub(1).unwrap()).unwrap()
21-
} else {
22-
// If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
23-
// required to hold the string and its terminating null character.
24-
u32::try_from(len).unwrap()
25-
}
26-
}
12+
use helpers::windows_check_buffer_size;
2713

2814
#[derive(Default)]
2915
pub struct EnvVars<'tcx> {
@@ -164,7 +150,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
164150
let name_ptr = this.read_pointer(name_op)?;
165151
let name = this.read_os_str_from_wide_str(name_ptr)?;
166152
Ok(match this.machine.env_vars.map.get(&name) {
167-
Some(var_ptr) => {
153+
Some(&var_ptr) => {
154+
this.set_last_error(Scalar::from_u32(0))?; // make sure this is unambiguously not an error
168155
// The offset is used to strip the "{name}=" part of the string.
169156
#[rustfmt::skip]
170157
let name_offset_bytes = u64::try_from(name.len()).unwrap()
@@ -375,10 +362,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
375362

376363
// If we cannot get the current directory, we return 0
377364
match env::current_dir() {
378-
Ok(cwd) =>
365+
Ok(cwd) => {
366+
this.set_last_error(Scalar::from_u32(0))?; // make sure this is unambiguously not an error
379367
return Ok(Scalar::from_u32(windows_check_buffer_size(
380368
this.write_path_to_wide_str(&cwd, buf, size, /*truncate*/ false)?,
381-
))),
369+
)));
370+
}
382371
Err(e) => this.set_last_error_from_io_error(e.kind())?,
383372
}
384373
Ok(Scalar::from_u32(0))

src/shims/os_str.rs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -316,9 +316,21 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
316316
// We also have to ensure that absolute paths remain absolute.
317317
match direction {
318318
PathConversion::HostToTarget => {
319-
// If this start withs a `\`, we add `\\?` so it starts with `\\?\` which is
320-
// some magic path on Windows that *is* considered absolute.
321-
if converted.get(0).copied() == Some(b'\\') {
319+
// If the path is `/C:/`, the leading backslash was probably added by the below
320+
// driver letter handling and we should get rid of it again.
321+
if converted.get(0).copied() == Some(b'\\')
322+
&& converted.get(2).copied() == Some(b':')
323+
&& converted.get(3).copied() == Some(b'\\')
324+
{
325+
converted.remove(0);
326+
}
327+
// If this start withs a `\` but not a `\\`, then for Windows this is a relative
328+
// path. But the host path is absolute as it started with `/`. We add `\\?` so
329+
// it starts with `\\?\` which is some magic path on Windows that *is*
330+
// considered absolute.
331+
else if converted.get(0).copied() == Some(b'\\')
332+
&& converted.get(1).copied() != Some(b'\\')
333+
{
322334
converted.splice(0..0, b"\\\\?".iter().copied());
323335
}
324336
}
@@ -333,6 +345,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
333345
// Remove first 3 characters
334346
converted.splice(0..3, std::iter::empty());
335347
}
348+
// If it starts with a drive letter, convert it to an absolute Unix path.
349+
else if converted.get(1).copied() == Some(b':')
350+
&& converted.get(2).copied() == Some(b'/')
351+
{
352+
converted.insert(0, b'/');
353+
}
336354
}
337355
}
338356
Cow::Owned(OsString::from_vec(converted))

src/shims/windows/foreign_items.rs

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use std::ffi::OsStr;
2+
use std::io;
23
use std::iter;
4+
use std::path::{self, Path, PathBuf};
35
use std::str;
46

57
use rustc_span::Symbol;
@@ -21,6 +23,61 @@ fn is_dyn_sym(name: &str) -> bool {
2123
)
2224
}
2325

26+
#[cfg(windows)]
27+
fn win_absolute<'tcx>(path: &Path) -> InterpResult<'tcx, io::Result<PathBuf>> {
28+
// We are on Windows so we can simply lte the host do this.
29+
return Ok(path::absolute(path));
30+
}
31+
32+
#[cfg(unix)]
33+
#[allow(clippy::get_first, clippy::arithmetic_side_effects)]
34+
fn win_absolute<'tcx>(path: &Path) -> InterpResult<'tcx, io::Result<PathBuf>> {
35+
// We are on Unix, so we need to implement parts of the logic ourselves.
36+
let bytes = path.as_os_str().as_encoded_bytes();
37+
// If it starts with `//` (these were backslashes but are already converted)
38+
// then this is a magic special path, we just leave it unchanged.
39+
if bytes.get(0).copied() == Some(b'/') && bytes.get(1).copied() == Some(b'/') {
40+
return Ok(Ok(path.into()));
41+
};
42+
// Special treatment for Windows' magic filenames: they are treated as being relative to `\\.\`.
43+
let magic_filenames = &[
44+
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
45+
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
46+
];
47+
if magic_filenames.iter().any(|m| m.as_bytes() == bytes) {
48+
let mut result: Vec<u8> = br"//./".into();
49+
result.extend(bytes);
50+
return Ok(Ok(bytes_to_os_str(&result)?.into()));
51+
}
52+
// Otherwise we try to do something kind of close to what Windows does, but this is probably not
53+
// right in all cases. We iterate over the components between `/`, and remove trailing `.`,
54+
// except that trailing `..` remain unchanged.
55+
let mut result = vec![];
56+
let mut bytes = bytes; // the remaining bytes to process
57+
loop {
58+
let len = bytes.iter().position(|&b| b == b'/').unwrap_or(bytes.len());
59+
let mut component = &bytes[..len];
60+
if len >= 2 && component[len - 1] == b'.' && component[len - 2] != b'.' {
61+
// Strip trailing `.`
62+
component = &component[..len - 1];
63+
}
64+
// Add this component to output.
65+
result.extend(component);
66+
// Prepare next iteration.
67+
if len < bytes.len() {
68+
// There's a component after this; add `/` and process remaining bytes.
69+
result.push(b'/');
70+
bytes = &bytes[len + 1..];
71+
continue;
72+
} else {
73+
// This was the last component and it did not have a trailing `/`.
74+
break;
75+
}
76+
}
77+
// Let the host `absolute` function do working-dir handling
78+
Ok(path::absolute(bytes_to_os_str(&result)?))
79+
}
80+
2481
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
2582
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
2683
fn emulate_foreign_item_inner(
@@ -112,7 +169,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
112169

113170
let written = if handle == -11 || handle == -12 {
114171
// stdout/stderr
115-
use std::io::{self, Write};
172+
use io::Write;
116173

117174
let buf_cont =
118175
this.read_bytes_ptr_strip_provenance(buf, Size::from_bytes(u64::from(n)))?;
@@ -146,6 +203,40 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
146203
dest,
147204
)?;
148205
}
206+
"GetFullPathNameW" => {
207+
let [filename, size, buffer, filepart] =
208+
this.check_shim(abi, Abi::System { unwind: false }, link_name, args)?;
209+
this.check_no_isolation("`GetFullPathNameW`")?;
210+
211+
let filename = this.read_pointer(filename)?;
212+
let size = this.read_scalar(size)?.to_u32()?;
213+
let buffer = this.read_pointer(buffer)?;
214+
let filepart = this.read_pointer(filepart)?;
215+
216+
if !this.ptr_is_null(filepart)? {
217+
throw_unsup_format!("GetFullPathNameW: non-null `lpFilePart` is not supported");
218+
}
219+
220+
let filename = this.read_path_from_wide_str(filename)?;
221+
let result = match win_absolute(&filename)? {
222+
Err(err) => {
223+
this.set_last_error_from_io_error(err.kind())?;
224+
Scalar::from_u32(0) // return zero upon failure
225+
}
226+
Ok(abs_filename) => {
227+
this.set_last_error(Scalar::from_u32(0))?; // make sure this is unambiguously not an error
228+
Scalar::from_u32(helpers::windows_check_buffer_size(
229+
this.write_path_to_wide_str(
230+
&abs_filename,
231+
buffer,
232+
size.into(),
233+
/*truncate*/ false,
234+
)?,
235+
))
236+
}
237+
};
238+
this.write_scalar(result, dest)?;
239+
}
149240

150241
// Allocation
151242
"HeapAlloc" => {

tests/pass/shims/path.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//@compile-flags: -Zmiri-disable-isolation
2+
#![feature(absolute_path)]
3+
use std::path::{absolute, Path};
4+
5+
#[track_caller]
6+
fn test_absolute(in_: &str, out: &str) {
7+
assert_eq!(absolute(in_).unwrap().as_os_str(), Path::new(out).as_os_str());
8+
}
9+
10+
fn main() {
11+
if cfg!(unix) {
12+
test_absolute("/a/b/c", "/a/b/c");
13+
test_absolute("/a/b/c", "/a/b/c");
14+
test_absolute("/a//b/c", "/a/b/c");
15+
test_absolute("//a/b/c", "//a/b/c");
16+
test_absolute("///a/b/c", "/a/b/c");
17+
test_absolute("/a/b/c/", "/a/b/c/");
18+
test_absolute("/a/./b/../c/.././..", "/a/b/../c/../..");
19+
} else if cfg!(windows) {
20+
// Test that all these are unchanged
21+
test_absolute(r"C:\path\to\file", r"C:\path\to\file");
22+
test_absolute(r"C:\path\to\file\", r"C:\path\to\file\");
23+
test_absolute(r"\\server\share\to\file", r"\\server\share\to\file");
24+
test_absolute(r"\\server.\share.\to\file", r"\\server.\share.\to\file");
25+
test_absolute(r"\\.\PIPE\name", r"\\.\PIPE\name");
26+
test_absolute(r"\\.\C:\path\to\COM1", r"\\.\C:\path\to\COM1");
27+
test_absolute(r"\\?\C:\path\to\file", r"\\?\C:\path\to\file");
28+
test_absolute(r"\\?\UNC\server\share\to\file", r"\\?\UNC\server\share\to\file");
29+
test_absolute(r"\\?\PIPE\name", r"\\?\PIPE\name");
30+
// Verbatim paths are always unchanged, no matter what.
31+
test_absolute(r"\\?\path.\to/file..", r"\\?\path.\to/file..");
32+
33+
test_absolute(r"C:\path..\to.\file.", r"C:\path..\to\file");
34+
test_absolute(r"COM1", r"\\.\COM1");
35+
} else {
36+
panic!("unsupported OS");
37+
}
38+
}

0 commit comments

Comments
 (0)