1use std::ffi::OsStr;
7use std::path::{Path, PathBuf};
8use std::sync::OnceLock;
9use std::thread::panicking;
10use std::time::{Instant, SystemTime, UNIX_EPOCH};
11use std::{env, fs, io, panic, str};
12
13use object::read::archive::ArchiveFile;
14
15use crate::LldMode;
16use crate::core::builder::Builder;
17use crate::core::config::{Config, TargetSelection};
18use crate::utils::exec::{BootstrapCommand, command};
19pub use crate::utils::shared_helpers::{dylib_path, dylib_path_var};
20
21#[cfg(test)]
22mod tests;
23
24pub struct PanicTracker<'a>(pub &'a panic::Location<'a>);
27
28impl Drop for PanicTracker<'_> {
29 fn drop(&mut self) {
30 if panicking() {
31 eprintln!(
32 "Panic was initiated from {}:{}:{}",
33 self.0.file(),
34 self.0.line(),
35 self.0.column()
36 );
37 }
38 }
39}
40
41#[macro_export]
50macro_rules! t {
51 ($e:expr) => {{
52 let _panic_guard = $crate::PanicTracker(std::panic::Location::caller());
53 match $e {
54 Ok(e) => e,
55 Err(e) => panic!("{} failed with {}", stringify!($e), e),
56 }
57 }};
58 ($e:expr, $extra:expr) => {{
60 let _panic_guard = $crate::PanicTracker(std::panic::Location::caller());
61 match $e {
62 Ok(e) => e,
63 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
64 }
65 }};
66}
67
68pub use t;
69pub fn exe(name: &str, target: TargetSelection) -> String {
70 crate::utils::shared_helpers::exe(name, &target.triple)
71}
72
73pub fn split_debuginfo(name: impl Into<PathBuf>) -> Option<PathBuf> {
75 let path = name.into();
78 let pdb = path.with_extension("pdb");
79 if pdb.exists() {
80 return Some(pdb);
81 }
82
83 let file_name = pdb.file_name()?.to_str()?.replace("-", "_");
85
86 let pdb: PathBuf = [path.parent()?, Path::new(&file_name)].into_iter().collect();
87 pdb.exists().then_some(pdb)
88}
89
90pub fn is_dylib(path: &Path) -> bool {
92 path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| {
93 ext == "dylib" || ext == "so" || ext == "dll" || (ext == "a" && is_aix_shared_archive(path))
94 })
95}
96
97pub fn submodule_path_of(builder: &Builder<'_>, path: &str) -> Option<String> {
99 let submodule_paths = builder.submodule_paths();
100 submodule_paths.iter().find_map(|submodule_path| {
101 if path.starts_with(submodule_path) { Some(submodule_path.to_string()) } else { None }
102 })
103}
104
105fn is_aix_shared_archive(path: &Path) -> bool {
106 let file = match fs::File::open(path) {
107 Ok(file) => file,
108 Err(_) => return false,
109 };
110 let reader = object::ReadCache::new(file);
111 let archive = match ArchiveFile::parse(&reader) {
112 Ok(result) => result,
113 Err(_) => return false,
114 };
115
116 archive
117 .members()
118 .filter_map(Result::ok)
119 .any(|entry| String::from_utf8_lossy(entry.name()).contains(".so"))
120}
121
122pub fn is_debug_info(name: &str) -> bool {
124 name.ends_with(".pdb")
126}
127
128pub fn libdir(target: TargetSelection) -> &'static str {
131 if target.is_windows() || target.contains("cygwin") { "bin" } else { "lib" }
132}
133
134pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut BootstrapCommand) {
137 let mut list = dylib_path();
138 for path in path {
139 list.insert(0, path);
140 }
141 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
142}
143
144pub struct TimeIt(bool, Instant);
145
146pub fn timeit(builder: &Builder<'_>) -> TimeIt {
148 TimeIt(builder.config.dry_run(), Instant::now())
149}
150
151impl Drop for TimeIt {
152 fn drop(&mut self) {
153 let time = self.1.elapsed();
154 if !self.0 {
155 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
156 }
157 }
158}
159
160pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()> {
163 if config.dry_run() {
164 return Ok(());
165 }
166 let _ = fs::remove_dir_all(link);
167 return symlink_dir_inner(original, link);
168
169 #[cfg(not(windows))]
170 fn symlink_dir_inner(original: &Path, link: &Path) -> io::Result<()> {
171 use std::os::unix::fs;
172 fs::symlink(original, link)
173 }
174
175 #[cfg(windows)]
176 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
177 junction::create(target, junction)
178 }
179}
180
181pub fn get_host_target() -> TargetSelection {
183 TargetSelection::from_user(env!("BUILD_TRIPLE"))
184}
185
186pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
189 match fs::rename(&from, &to) {
190 Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
191 std::fs::copy(&from, &to)?;
192 std::fs::remove_file(&from)
193 }
194 r => r,
195 }
196}
197
198pub fn forcing_clang_based_tests() -> bool {
199 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
200 match &var.to_string_lossy().to_lowercase()[..] {
201 "1" | "yes" | "on" => true,
202 "0" | "no" | "off" => false,
203 other => {
204 panic!(
206 "Unrecognized option '{other}' set in \
207 RUSTBUILD_FORCE_CLANG_BASED_TESTS"
208 )
209 }
210 }
211 } else {
212 false
213 }
214}
215
216pub fn use_host_linker(target: TargetSelection) -> bool {
217 !(target.contains("emscripten")
220 || target.contains("wasm32")
221 || target.contains("nvptx")
222 || target.contains("fortanix")
223 || target.contains("fuchsia")
224 || target.contains("bpf")
225 || target.contains("switch"))
226}
227
228pub fn target_supports_cranelift_backend(target: TargetSelection) -> bool {
229 if target.contains("linux") {
230 target.contains("x86_64")
231 || target.contains("aarch64")
232 || target.contains("s390x")
233 || target.contains("riscv64gc")
234 } else if target.contains("darwin") {
235 target.contains("x86_64") || target.contains("aarch64")
236 } else if target.is_windows() {
237 target.contains("x86_64")
238 } else {
239 false
240 }
241}
242
243pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
244 path: &'a Path,
245 suite_path: P,
246 builder: &Builder<'_>,
247) -> Option<&'a str> {
248 let suite_path = suite_path.as_ref();
249 let path = match path.strip_prefix(".") {
250 Ok(p) => p,
251 Err(_) => path,
252 };
253 if !path.starts_with(suite_path) {
254 return None;
255 }
256 let abs_path = builder.src.join(path);
257 let exists = abs_path.is_dir() || abs_path.is_file();
258 if !exists {
259 panic!(
260 "Invalid test suite filter \"{}\": file or directory does not exist",
261 abs_path.display()
262 );
263 }
264 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
271 Some(s) if !s.is_empty() => Some(s),
272 _ => None,
273 }
274}
275
276pub fn make(host: &str) -> PathBuf {
277 if host.contains("dragonfly")
278 || host.contains("freebsd")
279 || host.contains("netbsd")
280 || host.contains("openbsd")
281 {
282 PathBuf::from("gmake")
283 } else {
284 PathBuf::from("make")
285 }
286}
287
288pub fn mtime(path: &Path) -> SystemTime {
290 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
291}
292
293pub fn up_to_date(src: &Path, dst: &Path) -> bool {
298 if !dst.exists() {
299 return false;
300 }
301 let threshold = mtime(dst);
302 let meta = match fs::metadata(src) {
303 Ok(meta) => meta,
304 Err(e) => panic!("source {src:?} failed to get metadata: {e}"),
305 };
306 if meta.is_dir() {
307 dir_up_to_date(src, threshold)
308 } else {
309 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
310 }
311}
312
313pub fn unhashed_basename(obj: &Path) -> &str {
318 let basename = obj.file_stem().unwrap().to_str().expect("UTF-8 file name");
319 basename.split_once('-').unwrap().1
320}
321
322fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
323 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
324 let meta = t!(e.metadata());
325 if meta.is_dir() {
326 dir_up_to_date(&e.path(), threshold)
327 } else {
328 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
329 }
330 })
331}
332
333pub fn get_clang_cl_resource_dir(builder: &Builder<'_>, clang_cl_path: &str) -> PathBuf {
339 let mut builtins_locator = command(clang_cl_path);
342 builtins_locator.args(["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
343
344 let clang_rt_builtins = builtins_locator.run_capture_stdout(builder).stdout();
345 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
346 assert!(
347 clang_rt_builtins.exists(),
348 "`clang-cl` must correctly locate the library runtime directory"
349 );
350
351 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
354 clang_rt_dir.to_path_buf()
355}
356
357fn lld_flag_no_threads(builder: &Builder<'_>, lld_mode: LldMode, is_windows: bool) -> &'static str {
361 static LLD_NO_THREADS: OnceLock<(&'static str, &'static str)> = OnceLock::new();
362
363 let new_flags = ("/threads:1", "--threads=1");
364 let old_flags = ("/no-threads", "--no-threads");
365
366 let (windows_flag, other_flag) = LLD_NO_THREADS.get_or_init(|| {
367 let newer_version = match lld_mode {
368 LldMode::External => {
369 let mut cmd = command("lld");
370 cmd.arg("-flavor").arg("ld").arg("--version");
371 let out = cmd.run_capture_stdout(builder).stdout();
372 match (out.find(char::is_numeric), out.find('.')) {
373 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
374 _ => true,
375 }
376 }
377 _ => true,
378 };
379 if newer_version { new_flags } else { old_flags }
380 });
381 if is_windows { windows_flag } else { other_flag }
382}
383
384pub fn dir_is_empty(dir: &Path) -> bool {
385 t!(std::fs::read_dir(dir), dir).next().is_none()
386}
387
388pub fn extract_beta_rev(version: &str) -> Option<String> {
393 let parts = version.splitn(2, "-beta.").collect::<Vec<_>>();
394 parts.get(1).and_then(|s| s.find(' ').map(|p| s[..p].to_string()))
395}
396
397pub enum LldThreads {
398 Yes,
399 No,
400}
401
402pub fn linker_args(
404 builder: &Builder<'_>,
405 target: TargetSelection,
406 lld_threads: LldThreads,
407) -> Vec<String> {
408 let mut args = linker_flags(builder, target, lld_threads);
409
410 if let Some(linker) = builder.linker(target) {
411 args.push(format!("-Clinker={}", linker.display()));
412 }
413
414 args
415}
416
417pub fn linker_flags(
420 builder: &Builder<'_>,
421 target: TargetSelection,
422 lld_threads: LldThreads,
423) -> Vec<String> {
424 let mut args = vec![];
425 if !builder.is_lld_direct_linker(target) && builder.config.lld_mode.is_used() {
426 match builder.config.lld_mode {
427 LldMode::External => {
428 args.push("-Zlinker-features=+lld".to_string());
429 args.push("-Zunstable-options".to_string());
431 }
432 LldMode::SelfContained => {
433 args.push("-Zlinker-features=+lld".to_string());
434 args.push("-Clink-self-contained=+linker".to_string());
435 args.push("-Zunstable-options".to_string());
437 }
438 LldMode::Unused => unreachable!(),
439 };
440
441 if matches!(lld_threads, LldThreads::No) {
442 args.push(format!(
443 "-Clink-arg=-Wl,{}",
444 lld_flag_no_threads(builder, builder.config.lld_mode, target.is_windows())
445 ));
446 }
447 }
448 args
449}
450
451pub fn add_rustdoc_cargo_linker_args(
452 cmd: &mut BootstrapCommand,
453 builder: &Builder<'_>,
454 target: TargetSelection,
455 lld_threads: LldThreads,
456) {
457 let args = linker_args(builder, target, lld_threads);
458 let mut flags = cmd
459 .get_envs()
460 .find_map(|(k, v)| if k == OsStr::new("RUSTDOCFLAGS") { v } else { None })
461 .unwrap_or_default()
462 .to_os_string();
463 for arg in args {
464 if !flags.is_empty() {
465 flags.push(" ");
466 }
467 flags.push(arg);
468 }
469 if !flags.is_empty() {
470 cmd.env("RUSTDOCFLAGS", flags);
471 }
472}
473
474pub fn hex_encode<T>(input: T) -> String
476where
477 T: AsRef<[u8]>,
478{
479 use std::fmt::Write;
480
481 input.as_ref().iter().fold(String::with_capacity(input.as_ref().len() * 2), |mut acc, &byte| {
482 write!(&mut acc, "{byte:02x}").expect("Failed to write byte to the hex String.");
483 acc
484 })
485}
486
487pub fn check_cfg_arg(name: &str, values: Option<&[&str]>) -> String {
490 let next = match values {
493 Some(values) => {
494 let mut tmp = values.iter().flat_map(|val| [",", "\"", val, "\""]).collect::<String>();
495
496 tmp.insert_str(1, "values(");
497 tmp.push(')');
498 tmp
499 }
500 None => "".to_string(),
501 };
502 format!("--check-cfg=cfg({name}{next})")
503}
504
505#[track_caller]
513pub fn git(source_dir: Option<&Path>) -> BootstrapCommand {
514 let mut git = command("git");
515
516 if let Some(source_dir) = source_dir {
517 git.current_dir(source_dir);
518 git.env_remove("GIT_DIR");
521 git.env_remove("GIT_WORK_TREE")
525 .env_remove("GIT_INDEX_FILE")
526 .env_remove("GIT_OBJECT_DIRECTORY")
527 .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES");
528 }
529
530 git
531}
532
533pub fn set_file_times<P: AsRef<Path>>(path: P, times: fs::FileTimes) -> io::Result<()> {
535 let f = if cfg!(windows) {
538 fs::File::options().write(true).open(path)?
539 } else {
540 fs::File::open(path)?
541 };
542 f.set_times(times)
543}