Skip to content

Commit e870822

Browse files
committed
Improve Windows path prefix parsing
1 parent 2c28b0e commit e870822

File tree

6 files changed

+124
-37
lines changed

6 files changed

+124
-37
lines changed

library/std/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@
240240
#![feature(exhaustive_patterns)]
241241
#![feature(intra_doc_pointers)]
242242
#![feature(lang_items)]
243+
#![feature(let_chains)]
243244
#![feature(linkage)]
244245
#![feature(min_specialization)]
245246
#![feature(must_not_suspend)]

library/std/src/path.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,8 +168,8 @@ pub enum Prefix<'a> {
168168

169169
/// Device namespace prefix, e.g., `\\.\COM42`.
170170
///
171-
/// Device namespace prefixes consist of `\\.\` immediately followed by the
172-
/// device name.
171+
/// Device namespace prefixes consist of `\\.\` (possibly using `/`
172+
/// instead of `\`), immediately followed by the device name.
173173
#[stable(feature = "rust1", since = "1.0.0")]
174174
DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
175175

library/std/src/path/tests.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -971,15 +971,15 @@ pub fn test_decompositions_windows() {
971971
file_prefix: None
972972
);
973973

974-
t!("\\\\?\\C:/foo",
975-
iter: ["\\\\?\\C:/foo"],
974+
t!("\\\\?\\C:/foo/bar",
975+
iter: ["\\\\?\\C:", "\\", "foo/bar"],
976976
has_root: true,
977977
is_absolute: true,
978-
parent: None,
979-
file_name: None,
980-
file_stem: None,
978+
parent: Some("\\\\?\\C:/"),
979+
file_name: Some("foo/bar"),
980+
file_stem: Some("foo/bar"),
981981
extension: None,
982-
file_prefix: None
982+
file_prefix: Some("foo/bar")
983983
);
984984

985985
t!("\\\\.\\foo\\bar",

library/std/src/sys/windows/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,10 @@ where
190190
{
191191
// Start off with a stack buf but then spill over to the heap if we end up
192192
// needing more space.
193+
//
194+
// This initial size also works around `GetFullPathNameW` returning
195+
// incorrect size hints for some short paths:
196+
// https://github.com/dylni/normpath/issues/5
193197
let mut stack_buf = [0u16; 512];
194198
let mut heap_buf = Vec::new();
195199
unsafe {

library/std/src/sys/windows/path.rs

Lines changed: 91 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -50,37 +50,101 @@ pub(crate) fn append_suffix(path: PathBuf, suffix: &OsStr) -> PathBuf {
5050
path.into()
5151
}
5252

53+
struct PrefixParser<'a, const LEN: usize> {
54+
path: &'a OsStr,
55+
prefix: [u8; LEN],
56+
}
57+
58+
impl<'a, const LEN: usize> PrefixParser<'a, LEN> {
59+
#[inline]
60+
fn get_prefix(path: &OsStr) -> [u8; LEN] {
61+
let mut prefix = [0; LEN];
62+
// SAFETY: Only ASCII characters are modified.
63+
for (i, &ch) in path.bytes().iter().take(LEN).enumerate() {
64+
prefix[i] = if ch == b'/' { b'\\' } else { ch };
65+
}
66+
prefix
67+
}
68+
69+
fn new(path: &'a OsStr) -> Self {
70+
Self { path, prefix: Self::get_prefix(path) }
71+
}
72+
73+
fn as_slice(&self) -> PrefixParserSlice<'a, '_> {
74+
PrefixParserSlice {
75+
path: self.path,
76+
prefix: &self.prefix[..LEN.min(self.path.len())],
77+
index: 0,
78+
}
79+
}
80+
}
81+
82+
struct PrefixParserSlice<'a, 'b> {
83+
path: &'a OsStr,
84+
prefix: &'b [u8],
85+
index: usize,
86+
}
87+
88+
impl<'a> PrefixParserSlice<'a, '_> {
89+
fn strip_prefix(&self, prefix: &str) -> Option<Self> {
90+
self.prefix[self.index..]
91+
.starts_with(prefix.as_bytes())
92+
.then(|| Self { index: self.index + prefix.len(), ..*self })
93+
}
94+
95+
fn prefix_bytes(&self) -> &'a [u8] {
96+
&self.path.bytes()[..self.index]
97+
}
98+
99+
fn finish(self) -> &'a OsStr {
100+
// SAFETY: The unsafety here stems from converting between &OsStr and
101+
// &[u8] and back. This is safe to do because (1) we only look at ASCII
102+
// contents of the encoding and (2) new &OsStr values are produced only
103+
// from ASCII-bounded slices of existing &OsStr values.
104+
unsafe { bytes_as_os_str(&self.path.bytes()[self.index..]) }
105+
}
106+
}
107+
53108
pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
54109
use Prefix::{DeviceNS, Disk, Verbatim, VerbatimDisk, VerbatimUNC, UNC};
55110

