Skip to content

Commit db4e287

Browse files
authored
Rollup merge of rust-lang#139870 - Shourya742:2025-04-15-add-retries-to-remove_and_create_dir_all, r=jieyouxu
add retries to remove and create dir all closes: rust-lang#139230 r? ``@jieyouxu``
2 parents 76c06b6 + d4eab8a commit db4e287

File tree

5 files changed

+72
-25
lines changed

5 files changed

+72
-25
lines changed

src/build_helper/src/fs/mod.rs

+46-10
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,27 @@ where
2222
/// A wrapper around [`std::fs::remove_dir_all`] that can also be used on *non-directory entries*,
2323
/// including files and symbolic links.
2424
///
25-
/// - This will produce an error if the target path is not found.
25+
/// - This will not produce an error if the target path is not found.
2626
/// - Like [`std::fs::remove_dir_all`], this helper does not traverse symbolic links, will remove
2727
/// symbolic link itself.
2828
/// - This helper is **not** robust against races on the underlying filesystem, behavior is
2929
/// unspecified if this helper is called concurrently.
3030
/// - This helper is not robust against TOCTOU problems.
3131
///
32-
/// FIXME: this implementation is insufficiently robust to replace bootstrap's clean `rm_rf`
33-
/// implementation:
34-
///
35-
/// - This implementation currently does not perform retries.
32+
/// FIXME: Audit whether this implementation is robust enough to replace bootstrap's clean `rm_rf`.
3633
#[track_caller]
3734
pub fn recursive_remove<P: AsRef<Path>>(path: P) -> io::Result<()> {
3835
let path = path.as_ref();
39-
let metadata = fs::symlink_metadata(path)?;
36+
37+
// If the path doesn't exist, we treat it as a successful no-op.
38+
// From the caller's perspective, the goal is simply "ensure this file/dir is gone" —
39+
// if it's already not there, that's a success, not an error.
40+
let metadata = match fs::symlink_metadata(path) {
41+
Ok(m) => m,
42+
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
43+
Err(e) => return Err(e),
44+
};
45+
4046
#[cfg(windows)]
4147
let is_dir_like = |meta: &fs::Metadata| {
4248
use std::os::windows::fs::FileTypeExt;
@@ -45,11 +51,35 @@ pub fn recursive_remove<P: AsRef<Path>>(path: P) -> io::Result<()> {
4551
#[cfg(not(windows))]
4652
let is_dir_like = fs::Metadata::is_dir;
4753

48-
if is_dir_like(&metadata) {
49-
fs::remove_dir_all(path)
50-
} else {
51-
try_remove_op_set_perms(fs::remove_file, path, metadata)
54+
const MAX_RETRIES: usize = 5;
55+
const RETRY_DELAY_MS: u64 = 100;
56+
57+
let try_remove = || {
58+
if is_dir_like(&metadata) {
59+
fs::remove_dir_all(path)
60+
} else {
61+
try_remove_op_set_perms(fs::remove_file, path, metadata.clone())
62+
}
63+
};
64+
65+
// Retry deletion a few times to handle transient filesystem errors.
66+
// This is unusual for local file operations, but it's a mitigation
67+
// against unlikely events where malware scanners may be holding a
68+
// file beyond our control, to give the malware scanners some opportunity
69+
// to release their hold.
70+
for attempt in 0..MAX_RETRIES {
71+
match try_remove() {
72+
Ok(()) => return Ok(()),
73+
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
74+
Err(_) if attempt < MAX_RETRIES - 1 => {
75+
std::thread::sleep(std::time::Duration::from_millis(RETRY_DELAY_MS));
76+
continue;
77+
}
78+
Err(e) => return Err(e),
79+
}
5280
}
81+
82+
Ok(())
5383
}
5484

5585
fn try_remove_op_set_perms<'p, Op>(mut op: Op, path: &'p Path, metadata: Metadata) -> io::Result<()>
@@ -67,3 +97,9 @@ where
6797
Err(e) => Err(e),
6898
}
6999
}
100+
101+
pub fn remove_and_create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
102+
let path = path.as_ref();
103+
recursive_remove(path)?;
104+
fs::create_dir_all(path)
105+
}

src/build_helper/src/fs/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ mod recursive_remove_tests {
1414
let tmpdir = env::temp_dir();
1515
let path = tmpdir.join("__INTERNAL_BOOTSTRAP_nonexistent_path");
1616
assert!(fs::symlink_metadata(&path).is_err_and(|e| e.kind() == io::ErrorKind::NotFound));
17-
assert!(recursive_remove(&path).is_err_and(|e| e.kind() == io::ErrorKind::NotFound));
17+
assert!(recursive_remove(&path).is_ok());
1818
}
1919

2020
#[test]

src/tools/compiletest/src/runtest.rs

