Skip to main content

rustc_fs_util/
lib.rs

1use std::ffi::{CString, OsStr};
2use std::path::{Path, PathBuf, absolute};
3use std::{fs, io};
4
5use tempfile::TempDir;
6
7// Unfortunately, on windows, it looks like msvcrt.dll is silently translating
8// verbatim paths under the hood to non-verbatim paths! This manifests itself as
9// gcc looking like it cannot accept paths of the form `\\?\C:\...`, but the
10// real bug seems to lie in msvcrt.dll.
11//
12// Verbatim paths are generally pretty rare, but the implementation of
13// `fs::canonicalize` currently generates paths of this form, meaning that we're
14// going to be passing quite a few of these down to gcc, so we need to deal with
15// this case.
16//
17// For now we just strip the "verbatim prefix" of `\\?\` from the path. This
18// will probably lose information in some cases, but there's not a whole lot
19// more we can do with a buggy msvcrt...
20//
21// For some more information, see this comment:
22//   https://github.com/rust-lang/rust/issues/25505#issuecomment-102876737
23#[cfg(windows)]
24pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
25    use std::ffi::OsString;
26    use std::path;
27    let mut components = p.components();
28    let prefix = match components.next() {
29        Some(path::Component::Prefix(p)) => p,
30        _ => return p.to_path_buf(),
31    };
32    match prefix.kind() {
33        path::Prefix::VerbatimDisk(disk) => {
34            let mut base = OsString::from(format!("{}:", disk as char));
35            base.push(components.as_path());
36            PathBuf::from(base)
37        }
38        path::Prefix::VerbatimUNC(server, share) => {
39            let mut base = OsString::from(r"\\");
40            base.push(server);
41            base.push(r"\");
42            base.push(share);
43            base.push(components.as_path());
44            PathBuf::from(base)
45        }
46        _ => p.to_path_buf(),
47    }
48}
49
50#[cfg(not(windows))]
51pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
52    p.to_path_buf()
53}
54
55pub enum LinkOrCopy {
56    Link,
57    Copy,
58}
59
60/// Copies `p` into `q`, preferring to use hard-linking if possible.
61/// The result indicates which of the two operations has been performed.
62pub fn link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(
63    p: P,
64    q: Q,
65    allow_overwrite: bool,
66) -> io::Result<LinkOrCopy> {
67    // Creating a hard-link will fail if the destination path already exists. We could defensively
68    // call remove_file in this function, but that pessimizes callers who can avoid such calls.
69    // Incremental compilation calls this function a lot, and is able to avoid calls that
70    // would fail the first hard_link attempt.
71
72    let p = p.as_ref();
73    let q = q.as_ref();
74
75    let err = match fs::hard_link(p, q) {
76        Ok(()) => return Ok(LinkOrCopy::Link),
77        Err(err) => err,
78    };
79
80    if err.kind() == io::ErrorKind::AlreadyExists {
81        if !allow_overwrite {
82            {
    ::core::panicking::panic_fmt(format_args!("link/copy target {0} already exists: {1}",
            q.display(), err));
};panic!("link/copy target {} already exists: {err}", q.display());
83        }
84        fs::remove_file(q)?;
85        if fs::hard_link(p, q).is_ok() {
86            return Ok(LinkOrCopy::Link);
87        }
88    }
89
90    // Hard linking failed, fall back to copying.
91    fs::copy(p, q).map(|_| LinkOrCopy::Copy)
92}
93
94#[cfg(any(unix, all(target_os = "wasi", target_env = "p1")))]
95pub fn path_to_c_string(p: &Path) -> CString {
96    use std::ffi::OsStr;
97    #[cfg(unix)]
98    use std::os::unix::ffi::OsStrExt;
99    #[cfg(all(target_os = "wasi", target_env = "p1"))]
100    use std::os::wasi::ffi::OsStrExt;
101
102    let p: &OsStr = p.as_ref();
103    CString::new(p.as_bytes()).unwrap()
104}
105#[cfg(windows)]
106pub fn path_to_c_string(p: &Path) -> CString {
107    CString::new(p.to_str().unwrap()).unwrap()
108}
109
110#[inline]
111pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
112    fs::canonicalize(&path).or_else(|_| absolute(&path))
113}
114
115pub struct TempDirBuilder<'a, 'b> {
116    builder: tempfile::Builder<'a, 'b>,
117}
118
119impl<'a, 'b> TempDirBuilder<'a, 'b> {
120    pub fn new() -> Self {
121        Self { builder: tempfile::Builder::new() }
122    }
123
124    pub fn prefix<S: AsRef<OsStr> + ?Sized>(&mut self, prefix: &'a S) -> &mut Self {
125        self.builder.prefix(prefix);
126        self
127    }
128
129    pub fn suffix<S: AsRef<OsStr> + ?Sized>(&mut self, suffix: &'b S) -> &mut Self {
130        self.builder.suffix(suffix);
131        self
132    }
133
134    pub fn tempdir_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<TempDir> {
135        let dir = dir.as_ref();
136        // On Windows in CI, we had been getting fairly frequent "Access is denied"
137        // errors when creating temporary directories.
138        // So this implements a simple retry with backoff loop.
139        #[cfg(windows)]
140        for wait in 1..11 {
141            match self.builder.tempdir_in(dir) {
142                Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {}
143                t => return t,
144            }
145            std::thread::sleep(std::time::Duration::from_millis(1 << wait));
146        }
147        self.builder.tempdir_in(dir)
148    }
149}