1use std::ffi::{CString, OsStr};
2use std::path::{Path, PathBuf, absolute};
3use std::{fs, io};
45use tempfile::TempDir;
67// 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 {
25use std::ffi::OsString;
26use std::path;
27let mut components = p.components();
28let prefix = match components.next() {
29Some(path::Component::Prefix(p)) => p,
30_ => return p.to_path_buf(),
31 };
32match prefix.kind() {
33 path::Prefix::VerbatimDisk(disk) => {
34let 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) => {
39let 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}
4950#[cfg(not(windows))]
51pub fn fix_windows_verbatim_for_gcc(p: &Path) -> PathBuf {
52p.to_path_buf()
53}
5455pub enum LinkOrCopy {
56 Link,
57 Copy,
58}
5960/// 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.
7172let p = p.as_ref();
73let q = q.as_ref();
7475let err = match fs::hard_link(p, q) {
76Ok(()) => return Ok(LinkOrCopy::Link),
77Err(err) => err,
78 };
7980if err.kind() == io::ErrorKind::AlreadyExists {
81if !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)?;
85if fs::hard_link(p, q).is_ok() {
86return Ok(LinkOrCopy::Link);
87 }
88 }
8990// Hard linking failed, fall back to copying.
91fs::copy(p, q).map(|_| LinkOrCopy::Copy)
92}
9394#[cfg(any(unix, all(target_os = "wasi", target_env = "p1")))]
95pub fn path_to_c_string(p: &Path) -> CString {
96use std::ffi::OsStr;
97#[cfg(unix)]
98use std::os::unix::ffi::OsStrExt;
99#[cfg(all(target_os = "wasi", target_env = "p1"))]
100use std::os::wasi::ffi::OsStrExt;
101102let p: &OsStr = p.as_ref();
103CString::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}
109110#[inline]
111pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
112 fs::canonicalize(&path).or_else(|_| absolute(&path))
113}
114115pub struct TempDirBuilder<'a, 'b> {
116 builder: tempfile::Builder<'a, 'b>,
117}
118119impl<'a, 'b> TempDirBuilder<'a, 'b> {
120pub fn new() -> Self {
121Self { builder: tempfile::Builder::new() }
122 }
123124pub fn prefix<S: AsRef<OsStr> + ?Sized>(&mut self, prefix: &'a S) -> &mut Self {
125self.builder.prefix(prefix);
126self127 }
128129pub fn suffix<S: AsRef<OsStr> + ?Sized>(&mut self, suffix: &'b S) -> &mut Self {
130self.builder.suffix(suffix);
131self132 }
133134pub fn tempdir_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<TempDir> {
135let 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)]
140for wait in 1..11 {
141match self.builder.tempdir_in(dir) {
142Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {}
143 t => return t,
144 }
145 std::thread::sleep(std::time::Duration::from_millis(1 << wait));
146 }
147self.builder.tempdir_in(dir)
148 }
149}