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 build_helper::ci::CiEnv;
14use object::read::archive::ArchiveFile;
15
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};
20use crate::{BootstrapOverrideLld, StepStack};
21
22#[cfg(test)]
23mod tests;
24
25pub struct PanicTracker<'a>(pub &'a panic::Location<'a>);
28
29impl Drop for PanicTracker<'_> {
30 fn drop(&mut self) {
31 if panicking() {
32 eprintln!(
33 "Panic was initiated from {}:{}:{}",
34 self.0.file(),
35 self.0.line(),
36 self.0.column()
37 );
38 }
39 }
40}
41
42#[macro_export]
51macro_rules! t {
52 ($e:expr) => {{
53 let _panic_guard = $crate::PanicTracker(std::panic::Location::caller());
54 match $e {
55 Ok(e) => e,
56 Err(e) => panic!("{} failed with {}", stringify!($e), e),
57 }
58 }};
59 ($e:expr, $extra:expr) => {{
61 let _panic_guard = $crate::PanicTracker(std::panic::Location::caller());
62 match $e {
63 Ok(e) => e,
64 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
65 }
66 }};
67}
68
69pub use t;
70pub fn exe(name: &str, target: TargetSelection) -> String {
71 crate::utils::shared_helpers::exe(name, &target.triple)
72}
73
74pub fn split_debuginfo(name: impl Into<PathBuf>) -> Option<PathBuf> {
76 let path = name.into();
79 let pdb = path.with_extension("pdb");
80 if pdb.exists() {
81 return Some(pdb);
82 }
83
84 let file_name = pdb.file_name()?.to_str()?.replace("-", "_");
86
87 let pdb: PathBuf = [path.parent()?, Path::new(&file_name)].into_iter().collect();
88 pdb.exists().then_some(pdb)
89}
90
91pub fn is_dylib(path: &Path) -> bool {
93 path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| {
94 ext == "dylib" || ext == "so" || ext == "dll" || (ext == "a" && is_aix_shared_archive(path))
95 })
96}
97
98pub fn submodule_path_of(builder: &Builder<'_>, path: &str) -> Option<String> {
100 submodule_path_of_paths(builder.submodule_paths(), path)
101}
102
103fn submodule_path_of_paths(submodule_paths: &[String], path: &str) -> Option<String> {
104 let path = Path::new(path);
105 submodule_paths.iter().find_map(|submodule_path| {
106 if path.starts_with(submodule_path) { Some(submodule_path.to_string()) } else { None }
107 })
108}
109
110fn is_aix_shared_archive(path: &Path) -> bool {
111 let file = match fs::File::open(path) {
112 Ok(file) => file,
113 Err(_) => return false,
114 };
115 let reader = object::ReadCache::new(file);
116 let archive = match ArchiveFile::parse(&reader) {
117 Ok(result) => result,
118 Err(_) => return false,
119 };
120
121 archive
122 .members()
123 .filter_map(Result::ok)
124 .any(|entry| String::from_utf8_lossy(entry.name()).contains(".so"))
125}
126
127pub fn is_debug_info(name: &str) -> bool {
129 name.ends_with(".pdb")
131}
132
133pub fn libdir(target: TargetSelection) -> &'static str {
136 if target.is_windows() || target.contains("cygwin") { "bin" } else { "lib" }
137}
138
139pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut BootstrapCommand) {
142 let mut list = dylib_path();
143 for path in path {
144 list.insert(0, path);
145 }
146 cmd.env(dylib_path_var(), t!(env::join_paths(list)));
147}
148
149pub struct TimeIt(bool, Instant);
150
151pub fn timeit(builder: &Builder<'_>) -> TimeIt {
153 TimeIt(builder.config.dry_run(), Instant::now())
154}
155
156impl Drop for TimeIt {
157 fn drop(&mut self) {
158 let time = self.1.elapsed();
159 if !self.0 {
160 println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
161 }
162 }
163}
164
165pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()> {
168 if config.dry_run() {
169 return Ok(());
170 }
171 let _ = fs::remove_dir_all(link);
172 return symlink_dir_inner(original, link);
173
174 #[cfg(not(windows))]
175 fn symlink_dir_inner(original: &Path, link: &Path) -> io::Result<()> {
176 use std::os::unix::fs;
177 fs::symlink(original, link)
178 }
179
180 #[cfg(windows)]
181 fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
182 junction::create(target, junction)
183 }
184}
185
186pub fn get_host_target() -> TargetSelection {
188 TargetSelection::from_user(env!("BUILD_TRIPLE"))
189}
190
191pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
194 match fs::rename(&from, &to) {
195 Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
196 std::fs::copy(&from, &to)?;
197 std::fs::remove_file(&from)
198 }
199 r => r,
200 }
201}
202
203pub fn forcing_clang_based_tests() -> bool {
204 if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
205 match &var.to_string_lossy().to_lowercase()[..] {
206 "1" | "yes" | "on" => true,
207 "0" | "no" | "off" => false,
208 other => {
209 panic!(
211 "Unrecognized option '{other}' set in \
212 RUSTBUILD_FORCE_CLANG_BASED_TESTS"
213 )
214 }
215 }
216 } else {
217 false
218 }
219}
220
221pub fn use_host_linker(target: TargetSelection) -> bool {
222 !(target.contains("emscripten")
225 || target.contains("wasm32")
226 || target.contains("nvptx")
227 || target.contains("fortanix")
228 || target.contains("fuchsia")
229 || target.contains("bpf")
230 || target.contains("switch"))
231}
232
233pub fn target_supports_cranelift_backend(target: TargetSelection) -> bool {
234 if target.contains("linux") {
235 target.contains("x86_64")
236 || target.contains("aarch64")
237 || target.contains("s390x")
238 || target.contains("riscv64gc")
239 } else if target.contains("darwin") {
240 target.contains("x86_64") || target.contains("aarch64")
241 } else if target.is_windows() {
242 target.contains("x86_64")
243 } else {
244 false
245 }
246}
247
248pub enum TestFilterCategory<'a> {
251 Fullsuite,
253 Arg(&'a str),
256 Uninteresting,
258}
259
260pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
261 path: &'a Path,
262 suite_path: P,
263 builder: &Builder<'_>,
264) -> TestFilterCategory<'a> {
265 let suite_path = suite_path.as_ref();
266 let path = match path.strip_prefix(".") {
267 Ok(p) => p,
268 Err(_) => path,
269 };
270 if !path.starts_with(suite_path) {
271 return TestFilterCategory::Uninteresting;
272 }
273 let abs_path = builder.src.join(path);
274 let exists = abs_path.is_dir() || abs_path.is_file();
275 if !exists {
276 panic!(
277 "Invalid test suite filter \"{}\": file or directory does not exist",
278 abs_path.display()
279 );
280 }
281 match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
288 Some(s) if !s.is_empty() => TestFilterCategory::Arg(s),
289 _ => TestFilterCategory::Fullsuite,
290 }
291}
292
293pub fn make(host: &str) -> PathBuf {
294 if host.contains("dragonfly")
295 || host.contains("freebsd")
296 || host.contains("netbsd")
297 || host.contains("openbsd")
298 {
299 PathBuf::from("gmake")
300 } else {
301 PathBuf::from("make")
302 }
303}
304
305pub fn mtime(path: &Path) -> SystemTime {
307 fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
308}
309
310pub fn up_to_date(src: &Path, dst: &Path) -> bool {
315 if !dst.exists() {
316 return false;
317 }
318 let threshold = mtime(dst);
319 let meta = match fs::metadata(src) {
320 Ok(meta) => meta,
321 Err(e) => panic!("source {src:?} failed to get metadata: {e}"),
322 };
323 if meta.is_dir() {
324 dir_up_to_date(src, threshold)
325 } else {
326 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
327 }
328}
329
330pub fn unhashed_basename(obj: &Path) -> &str {
335 let basename = obj.file_stem().unwrap().to_str().expect("UTF-8 file name");
336 basename.split_once('-').unwrap().1
337}
338
339fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
340 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
341 let meta = t!(e.metadata());
342 if meta.is_dir() {
343 dir_up_to_date(&e.path(), threshold)
344 } else {
345 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
346 }
347 })
348}
349
350pub fn get_clang_cl_resource_dir(builder: &Builder<'_>, clang_cl_path: &str) -> PathBuf {
356 let mut builtins_locator = command(clang_cl_path);
359 builtins_locator.args(["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
360
361 let clang_rt_builtins = builtins_locator.run_capture_stdout(builder).stdout();
362 let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
363 assert!(
364 clang_rt_builtins.exists(),
365 "`clang-cl` must correctly locate the library runtime directory"
366 );
367
368 let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
371 clang_rt_dir.to_path_buf()
372}
373
374fn lld_flag_no_threads(
378 builder: &Builder<'_>,
379 bootstrap_override_lld: BootstrapOverrideLld,
380 is_windows: bool,
381) -> &'static str {
382 static LLD_NO_THREADS: OnceLock<(&'static str, &'static str)> = OnceLock::new();
383
384 let new_flags = ("/threads:1", "--threads=1");
385 let old_flags = ("/no-threads", "--no-threads");
386
387 let (windows_flag, other_flag) = LLD_NO_THREADS.get_or_init(|| {
388 let newer_version = match bootstrap_override_lld {
389 BootstrapOverrideLld::External => {
390 let mut cmd = command("lld");
391 cmd.arg("-flavor").arg("ld").arg("--version");
392 let out = cmd.run_capture_stdout(builder).stdout();
393 match (out.find(char::is_numeric), out.find('.')) {
394 (Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
395 _ => true,
396 }
397 }
398 _ => true,
399 };
400 if newer_version { new_flags } else { old_flags }
401 });
402 if is_windows { windows_flag } else { other_flag }
403}
404
405pub fn dir_is_empty(dir: &Path) -> bool {
406 t!(std::fs::read_dir(dir), dir).next().is_none()
407}
408
409pub fn extract_beta_rev(version: &str) -> Option<String> {
414 let parts = version.splitn(2, "-beta.").collect::<Vec<_>>();
415 parts.get(1).and_then(|s| s.find(' ').map(|p| s[..p].to_string()))
416}
417
418pub enum LldThreads {
419 Yes,
420 No,
421}
422
423pub fn linker_args(
425 builder: &Builder<'_>,
426 target: TargetSelection,
427 lld_threads: LldThreads,
428) -> Vec<String> {
429 let mut args = linker_flags(builder, target, lld_threads);
430
431 if let Some(linker) = builder.linker(target) {
432 args.push(format!("-Clinker={}", linker.display()));
433 }
434
435 args
436}
437
438pub fn linker_flags(
441 builder: &Builder<'_>,
442 target: TargetSelection,
443 lld_threads: LldThreads,
444) -> Vec<String> {
445 let mut args = vec![];
446 if !builder.is_lld_direct_linker(target) && builder.config.bootstrap_override_lld.is_used() {
447 match builder.config.bootstrap_override_lld {
448 BootstrapOverrideLld::External => {
449 args.push("-Clinker-features=+lld".to_string());
450 args.push("-Clink-self-contained=-linker".to_string());
451 args.push("-Zunstable-options".to_string());
452 }
453 BootstrapOverrideLld::SelfContained => {
454 args.push("-Clinker-features=+lld".to_string());
455 args.push("-Clink-self-contained=+linker".to_string());
456 args.push("-Zunstable-options".to_string());
457 }
458 BootstrapOverrideLld::None => unreachable!(),
459 };
460
461 if matches!(lld_threads, LldThreads::No) {
462 args.push(format!(
463 "-Clink-arg=-Wl,{}",
464 lld_flag_no_threads(
465 builder,
466 builder.config.bootstrap_override_lld,
467 target.is_windows()
468 )
469 ));
470 }
471 }
472 args
473}
474
475pub fn add_rustdoc_cargo_linker_args(
476 cmd: &mut BootstrapCommand,
477 builder: &Builder<'_>,
478 target: TargetSelection,
479 lld_threads: LldThreads,
480) {
481 let args = linker_args(builder, target, lld_threads);
482 let mut flags = cmd
483 .get_envs()
484 .find_map(|(k, v)| if k == OsStr::new("RUSTDOCFLAGS") { v } else { None })
485 .unwrap_or_default()
486 .to_os_string();
487 for arg in args {
488 if !flags.is_empty() {
489 flags.push(" ");
490 }
491 flags.push(arg);
492 }
493 if !flags.is_empty() {
494 cmd.env("RUSTDOCFLAGS", flags);
495 }
496}
497
498pub fn hex_encode<T>(input: T) -> String
500where
501 T: AsRef<[u8]>,
502{
503 use std::fmt::Write;
504
505 input.as_ref().iter().fold(String::with_capacity(input.as_ref().len() * 2), |mut acc, &byte| {
506 write!(&mut acc, "{byte:02x}").expect("Failed to write byte to the hex String.");
507 acc
508 })
509}
510
511pub fn check_cfg_arg(name: &str, values: Option<&[&str]>) -> String {
514 let next = match values {
517 Some(values) => {
518 let mut tmp = values.iter().flat_map(|val| [",", "\"", val, "\""]).collect::<String>();
519
520 tmp.insert_str(1, "values(");
521 tmp.push(')');
522 tmp
523 }
524 None => "".to_string(),
525 };
526 format!("--check-cfg=cfg({name}{next})")
527}
528
529#[track_caller]
537pub fn git(source_dir: Option<&Path>) -> BootstrapCommand {
538 let mut git = command("git");
539 git.cached();
541
542 if let Some(source_dir) = source_dir {
543 git.current_dir(source_dir);
544 git.env_remove("GIT_DIR");
547 git.env_remove("GIT_WORK_TREE")
551 .env_remove("GIT_INDEX_FILE")
552 .env_remove("GIT_OBJECT_DIRECTORY")
553 .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES");
554 }
555
556 git
557}
558
559pub fn set_file_times<P: AsRef<Path>>(path: P, times: fs::FileTimes) -> io::Result<()> {
561 let f = if cfg!(windows) {
564 fs::File::options().write(true).open(path)?
565 } else {
566 fs::File::open(path)?
567 };
568 f.set_times(times)
569}
570
571pub fn detail_exit(code: i32, is_test: bool) -> ! {
574 if is_test {
576 panic!("status code: {code}");
577 } else {
578 if CiEnv::is_ci() {
581 let bootstrap_args =
583 std::env::args().skip(1).map(|a| a.to_string()).collect::<Vec<_>>().join(" ");
584 eprintln!("Bootstrap failed while executing `{bootstrap_args}`");
585 eprintln!("Currently active steps:");
586 StepStack::with_current(|stack| {
587 for step in stack.get_active_steps() {
588 eprintln!("{} at {}", step.info, step.location);
589 }
590 });
591 }
592
593 std::process::exit(code);
595 }
596}
597
598pub fn fail(s: &str) -> ! {
599 eprintln!("\n\n{s}\n\n");
600 detail_exit(1, cfg!(test));
601}