56-
if let Some(path) = strip_prefix(path, r"\\") {
111+
let parser = PrefixParser::<8>::new(path);
112+
let parser = parser.as_slice();
113+
if let Some(parser) = parser.strip_prefix(r"\\") {
57114
// \\
58-
if let Some(path) = strip_prefix(path, r"?\") {
115+
116+
// The meaning of verbatim paths can change when they use a different
117+
// separator.
118+
if let Some(parser) = parser.strip_prefix(r"?\") && !parser.prefix_bytes().iter().any(|&x| x == b'/') {
59119
// \\?\
60-
if let Some(path) = strip_prefix(path, r"UNC\") {
120+
if let Some(parser) = parser.strip_prefix(r"UNC\") {
61121
// \\?\UNC\server\share
62122

123+
let path = parser.finish();
63124
let (server, path) = parse_next_component(path, true);
64125
let (share, _) = parse_next_component(path, true);
65126

66127
Some(VerbatimUNC(server, share))
67128
} else {
68-
let (prefix, _) = parse_next_component(path, true);
129+
let path = parser.finish();
69130

70131
// in verbatim paths only recognize an exact drive prefix
71-
if let Some(drive) = parse_drive_exact(prefix) {
132+
if let Some(drive) = parse_drive_exact(path) {
72133
// \\?\C:
73134
Some(VerbatimDisk(drive))
74135
} else {
75136
// \\?\prefix
137+
let (prefix, _) = parse_next_component(path, true);
76138
Some(Verbatim(prefix))
77139
}
78140
}
79-
} else if let Some(path) = strip_prefix(path, r".\") {
141+
} else if let Some(parser) = parser.strip_prefix(r".\") {
80142
// \\.\COM42
143+
let path = parser.finish();
81144
let (prefix, _) = parse_next_component(path, false);
82145
Some(DeviceNS(prefix))
83146
} else {
147+
let path = parser.finish();
84148
let (server, path) = parse_next_component(path, false);
85149
let (share, _) = parse_next_component(path, false);
86150

@@ -102,31 +166,26 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
102166
}
103167

104168
// Parses a drive prefix, e.g. "C:" and "C:\whatever"
105-
fn parse_drive(prefix: &OsStr) -> Option<u8> {
169+
fn parse_drive(path: &OsStr) -> Option<u8> {
106170
// In most DOS systems, it is not possible to have more than 26 drive letters.
107171
// See <https://en.wikipedia.org/wiki/Drive_letter_assignment#Common_assignments>.
108172
fn is_valid_drive_letter(drive: &u8) -> bool {
109173
drive.is_ascii_alphabetic()
110174
}
111175

112-
match prefix.bytes() {
176+
match path.bytes() {
113177
[drive, b':', ..] if is_valid_drive_letter(drive) => Some(drive.to_ascii_uppercase()),
114178
_ => None,
115179
}
116180
}
117181

118182
// Parses a drive prefix exactly, e.g. "C:"
119-
fn parse_drive_exact(prefix: &OsStr) -> Option<u8> {
183+
fn parse_drive_exact(path: &OsStr) -> Option<u8> {
120184
// only parse two bytes: the drive letter and the drive separator
121-
if prefix.len() == 2 { parse_drive(prefix) } else { None }
122-
}
123-
124-
fn strip_prefix<'a>(path: &'a OsStr, prefix: &str) -> Option<&'a OsStr> {
125-
// `path` and `prefix` are valid wtf8 and utf8 encoded slices respectively, `path[prefix.len()]`
126-
// is thus a code point boundary and `path[prefix.len()..]` is a valid wtf8 encoded slice.
127-
match path.bytes().strip_prefix(prefix.as_bytes()) {
128-
Some(path) => unsafe { Some(bytes_as_os_str(path)) },
129-
None => None,
185+
if path.bytes().get(2).map(|&x| is_sep_byte(x)).unwrap_or(true) {
186+
parse_drive(path)
187+
} else {
188+
None
130189
}
131190
}
132191

@@ -219,15 +278,7 @@ pub(crate) fn maybe_verbatim(path: &Path) -> io::Result<Vec<u16>> {
219278
// SAFETY: `fill_utf16_buf` ensures the `buffer` and `size` are valid.
220279
// `lpfilename` is a pointer to a null terminated string that is not
221280
// invalidated until after `GetFullPathNameW` returns successfully.
222-
|buffer, size| unsafe {
223-
// While the docs for `GetFullPathNameW` have the standard note
224-
// about needing a `\\?\` path for a long lpfilename, this does not
225-
// appear to be true in practice.
226-
// See:
227-
// https://stackoverflow.com/questions/38036943/getfullpathnamew-and-long-windows-file-paths
228-
// https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html
229-
c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut())
230-
},
281+
|buffer, size| unsafe { c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()) },
231282
|mut absolute| {
232283
path.clear();
233284

@@ -263,9 +314,20 @@ pub(crate) fn maybe_verbatim(path: &Path) -> io::Result<Vec<u16>> {
263314

264315
/// Make a Windows path absolute.
265316
pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> {
266-
if path.as_os_str().bytes().starts_with(br"\\?\") {
267-
return Ok(path.into());
317+
let path = path.as_os_str();
318+
let prefix = parse_prefix(path);
319+
// Verbatim paths should not be modified.
320+
if prefix.map(|x| x.is_verbatim()).unwrap_or(false) {
321+
// NULs in verbatim paths are rejected for consistency.
322+
if path.bytes().contains(&0) {
323+
return Err(io::const_io_error!(
324+
io::ErrorKind::InvalidInput,
325+
"strings passed to WinAPI cannot contain NULs",
326+
));
327+
}
328+
return Ok(path.to_owned().into());
268329
}
330+
269331
let path = to_u16s(path)?;
270332
let lpfilename = path.as_ptr();
271333
fill_utf16_buf(

library/std/src/sys/windows/path/tests.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,23 @@ fn verbatim() {
9494
// A path that contains null is not a valid path.
9595
assert!(maybe_verbatim(Path::new("\0")).is_err());
9696
}
97+
98+
fn parse_prefix(path: &str) -> Option<Prefix<'_>> {
99+
super::parse_prefix(OsStr::new(path))
100+
}
101+
102+
#[test]
103+
fn test_parse_prefix_verbatim() {
104+
let prefix = Some(Prefix::VerbatimDisk(b'C'));
105+
assert_eq!(prefix, parse_prefix(r"\\?\C:/windows/system32/notepad.exe"));
106+
assert_eq!(prefix, parse_prefix(r"\\?\C:\windows\system32\notepad.exe"));
107+
}
108+
109+
#[test]
110+
fn test_parse_prefix_verbatim_device() {
111+
let prefix = Some(Prefix::UNC(OsStr::new("?"), OsStr::new("C:")));
112+
assert_eq!(prefix, parse_prefix(r"//?/C:/windows/system32/notepad.exe"));
113+
assert_eq!(prefix, parse_prefix(r"//?/C:\windows\system32\notepad.exe"));
114+
assert_eq!(prefix, parse_prefix(r"/\?\C:\windows\system32\notepad.exe"));
115+
assert_eq!(prefix, parse_prefix(r"\\?/C:\windows\system32\notepad.exe"));
116+
}

0 commit comments

Comments
 (0)