+19-12
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio};
99
use std::sync::Arc;
1010
use std::{env, iter, str};
1111

12+
use build_helper::fs::remove_and_create_dir_all;
1213
use camino::{Utf8Path, Utf8PathBuf};
1314
use colored::Colorize;
1415
use regex::{Captures, Regex};
@@ -207,12 +208,6 @@ pub fn compute_stamp_hash(config: &Config) -> String {
207208
format!("{:x}", hash.finish())
208209
}
209210

210-
fn remove_and_create_dir_all(path: &Utf8Path) {
211-
let path = path.as_std_path();
212-
let _ = fs::remove_dir_all(path);
213-
fs::create_dir_all(path).unwrap();
214-
}
215-
216211
#[derive(Copy, Clone, Debug)]
217212
struct TestCx<'test> {
218213
config: &'test Config,
@@ -523,7 +518,9 @@ impl<'test> TestCx<'test> {
523518
let mut rustc = Command::new(&self.config.rustc_path);
524519

525520
let out_dir = self.output_base_name().with_extension("pretty-out");
526-
remove_and_create_dir_all(&out_dir);
521+
remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| {
522+
panic!("failed to remove and recreate output directory `{out_dir}`: {e}")
523+
});
527524

528525
let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
529526

@@ -1098,13 +1095,19 @@ impl<'test> TestCx<'test> {
10981095
let aux_dir = self.aux_output_dir_name();
10991096

11001097
if !self.props.aux.builds.is_empty() {
1101-
remove_and_create_dir_all(&aux_dir);
1098+
remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| {
1099+
panic!("failed to remove and recreate output directory `{aux_dir}`: {e}")
1100+
});
11021101
}
11031102

11041103
if !self.props.aux.bins.is_empty() {
11051104
let aux_bin_dir = self.aux_bin_output_dir_name();
1106-
remove_and_create_dir_all(&aux_dir);
1107-
remove_and_create_dir_all(&aux_bin_dir);
1105+
remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| {
1106+
panic!("failed to remove and recreate output directory `{aux_dir}`: {e}")
1107+
});
1108+
remove_and_create_dir_all(&aux_bin_dir).unwrap_or_else(|e| {
1109+
panic!("failed to remove and recreate output directory `{aux_bin_dir}`: {e}")
1110+
});
11081111
}
11091112

11101113
aux_dir
@@ -1509,7 +1512,9 @@ impl<'test> TestCx<'test> {
15091512

15101513
let set_mir_dump_dir = |rustc: &mut Command| {
15111514
let mir_dump_dir = self.get_mir_dump_dir();
1512-
remove_and_create_dir_all(&mir_dump_dir);
1515+
remove_and_create_dir_all(&mir_dump_dir).unwrap_or_else(|e| {
1516+
panic!("failed to remove and recreate output directory `{mir_dump_dir}`: {e}")
1517+
});
15131518
let mut dir_opt = "-Zdump-mir-dir=".to_string();
15141519
dir_opt.push_str(mir_dump_dir.as_str());
15151520
debug!("dir_opt: {:?}", dir_opt);
@@ -1969,7 +1974,9 @@ impl<'test> TestCx<'test> {
19691974
let suffix =
19701975
self.safe_revision().map_or("nightly".into(), |path| path.to_owned() + "-nightly");
19711976
let compare_dir = output_base_dir(self.config, self.testpaths, Some(&suffix));
1972-
remove_and_create_dir_all(&compare_dir);
1977+
remove_and_create_dir_all(&compare_dir).unwrap_or_else(|e| {
1978+
panic!("failed to remove and recreate output directory `{compare_dir}`: {e}")
1979+
});
19731980

19741981
// We need to create a new struct for the lifetimes on `config` to work.
19751982
let new_rustdoc = TestCx {

src/tools/compiletest/src/runtest/rustdoc.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ impl TestCx<'_> {
77
assert!(self.revision.is_none(), "revisions not relevant here");
88

99
let out_dir = self.output_base_dir();
10-
remove_and_create_dir_all(&out_dir);
10+
remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| {
11+
panic!("failed to remove and recreate output directory `{out_dir}`: {e}")
12+
});
1113

1214
let proc_res = self.document(&out_dir, &self.testpaths);
1315
if !proc_res.status.success() {

src/tools/compiletest/src/runtest/rustdoc_json.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ impl TestCx<'_> {
99
assert!(self.revision.is_none(), "revisions not relevant here");
1010

1111
let out_dir = self.output_base_dir();
12-
remove_and_create_dir_all(&out_dir);
12+
remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| {
13+
panic!("failed to remove and recreate output directory `{out_dir}`: {e}")
14+
});
1315

1416
let proc_res = self.document(&out_dir, &self.testpaths);
1517
if !proc_res.status.success() {

0 commit comments

Comments
 (0)