std\sys\path/windows.rs
1use crate::ffi::{OsStr, OsString};
2use crate::path::{Path, PathBuf};
3use crate::sys::api::utf16;
4use crate::sys::pal::{c, fill_utf16_buf, os2path, to_u16s};
5use crate::{io, ptr};
6
7#[cfg(test)]
8mod tests;
9
10pub use super::windows_prefix::parse_prefix;
11
12pub const HAS_PREFIXES: bool = true;
13pub const MAIN_SEP_STR: &str = "\\";
14pub const MAIN_SEP: char = '\\';
15
16/// A null terminated wide string.
17#[repr(transparent)]
18pub struct WCStr([u16]);
19
20impl WCStr {
21 /// Convert a slice to a WCStr without checks.
22 ///
23 /// Though it is memory safe, the slice should also not contain interior nulls
24 /// as this may lead to unwanted truncation.
25 ///
26 /// # Safety
27 ///
28 /// The slice must end in a null.
29 pub unsafe fn from_wchars_with_null_unchecked(s: &[u16]) -> &Self {
30 unsafe { &*(s as *const [u16] as *const Self) }
31 }
32
33 pub fn as_ptr(&self) -> *const u16 {
34 self.0.as_ptr()
35 }
36
37 pub fn count_bytes(&self) -> usize {
38 self.0.len()
39 }
40}
41
42#[inline]
43pub fn with_native_path<T>(path: &Path, f: &dyn Fn(&WCStr) -> io::Result<T>) -> io::Result<T> {
44 let path = maybe_verbatim(path)?;
45 // SAFETY: maybe_verbatim returns null-terminated strings
46 let path = unsafe { WCStr::from_wchars_with_null_unchecked(&path) };
47 f(path)
48}
49
50#[inline]
51pub fn is_sep_byte(b: u8) -> bool {
52 b == b'/' || b == b'\\'
53}
54
55#[inline]
56pub fn is_verbatim_sep(b: u8) -> bool {
57 b == b'\\'
58}
59
60pub fn is_verbatim(path: &[u16]) -> bool {
61 path.starts_with(utf16!(r"\\?\")) || path.starts_with(utf16!(r"\??\"))
62}
63
64/// Returns true if `path` looks like a lone filename.
65pub(crate) fn is_file_name(path: &OsStr) -> bool {
66 !path.as_encoded_bytes().iter().copied().any(is_sep_byte)
67}
68pub(crate) fn has_trailing_slash(path: &OsStr) -> bool {
69 let is_verbatim = path.as_encoded_bytes().starts_with(br"\\?\");
70 let is_separator = if is_verbatim { is_verbatim_sep } else { is_sep_byte };
71 if let Some(&c) = path.as_encoded_bytes().last() { is_separator(c) } else { false }
72}
73
74/// Appends a suffix to a path.
75///
76/// Can be used to append an extension without removing an existing extension.
77pub(crate) fn append_suffix(path: PathBuf, suffix: &OsStr) -> PathBuf {
78 let mut path = OsString::from(path);
79 path.push(suffix);
80 path.into()
81}
82
83/// Returns a UTF-16 encoded path capable of bypassing the legacy `MAX_PATH` limits.
84///
85/// This path may or may not have a verbatim prefix.
86pub(crate) fn maybe_verbatim(path: &Path) -> io::Result<Vec<u16>> {
87 let path = to_u16s(path)?;
88 get_long_path(path, true)
89}
90
91/// Gets a normalized absolute path that can bypass path length limits.
92///
93/// Setting prefer_verbatim to true suggests a stronger preference for verbatim
94/// paths even when not strictly necessary. This allows the Windows API to avoid
95/// repeating our work. However, if the path may be given back to users or
96/// passed to other application then it's preferable to use non-verbatim paths
97/// when possible. Non-verbatim paths are better understood by users and handled
98/// by more software.
99pub(crate) fn get_long_path(mut path: Vec<u16>, prefer_verbatim: bool) -> io::Result<Vec<u16>> {
100 // Normally the MAX_PATH is 260 UTF-16 code units (including the NULL).
101 // However, for APIs such as CreateDirectory[1], the limit is 248.
102 //
103 // [1]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectorya#parameters
104 const LEGACY_MAX_PATH: usize = 248;
105 // UTF-16 encoded code points, used in parsing and building UTF-16 paths.
106 // All of these are in the ASCII range so they can be cast directly to `u16`.
107 const SEP: u16 = b'\\' as _;
108 const ALT_SEP: u16 = b'/' as _;
109 const QUERY: u16 = b'?' as _;
110 const COLON: u16 = b':' as _;
111 const DOT: u16 = b'.' as _;
112 const U: u16 = b'U' as _;
113 const N: u16 = b'N' as _;
114 const C: u16 = b'C' as _;
115
116 // \\?\
117 const VERBATIM_PREFIX: &[u16] = &[SEP, SEP, QUERY, SEP];
118 // \??\
119 const NT_PREFIX: &[u16] = &[SEP, QUERY, QUERY, SEP];
120 // \\?\UNC\
121 const UNC_PREFIX: &[u16] = &[SEP, SEP, QUERY, SEP, U, N, C, SEP];
122
123 if path.starts_with(VERBATIM_PREFIX) || path.starts_with(NT_PREFIX) || path == [0] {
124 // Early return for paths that are already verbatim or empty.
125 return Ok(path);
126 } else if path.len() < LEGACY_MAX_PATH {
127 // Early return if an absolute path is less < 260 UTF-16 code units.
128 // This is an optimization to avoid calling `GetFullPathNameW` unnecessarily.
129 match path.as_slice() {
130 // Starts with `D:`, `D:\`, `D:/`, etc.
131 // Does not match if the path starts with a `\` or `/`.
132 [drive, COLON, 0] | [drive, COLON, SEP | ALT_SEP, ..]
133 if *drive != SEP && *drive != ALT_SEP =>
134 {
135 return Ok(path);
136 }
137 // Starts with `\\`, `//`, etc
138 [SEP | ALT_SEP, SEP | ALT_SEP, ..] => return Ok(path),
139 _ => {}
140 }
141 }
142
143 // Firstly, get the absolute path using `GetFullPathNameW`.
144 // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
145 let lpfilename = path.as_ptr();
146 fill_utf16_buf(
147 // SAFETY: `fill_utf16_buf` ensures the `buffer` and `size` are valid.
148 // `lpfilename` is a pointer to a null terminated string that is not
149 // invalidated until after `GetFullPathNameW` returns successfully.
150 |buffer, size| unsafe { c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()) },
151 |mut absolute| {
152 path.clear();
153
154 // Only prepend the prefix if needed.
155 if prefer_verbatim || absolute.len() + 1 >= LEGACY_MAX_PATH {
156 // Secondly, add the verbatim prefix. This is easier here because we know the
157 // path is now absolute and fully normalized (e.g. `/` has been changed to `\`).
158 let prefix = match absolute {
159 // C:\ => \\?\C:\
160 [_, COLON, SEP, ..] => VERBATIM_PREFIX,
161 // \\.\ => \\?\
162 [SEP, SEP, DOT, SEP, ..] => {
163 absolute = &absolute[4..];
164 VERBATIM_PREFIX
165 }
166 // Leave \\?\ and \??\ as-is.
167 [SEP, SEP, QUERY, SEP, ..] | [SEP, QUERY, QUERY, SEP, ..] => &[],
168 // \\ => \\?\UNC\
169 [SEP, SEP, ..] => {
170 absolute = &absolute[2..];
171 UNC_PREFIX
172 }
173 // Anything else we leave alone.
174 _ => &[],
175 };
176
177 path.reserve_exact(prefix.len() + absolute.len() + 1);
178 path.extend_from_slice(prefix);
179 } else {
180 path.reserve_exact(absolute.len() + 1);
181 }
182 path.extend_from_slice(absolute);
183 path.push(0);
184 },
185 )?;
186 Ok(path)
187}
188
189/// Make a Windows path absolute.
190pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> {
191 let path = path.as_os_str();
192 let prefix = parse_prefix(path);
193 // Verbatim paths should not be modified.
194 if prefix.map(|x| x.is_verbatim()).unwrap_or(false) {
195 // NULs in verbatim paths are rejected for consistency.
196 if path.as_encoded_bytes().contains(&0) {
197 return Err(io::const_error!(
198 io::ErrorKind::InvalidInput,
199 "strings passed to WinAPI cannot contain NULs",
200 ));
201 }
202 return Ok(path.to_owned().into());
203 }
204
205 let path = to_u16s(path)?;
206 let lpfilename = path.as_ptr();
207 fill_utf16_buf(
208 // SAFETY: `fill_utf16_buf` ensures the `buffer` and `size` are valid.
209 // `lpfilename` is a pointer to a null terminated string that is not
210 // invalidated until after `GetFullPathNameW` returns successfully.
211 |buffer, size| unsafe { c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()) },
212 os2path,
213 )
214}
215
216pub(crate) fn is_absolute(path: &Path) -> bool {
217 path.has_root() && path.prefix().is_some()
218}
219
220/// Test that the path is absolute, fully qualified and unchanged when processed by the Windows API.
221///
222/// For example:
223///
224/// - `C:\path\to\file` will return true.
225/// - `C:\path\to\nul` returns false because the Windows API will convert it to \\.\NUL
226/// - `C:\path\to\..\file` returns false because it will be resolved to `C:\path\file`.
227///
228/// This is a useful property because it means the path can be converted from and to and verbatim
229/// path just by changing the prefix.
230pub(crate) fn is_absolute_exact(path: &[u16]) -> bool {
231 // This is implemented by checking that passing the path through
232 // GetFullPathNameW does not change the path in any way.
233
234 // Windows paths are limited to i16::MAX length
235 // though the API here accepts a u32 for the length.
236 if path.is_empty() || path.len() > u32::MAX as usize || path.last() != Some(&0) {
237 return false;
238 }
239 // The path returned by `GetFullPathNameW` must be the same length as the
240 // given path, otherwise they're not equal.
241 let buffer_len = path.len();
242 let mut new_path = Vec::with_capacity(buffer_len);
243 let result = unsafe {
244 c::GetFullPathNameW(
245 path.as_ptr(),
246 new_path.capacity() as u32,
247 new_path.as_mut_ptr(),
248 crate::ptr::null_mut(),
249 )
250 };
251 // Note: if non-zero, the returned result is the length of the buffer without the null termination
252 if result == 0 || result as usize != buffer_len - 1 {
253 false
254 } else {
255 // SAFETY: `GetFullPathNameW` initialized `result` bytes and does not exceed `nBufferLength - 1` (capacity).
256 unsafe {
257 new_path.set_len((result as usize) + 1);
258 }
259 path == &new_path
260 }
261}