1use std::cell::{Cell, RefCell};
20use std::collections::{BTreeSet, HashMap, HashSet};
21use std::fmt::Display;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24use std::sync::OnceLock;
25use std::time::SystemTime;
26use std::{env, fs, io, str};
27
28use build_helper::ci::gha;
29use build_helper::exit;
30use termcolor::{ColorChoice, StandardStream, WriteColor};
31use utils::build_stamp::BuildStamp;
32use utils::channel::GitInfo;
33
34use crate::core::builder;
35use crate::core::builder::Kind;
36use crate::core::config::{DryRun, LldMode, LlvmLibunwind, Target, TargetSelection, flags};
37use crate::utils::exec::{BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode, command};
38use crate::utils::helpers::{self, dir_is_empty, exe, libdir, output, set_file_times, symlink_dir};
39
40mod core;
41mod utils;
42
43pub use core::builder::PathSet;
44pub use core::config::Config;
45pub use core::config::flags::{Flags, Subcommand};
46
47#[cfg(feature = "tracing")]
48use tracing::{instrument, span};
49pub use utils::change_tracker::{
50 CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
51};
52
53use crate::core::build_steps::vendor::VENDOR_DIR;
54
55const LLVM_TOOLS: &[&str] = &[
56 "llvm-cov", "llvm-nm", "llvm-objcopy", "llvm-objdump", "llvm-profdata", "llvm-readobj", "llvm-size", "llvm-strip", "llvm-ar", "llvm-as", "llvm-dis", "llvm-link", "llc", "opt", ];
71
72const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
74
75#[allow(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
79 (None, "bootstrap", None),
80 (Some(Mode::Rustc), "llvm_enzyme", None),
81 (Some(Mode::Codegen), "llvm_enzyme", None),
82 (Some(Mode::ToolRustc), "llvm_enzyme", None),
83 (Some(Mode::ToolRustc), "rust_analyzer", None),
84 (Some(Mode::ToolStd), "rust_analyzer", None),
85 ];
89
90#[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
96pub struct Compiler {
97 stage: u32,
98 host: TargetSelection,
99}
100
101#[derive(PartialEq, Eq, Copy, Clone, Debug)]
102pub enum DocTests {
103 Yes,
105 No,
107 Only,
109}
110
111pub enum GitRepo {
112 Rustc,
113 Llvm,
114}
115
116#[derive(Clone)]
127pub struct Build {
128 config: Config,
130
131 version: String,
133
134 src: PathBuf,
136 out: PathBuf,
137 bootstrap_out: PathBuf,
138 cargo_info: GitInfo,
139 rust_analyzer_info: GitInfo,
140 clippy_info: GitInfo,
141 miri_info: GitInfo,
142 rustfmt_info: GitInfo,
143 enzyme_info: GitInfo,
144 in_tree_llvm_info: GitInfo,
145 in_tree_gcc_info: GitInfo,
146 local_rebuild: bool,
147 fail_fast: bool,
148 doc_tests: DocTests,
149 verbosity: usize,
150
151 build: TargetSelection,
153 hosts: Vec<TargetSelection>,
155 targets: Vec<TargetSelection>,
157
158 initial_rustc: PathBuf,
159 initial_rustdoc: PathBuf,
160 initial_cargo: PathBuf,
161 initial_lld: PathBuf,
162 initial_relative_libdir: PathBuf,
163 initial_sysroot: PathBuf,
164
165 cc: RefCell<HashMap<TargetSelection, cc::Tool>>,
168 cxx: RefCell<HashMap<TargetSelection, cc::Tool>>,
169 ar: RefCell<HashMap<TargetSelection, PathBuf>>,
170 ranlib: RefCell<HashMap<TargetSelection, PathBuf>>,
171 crates: HashMap<String, Crate>,
174 crate_paths: HashMap<PathBuf, String>,
175 is_sudo: bool,
176 delayed_failures: RefCell<Vec<String>>,
177 prerelease_version: Cell<Option<u32>>,
178
179 #[cfg(feature = "build-metrics")]
180 metrics: crate::utils::metrics::BuildMetrics,
181}
182
183#[derive(Debug, Clone)]
184struct Crate {
185 name: String,
186 deps: HashSet<String>,
187 path: PathBuf,
188 has_lib: bool,
189 features: Vec<String>,
190}
191
192impl Crate {
193 fn local_path(&self, build: &Build) -> PathBuf {
194 self.path.strip_prefix(&build.config.src).unwrap().into()
195 }
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
200pub enum DependencyType {
201 Host,
203 Target,
205 TargetSelfContained,
207}
208
209#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
214pub enum Mode {
215 Std,
217
218 Rustc,
220
221 Codegen,
223
224 ToolBootstrap,
231
232 ToolStd,
236
237 ToolRustc,
242}
243
244impl Mode {
245 pub fn is_tool(&self) -> bool {
246 matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
247 }
248
249 pub fn must_support_dlopen(&self) -> bool {
250 matches!(self, Mode::Std | Mode::Codegen)
251 }
252}
253
254#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
255pub enum CLang {
256 C,
257 Cxx,
258}
259
260macro_rules! forward {
261 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
262 impl Build {
263 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
264 self.config.$fn( $($param),* )
265 } )+
266 }
267 }
268}
269
270forward! {
271 verbose(f: impl Fn()),
272 is_verbose() -> bool,
273 create(path: &Path, s: &str),
274 remove(f: &Path),
275 tempdir() -> PathBuf,
276 llvm_link_shared() -> bool,
277 download_rustc() -> bool,
278 initial_rustfmt() -> Option<PathBuf>,
279}
280
281impl Build {
282 pub fn new(mut config: Config) -> Build {
287 let src = config.src.clone();
288 let out = config.out.clone();
289
290 #[cfg(unix)]
291 let is_sudo = match env::var_os("SUDO_USER") {
294 Some(_sudo_user) => {
295 let uid = unsafe { libc::getuid() };
300 uid == 0
301 }
302 None => false,
303 };
304 #[cfg(not(unix))]
305 let is_sudo = false;
306
307 let rust_info = config.rust_info.clone();
308 let cargo_info = config.cargo_info.clone();
309 let rust_analyzer_info = config.rust_analyzer_info.clone();
310 let clippy_info = config.clippy_info.clone();
311 let miri_info = config.miri_info.clone();
312 let rustfmt_info = config.rustfmt_info.clone();
313 let enzyme_info = config.enzyme_info.clone();
314 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
315 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
316
317 let initial_target_libdir_str =
318 config.initial_sysroot.join("lib/rustlib").join(config.build).join("lib");
319
320 let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
321 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
322
323 let initial_relative_libdir = initial_target_dir
324 .ancestors()
325 .nth(2)
326 .unwrap()
327 .strip_prefix(&config.initial_sysroot)
328 .expect("Couldn’t determine initial relative libdir.")
329 .to_path_buf();
330
331 let version = std::fs::read_to_string(src.join("src").join("version"))
332 .expect("failed to read src/version");
333 let version = version.trim();
334
335 let mut bootstrap_out = std::env::current_exe()
336 .expect("could not determine path to running process")
337 .parent()
338 .unwrap()
339 .to_path_buf();
340 if bootstrap_out.ends_with("deps") {
343 bootstrap_out.pop();
344 }
345 if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
346 panic!(
348 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
349 bootstrap_out.display()
350 )
351 }
352
353 if rust_info.is_from_tarball() && config.description.is_none() {
354 config.description = Some("built from a source tarball".to_owned());
355 }
356
357 let mut build = Build {
358 initial_lld,
359 initial_relative_libdir,
360 initial_rustc: config.initial_rustc.clone(),
361 initial_rustdoc: config.initial_rustc.with_file_name(exe("rustdoc", config.build)),
362 initial_cargo: config.initial_cargo.clone(),
363 initial_sysroot: config.initial_sysroot.clone(),
364 local_rebuild: config.local_rebuild,
365 fail_fast: config.cmd.fail_fast(),
366 doc_tests: config.cmd.doc_tests(),
367 verbosity: config.verbose,
368
369 build: config.build,
370 hosts: config.hosts.clone(),
371 targets: config.targets.clone(),
372
373 config,
374 version: version.to_string(),
375 src,
376 out,
377 bootstrap_out,
378
379 cargo_info,
380 rust_analyzer_info,
381 clippy_info,
382 miri_info,
383 rustfmt_info,
384 enzyme_info,
385 in_tree_llvm_info,
386 in_tree_gcc_info,
387 cc: RefCell::new(HashMap::new()),
388 cxx: RefCell::new(HashMap::new()),
389 ar: RefCell::new(HashMap::new()),
390 ranlib: RefCell::new(HashMap::new()),
391 crates: HashMap::new(),
392 crate_paths: HashMap::new(),
393 is_sudo,
394 delayed_failures: RefCell::new(Vec::new()),
395 prerelease_version: Cell::new(None),
396
397 #[cfg(feature = "build-metrics")]
398 metrics: crate::utils::metrics::BuildMetrics::init(),
399 };
400
401 let local_version_verbose =
404 output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
405 let local_release = local_version_verbose
406 .lines()
407 .filter_map(|x| x.strip_prefix("release:"))
408 .next()
409 .unwrap()
410 .trim();
411 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
412 build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
413 build.local_rebuild = true;
414 }
415
416 build.verbose(|| println!("finding compilers"));
417 utils::cc_detect::find(&build);
418 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
424 build.verbose(|| println!("running sanity check"));
425 crate::core::sanity::check(&mut build);
426
427 let rust_submodules = ["library/backtrace", "library/stdarch"];
430 for s in rust_submodules {
431 build.require_submodule(
432 s,
433 Some(
434 "The submodule is required for the standard library \
435 and the main Cargo workspace.",
436 ),
437 );
438 }
439 build.update_existing_submodules();
441
442 build.verbose(|| println!("learning about cargo"));
443 crate::core::metadata::build(&mut build);
444 }
445
446 let build_triple = build.out.join(build.build);
448 t!(fs::create_dir_all(&build_triple));
449 let host = build.out.join("host");
450 if host.is_symlink() {
451 #[cfg(windows)]
454 t!(fs::remove_dir(&host));
455 #[cfg(not(windows))]
456 t!(fs::remove_file(&host));
457 }
458 t!(
459 symlink_dir(&build.config, &build_triple, &host),
460 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
461 );
462
463 build
464 }
465
466 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
475 if self.rust_info().is_from_tarball() {
476 return;
477 }
478
479 if cfg!(test) && !self.config.submodules() {
482 return;
483 }
484 self.config.update_submodule(submodule);
485 let absolute_path = self.config.src.join(submodule);
486 if dir_is_empty(&absolute_path) {
487 let maybe_enable = if !self.config.submodules()
488 && self.config.rust_info.is_managed_git_subrepository()
489 {
490 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
491 } else {
492 ""
493 };
494 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
495 eprintln!(
496 "submodule {submodule} does not appear to be checked out, \
497 but it is required for this step{maybe_enable}{err_hint}"
498 );
499 exit!(1);
500 }
501 }
502
503 pub fn require_and_update_all_submodules(&self) {
506 for submodule in build_helper::util::parse_gitmodules(&self.src) {
507 self.require_submodule(submodule, None);
508 }
509 }
510
511 fn update_existing_submodules(&self) {
514 if !self.config.submodules() {
517 return;
518 }
519 let output = helpers::git(Some(&self.src))
520 .args(["config", "--file"])
521 .arg(".gitmodules")
522 .args(["--get-regexp", "path"])
523 .run_capture(self)
524 .stdout();
525 std::thread::scope(|s| {
526 for line in output.lines() {
529 let submodule = line.split_once(' ').unwrap().1;
530 let config = self.config.clone();
531 s.spawn(move || {
532 Self::update_existing_submodule(&config, submodule);
533 });
534 }
535 });
536 }
537
538 pub fn update_existing_submodule(config: &Config, submodule: &str) {
540 if !config.submodules() {
542 return;
543 }
544
545 if GitInfo::new(false, Path::new(submodule)).is_managed_git_subrepository() {
546 config.update_submodule(submodule);
547 }
548 }
549
550 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
552 pub fn build(&mut self) {
553 trace!("setting up job management");
554 unsafe {
555 crate::utils::job::setup(self);
556 }
557
558 trace!("downloading rustfmt early");
560 let _ = &builder::Builder::new(self).initial_rustfmt();
561
562 {
564 #[cfg(feature = "tracing")]
565 let _hardcoded_span = span!(
566 tracing::Level::DEBUG,
567 "handling hardcoded subcommands (Format, Suggest, Perf)"
568 )
569 .entered();
570
571 match &self.config.cmd {
572 Subcommand::Format { check, all } => {
573 return core::build_steps::format::format(
574 &builder::Builder::new(self),
575 *check,
576 *all,
577 &self.config.paths,
578 );
579 }
580 Subcommand::Suggest { run } => {
581 return core::build_steps::suggest::suggest(&builder::Builder::new(self), *run);
582 }
583 Subcommand::Perf(args) => {
584 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
585 }
586 _cmd => {
587 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
588 }
589 }
590
591 debug!("handling subcommand normally");
592 }
593
594 if !self.config.dry_run() {
595 #[cfg(feature = "tracing")]
596 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
597
598 {
601 #[cfg(feature = "tracing")]
602 let _sanity_check_span =
603 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
604 self.config.dry_run = DryRun::SelfCheck;
605 let builder = builder::Builder::new(self);
606 builder.execute_cli();
607 }
608
609 {
611 #[cfg(feature = "tracing")]
612 let _actual_run_span =
613 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
614 self.config.dry_run = DryRun::Disabled;
615 let builder = builder::Builder::new(self);
616 builder.execute_cli();
617 }
618 } else {
619 #[cfg(feature = "tracing")]
620 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
621
622 let builder = builder::Builder::new(self);
623 builder.execute_cli();
624 }
625
626 #[cfg(feature = "tracing")]
627 debug!("checking for postponed test failures from `test --no-fail-fast`");
628
629 let failures = self.delayed_failures.borrow();
631 if failures.len() > 0 {
632 eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
633 for failure in failures.iter() {
634 eprintln!(" - {failure}\n");
635 }
636 exit!(1);
637 }
638
639 #[cfg(feature = "build-metrics")]
640 self.metrics.persist(self);
641 }
642
643 fn rust_info(&self) -> &GitInfo {
644 &self.config.rust_info
645 }
646
647 fn std_features(&self, target: TargetSelection) -> String {
650 let mut features: BTreeSet<&str> =
651 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
652
653 match self.config.llvm_libunwind(target) {
654 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
655 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
656 LlvmLibunwind::No => false,
657 };
658
659 if self.config.backtrace {
660 features.insert("backtrace");
661 }
662
663 if self.config.profiler_enabled(target) {
664 features.insert("profiler");
665 }
666
667 if target.contains("zkvm") {
669 features.insert("compiler-builtins-mem");
670 }
671
672 features.into_iter().collect::<Vec<_>>().join(" ")
673 }
674
675 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
677 let possible_features_by_crates: HashSet<_> = crates
678 .iter()
679 .flat_map(|krate| &self.crates[krate].features)
680 .map(std::ops::Deref::deref)
681 .collect();
682 let check = |feature: &str| -> bool {
683 crates.is_empty() || possible_features_by_crates.contains(feature)
684 };
685 let mut features = vec![];
686 if self.config.jemalloc && check("jemalloc") {
687 features.push("jemalloc");
688 }
689 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
690 features.push("llvm");
691 }
692 if self.config.rust_randomize_layout {
694 features.push("rustc_randomized_layouts");
695 }
696
697 if !self.config.rust_debug_logging && check("max_level_info") {
703 features.push("max_level_info");
704 }
705
706 features.join(" ")
707 }
708
709 fn cargo_dir(&self) -> &'static str {
712 if self.config.rust_optimize.is_release() { "release" } else { "debug" }
713 }
714
715 fn tools_dir(&self, compiler: Compiler) -> PathBuf {
716 let out = self.out.join(compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
717 t!(fs::create_dir_all(&out));
718 out
719 }
720
721 fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
726 let suffix = match mode {
727 Mode::Std => "-std",
728 Mode::Rustc => "-rustc",
729 Mode::Codegen => "-codegen",
730 Mode::ToolBootstrap => "-bootstrap-tools",
731 Mode::ToolStd | Mode::ToolRustc => "-tools",
732 };
733 self.out.join(compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
734 }
735
736 fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
740 self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
741 }
742
743 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
748 if self.config.llvm_from_ci && self.is_builder_target(&target) {
749 self.config.ci_llvm_root()
750 } else {
751 self.out.join(target).join("llvm")
752 }
753 }
754
755 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
756 self.out.join(&*target.triple).join("enzyme")
757 }
758
759 fn gcc_out(&self, target: TargetSelection) -> PathBuf {
760 self.out.join(&*target.triple).join("gcc")
761 }
762
763 fn lld_out(&self, target: TargetSelection) -> PathBuf {
764 self.out.join(target).join("lld")
765 }
766
767 fn doc_out(&self, target: TargetSelection) -> PathBuf {
769 self.out.join(target).join("doc")
770 }
771
772 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
774 self.out.join(target).join("json-doc")
775 }
776
777 fn test_out(&self, target: TargetSelection) -> PathBuf {
778 self.out.join(target).join("test")
779 }
780
781 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
783 self.out.join(target).join("compiler-doc")
784 }
785
786 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
788 self.out.join(target).join("md-doc")
789 }
790
791 fn vendored_crates_path(&self) -> Option<PathBuf> {
793 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
794 }
795
796 fn is_system_llvm(&self, target: TargetSelection) -> bool {
801 match self.config.target_config.get(&target) {
802 Some(Target { llvm_config: Some(_), .. }) => {
803 let ci_llvm = self.config.llvm_from_ci && self.is_builder_target(&target);
804 !ci_llvm
805 }
806 Some(Target { llvm_config: None, .. }) => false,
808 None => false,
809 }
810 }
811
812 fn is_rust_llvm(&self, target: TargetSelection) -> bool {
816 match self.config.target_config.get(&target) {
817 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
821 _ => !self.is_system_llvm(target),
824 }
825 }
826
827 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
829 let target_config = self.config.target_config.get(&target);
830 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
831 s.to_path_buf()
832 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
833 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
834 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
835 if filecheck.exists() {
836 filecheck
837 } else {
838 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
841 let lib_filecheck =
842 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
843 if lib_filecheck.exists() {
844 lib_filecheck
845 } else {
846 filecheck
850 }
851 }
852 } else {
853 let base = self.llvm_out(target).join("build");
854 let base = if !self.ninja() && target.is_msvc() {
855 if self.config.llvm_optimize {
856 if self.config.llvm_release_debuginfo {
857 base.join("RelWithDebInfo")
858 } else {
859 base.join("Release")
860 }
861 } else {
862 base.join("Debug")
863 }
864 } else {
865 base
866 };
867 base.join("bin").join(exe("FileCheck", target))
868 }
869 }
870
871 fn native_dir(&self, target: TargetSelection) -> PathBuf {
873 self.out.join(target).join("native")
874 }
875
876 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
879 self.native_dir(target).join("rust-test-helpers")
880 }
881
882 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
884 if env::var_os("RUST_TEST_THREADS").is_none() {
885 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
886 }
887 }
888
889 fn rustc_snapshot_libdir(&self) -> PathBuf {
891 self.rustc_snapshot_sysroot().join(libdir(self.config.build))
892 }
893
894 fn rustc_snapshot_sysroot(&self) -> &Path {
896 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
897 SYSROOT_CACHE.get_or_init(|| {
898 let mut rustc = Command::new(&self.initial_rustc);
899 rustc.args(["--print", "sysroot"]);
900 output(&mut rustc).trim().into()
901 })
902 }
903
904 #[track_caller]
908 fn run(
909 &self,
910 command: &mut BootstrapCommand,
911 stdout: OutputMode,
912 stderr: OutputMode,
913 ) -> CommandOutput {
914 command.mark_as_executed();
915 if self.config.dry_run() && !command.run_always {
916 return CommandOutput::default();
917 }
918
919 #[cfg(feature = "tracing")]
920 let _run_span = trace_cmd!(command);
921
922 let created_at = command.get_created_location();
923 let executed_at = std::panic::Location::caller();
924
925 self.verbose(|| {
926 println!("running: {command:?} (created at {created_at}, executed at {executed_at})")
927 });
928
929 let cmd = command.as_command_mut();
930 cmd.stdout(stdout.stdio());
931 cmd.stderr(stderr.stdio());
932
933 let output = cmd.output();
934
935 use std::fmt::Write;
936
937 let mut message = String::new();
938 let output: CommandOutput = match output {
939 Ok(output) if output.status.success() => {
941 CommandOutput::from_output(output, stdout, stderr)
942 }
943 Ok(output) => {
945 writeln!(
946 message,
947 r#"
948Command {command:?} did not execute successfully.
949Expected success, got {}
950Created at: {created_at}
951Executed at: {executed_at}"#,
952 output.status,
953 )
954 .unwrap();
955
956 let output: CommandOutput = CommandOutput::from_output(output, stdout, stderr);
957
958 if stdout.captures() {
962 writeln!(message, "\nSTDOUT ----\n{}", output.stdout().trim()).unwrap();
963 }
964 if stderr.captures() {
965 writeln!(message, "\nSTDERR ----\n{}", output.stderr().trim()).unwrap();
966 }
967 output
968 }
969 Err(e) => {
971 writeln!(
972 message,
973 "\n\nCommand {command:?} did not execute successfully.\
974 \nIt was not possible to execute the command: {e:?}"
975 )
976 .unwrap();
977 CommandOutput::did_not_start(stdout, stderr)
978 }
979 };
980
981 let fail = |message: &str, output: CommandOutput| -> ! {
982 if self.is_verbose() {
983 println!("{message}");
984 } else {
985 let (stdout, stderr) = (output.stdout_if_present(), output.stderr_if_present());
986 if stdout.is_some() || stderr.is_some() {
990 if let Some(stdout) =
991 output.stdout_if_present().take_if(|s| !s.trim().is_empty())
992 {
993 println!("STDOUT:\n{stdout}\n");
994 }
995 if let Some(stderr) =
996 output.stderr_if_present().take_if(|s| !s.trim().is_empty())
997 {
998 println!("STDERR:\n{stderr}\n");
999 }
1000 println!("Command {command:?} has failed. Rerun with -v to see more details.");
1001 } else {
1002 println!("Command has failed. Rerun with -v to see more details.");
1003 }
1004 }
1005 exit!(1);
1006 };
1007
1008 if !output.is_success() {
1009 match command.failure_behavior {
1010 BehaviorOnFailure::DelayFail => {
1011 if self.fail_fast {
1012 fail(&message, output);
1013 }
1014
1015 let mut failures = self.delayed_failures.borrow_mut();
1016 failures.push(message);
1017 }
1018 BehaviorOnFailure::Exit => {
1019 fail(&message, output);
1020 }
1021 BehaviorOnFailure::Ignore => {
1022 }
1026 }
1027 }
1028 output
1029 }
1030
1031 pub fn is_verbose_than(&self, level: usize) -> bool {
1033 self.verbosity > level
1034 }
1035
1036 fn verbose_than(&self, level: usize, f: impl Fn()) {
1038 if self.is_verbose_than(level) {
1039 f()
1040 }
1041 }
1042
1043 fn info(&self, msg: &str) {
1044 match self.config.dry_run {
1045 DryRun::SelfCheck => (),
1046 DryRun::Disabled | DryRun::UserSelected => {
1047 println!("{msg}");
1048 }
1049 }
1050 }
1051
1052 #[must_use = "Groups should not be dropped until the Step finishes running"]
1053 #[track_caller]
1054 fn msg_clippy(
1055 &self,
1056 what: impl Display,
1057 target: impl Into<Option<TargetSelection>>,
1058 ) -> Option<gha::Group> {
1059 self.msg(Kind::Clippy, self.config.stage, what, self.config.build, target)
1060 }
1061
1062 #[must_use = "Groups should not be dropped until the Step finishes running"]
1063 #[track_caller]
1064 fn msg_check(
1065 &self,
1066 what: impl Display,
1067 target: impl Into<Option<TargetSelection>>,
1068 ) -> Option<gha::Group> {
1069 self.msg(Kind::Check, self.config.stage, what, self.config.build, target)
1070 }
1071
1072 #[must_use = "Groups should not be dropped until the Step finishes running"]
1073 #[track_caller]
1074 fn msg_doc(
1075 &self,
1076 compiler: Compiler,
1077 what: impl Display,
1078 target: impl Into<Option<TargetSelection>> + Copy,
1079 ) -> Option<gha::Group> {
1080 self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into())
1081 }
1082
1083 #[must_use = "Groups should not be dropped until the Step finishes running"]
1084 #[track_caller]
1085 fn msg_build(
1086 &self,
1087 compiler: Compiler,
1088 what: impl Display,
1089 target: impl Into<Option<TargetSelection>>,
1090 ) -> Option<gha::Group> {
1091 self.msg(Kind::Build, compiler.stage, what, compiler.host, target)
1092 }
1093
1094 #[must_use = "Groups should not be dropped until the Step finishes running"]
1098 #[track_caller]
1099 fn msg(
1100 &self,
1101 action: impl Into<Kind>,
1102 stage: u32,
1103 what: impl Display,
1104 host: impl Into<Option<TargetSelection>>,
1105 target: impl Into<Option<TargetSelection>>,
1106 ) -> Option<gha::Group> {
1107 let action = action.into().description();
1108 let msg = |fmt| format!("{action} stage{stage} {what}{fmt}");
1109 let msg = if let Some(target) = target.into() {
1110 let host = host.into().unwrap();
1111 if host == target {
1112 msg(format_args!(" ({target})"))
1113 } else {
1114 msg(format_args!(" ({host} -> {target})"))
1115 }
1116 } else {
1117 msg(format_args!(""))
1118 };
1119 self.group(&msg)
1120 }
1121
1122 #[must_use = "Groups should not be dropped until the Step finishes running"]
1126 #[track_caller]
1127 fn msg_unstaged(
1128 &self,
1129 action: impl Into<Kind>,
1130 what: impl Display,
1131 target: TargetSelection,
1132 ) -> Option<gha::Group> {
1133 let action = action.into().description();
1134 let msg = format!("{action} {what} for {target}");
1135 self.group(&msg)
1136 }
1137
1138 #[must_use = "Groups should not be dropped until the Step finishes running"]
1139 #[track_caller]
1140 fn msg_sysroot_tool(
1141 &self,
1142 action: impl Into<Kind>,
1143 stage: u32,
1144 what: impl Display,
1145 host: TargetSelection,
1146 target: TargetSelection,
1147 ) -> Option<gha::Group> {
1148 let action = action.into().description();
1149 let msg = |fmt| format!("{action} {what} {fmt}");
1150 let msg = if host == target {
1151 msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1))
1152 } else {
1153 msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1))
1154 };
1155 self.group(&msg)
1156 }
1157
1158 #[track_caller]
1159 fn group(&self, msg: &str) -> Option<gha::Group> {
1160 match self.config.dry_run {
1161 DryRun::SelfCheck => None,
1162 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1163 }
1164 }
1165
1166 fn jobs(&self) -> u32 {
1169 self.config.jobs.unwrap_or_else(|| {
1170 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1171 })
1172 }
1173
1174 fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
1175 if !self.config.rust_remap_debuginfo {
1176 return None;
1177 }
1178
1179 match which {
1180 GitRepo::Rustc => {
1181 let sha = self.rust_sha().unwrap_or(&self.version);
1182 Some(format!("/rustc/{sha}"))
1183 }
1184 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1185 }
1186 }
1187
1188 fn cc(&self, target: TargetSelection) -> PathBuf {
1190 if self.config.dry_run() {
1191 return PathBuf::new();
1192 }
1193 self.cc.borrow()[&target].path().into()
1194 }
1195
1196 fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1199 if self.config.dry_run() {
1200 return Vec::new();
1201 }
1202 let base = match c {
1203 CLang::C => self.cc.borrow()[&target].clone(),
1204 CLang::Cxx => self.cxx.borrow()[&target].clone(),
1205 };
1206
1207 base.args()
1210 .iter()
1211 .map(|s| s.to_string_lossy().into_owned())
1212 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1213 .collect::<Vec<String>>()
1214 }
1215
1216 fn cc_unhandled_cflags(
1218 &self,
1219 target: TargetSelection,
1220 which: GitRepo,
1221 c: CLang,
1222 ) -> Vec<String> {
1223 let mut base = Vec::new();
1224
1225 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1229 base.push("-stdlib=libc++".into());
1230 }
1231
1232 if &*target.triple == "i686-pc-windows-gnu" {
1236 base.push("-fno-omit-frame-pointer".into());
1237 }
1238
1239 if let Some(map_to) = self.debuginfo_map_to(which) {
1240 let map = format!("{}={}", self.src.display(), map_to);
1241 let cc = self.cc(target);
1242 if cc.ends_with("clang") || cc.ends_with("gcc") {
1243 base.push(format!("-fdebug-prefix-map={map}"));
1244 } else if cc.ends_with("clang-cl.exe") {
1245 base.push("-Xclang".into());
1246 base.push(format!("-fdebug-prefix-map={map}"));
1247 }
1248 }
1249 base
1250 }
1251
1252 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1254 if self.config.dry_run() {
1255 return None;
1256 }
1257 self.ar.borrow().get(&target).cloned()
1258 }
1259
1260 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1262 if self.config.dry_run() {
1263 return None;
1264 }
1265 self.ranlib.borrow().get(&target).cloned()
1266 }
1267
1268 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1270 if self.config.dry_run() {
1271 return Ok(PathBuf::new());
1272 }
1273 match self.cxx.borrow().get(&target) {
1274 Some(p) => Ok(p.path().into()),
1275 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1276 }
1277 }
1278
1279 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1281 if self.config.dry_run() {
1282 return Some(PathBuf::new());
1283 }
1284 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1285 {
1286 Some(linker)
1287 } else if target.contains("vxworks") {
1288 Some(self.cxx.borrow()[&target].path().into())
1291 } else if !self.is_builder_target(&target)
1292 && helpers::use_host_linker(target)
1293 && !target.is_msvc()
1294 {
1295 Some(self.cc(target))
1296 } else if self.config.lld_mode.is_used()
1297 && self.is_lld_direct_linker(target)
1298 && self.build == target
1299 {
1300 match self.config.lld_mode {
1301 LldMode::SelfContained => Some(self.initial_lld.clone()),
1302 LldMode::External => Some("lld".into()),
1303 LldMode::Unused => None,
1304 }
1305 } else {
1306 None
1307 }
1308 }
1309
1310 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1313 target.is_msvc()
1314 }
1315
1316 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1318 if target.contains("pc-windows-msvc") {
1319 Some(true)
1320 } else {
1321 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1322 }
1323 }
1324
1325 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1327 self.config
1328 .target_config
1329 .get(&target)
1330 .and_then(|t| t.musl_root.as_ref())
1331 .or(self.config.musl_root.as_ref())
1332 .map(|p| &**p)
1333 }
1334
1335 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1337 let t = self.config.target_config.get(&target)?;
1338 if let libdir @ Some(_) = &t.musl_libdir {
1339 return libdir.clone();
1340 }
1341 self.musl_root(target).map(|root| root.join("lib"))
1342 }
1343
1344 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1351 let configured =
1352 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1353 if let Some(path) = configured {
1354 return Some(path.join("lib").join(target.to_string()));
1355 }
1356 let mut env_root = PathBuf::from(std::env::var_os("WASI_SDK_PATH")?);
1357 env_root.push("share");
1358 env_root.push("wasi-sysroot");
1359 env_root.push("lib");
1360 env_root.push(target.to_string());
1361 Some(env_root)
1362 }
1363
1364 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1366 self.config.target_config.get(&target).map(|t| t.no_std)
1367 }
1368
1369 fn remote_tested(&self, target: TargetSelection) -> bool {
1372 self.qemu_rootfs(target).is_some()
1373 || target.contains("android")
1374 || env::var_os("TEST_DEVICE_ADDR").is_some()
1375 }
1376
1377 fn runner(&self, target: TargetSelection) -> Option<String> {
1383 let configured_runner =
1384 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1385 if let Some(runner) = configured_runner {
1386 return Some(runner.to_owned());
1387 }
1388
1389 if target.starts_with("wasm") && target.contains("wasi") {
1390 self.default_wasi_runner(target)
1391 } else {
1392 None
1393 }
1394 }
1395
1396 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1400 let mut finder = crate::core::sanity::Finder::new();
1401
1402 if let Some(path) = finder.maybe_have("wasmtime") {
1406 if let Ok(mut path) = path.into_os_string().into_string() {
1407 path.push_str(" run -C cache=n --dir .");
1408 path.push_str(" --env RUSTC_BOOTSTRAP");
1415
1416 if target.contains("wasip2") {
1417 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1418 }
1419
1420 return Some(path);
1421 }
1422 }
1423
1424 None
1425 }
1426
1427 fn tool_enabled(&self, tool: &str) -> bool {
1432 if !self.config.extended {
1433 return false;
1434 }
1435 match &self.config.tools {
1436 Some(set) => set.contains(tool),
1437 None => true,
1438 }
1439 }
1440
1441 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1447 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1448 }
1449
1450 fn python(&self) -> &Path {
1452 if self.config.build.ends_with("apple-darwin") {
1453 Path::new("/usr/bin/python3")
1457 } else {
1458 self.config
1459 .python
1460 .as_ref()
1461 .expect("python is required for running LLDB or rustdoc tests")
1462 }
1463 }
1464
1465 fn extended_error_dir(&self) -> PathBuf {
1467 self.out.join("tmp/extended-error-metadata")
1468 }
1469
1470 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1489 !self.config.full_bootstrap
1490 && !self.config.download_rustc()
1491 && stage >= 2
1492 && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1493 }
1494
1495 fn force_use_stage2(&self, stage: u32) -> bool {
1501 self.config.download_rustc() && stage >= 2
1502 }
1503
1504 fn release(&self, num: &str) -> String {
1510 match &self.config.channel[..] {
1511 "stable" => num.to_string(),
1512 "beta" => {
1513 if !self.config.omit_git_hash {
1514 format!("{}-beta.{}", num, self.beta_prerelease_version())
1515 } else {
1516 format!("{num}-beta")
1517 }
1518 }
1519 "nightly" => format!("{num}-nightly"),
1520 _ => format!("{num}-dev"),
1521 }
1522 }
1523
1524 fn beta_prerelease_version(&self) -> u32 {
1525 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1526 let version = fs::read_to_string(version_file).ok()?;
1527
1528 helpers::extract_beta_rev(&version)
1529 }
1530
1531 if let Some(s) = self.prerelease_version.get() {
1532 return s;
1533 }
1534
1535 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1539 helpers::git(Some(&self.src))
1543 .arg("rev-list")
1544 .arg("--count")
1545 .arg("--merges")
1546 .arg(format!(
1547 "refs/remotes/origin/{}..HEAD",
1548 self.config.stage0_metadata.config.nightly_branch
1549 ))
1550 .run_always()
1551 .run_capture(self)
1552 .stdout()
1553 });
1554 let n = count.trim().parse().unwrap();
1555 self.prerelease_version.set(Some(n));
1556 n
1557 }
1558
1559 fn rust_release(&self) -> String {
1561 self.release(&self.version)
1562 }
1563
1564 fn package_vers(&self, num: &str) -> String {
1571 match &self.config.channel[..] {
1572 "stable" => num.to_string(),
1573 "beta" => "beta".to_string(),
1574 "nightly" => "nightly".to_string(),
1575 _ => format!("{num}-dev"),
1576 }
1577 }
1578
1579 fn rust_package_vers(&self) -> String {
1581 self.package_vers(&self.version)
1582 }
1583
1584 fn rust_version(&self) -> String {
1590 let mut version = self.rust_info().version(self, &self.version);
1591 if let Some(ref s) = self.config.description {
1592 if !s.is_empty() {
1593 version.push_str(" (");
1594 version.push_str(s);
1595 version.push(')');
1596 }
1597 }
1598 version
1599 }
1600
1601 fn rust_sha(&self) -> Option<&str> {
1603 self.rust_info().sha()
1604 }
1605
1606 fn release_num(&self, package: &str) -> String {
1608 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1609 let toml = t!(fs::read_to_string(toml_file_name));
1610 for line in toml.lines() {
1611 if let Some(stripped) =
1612 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1613 {
1614 return stripped.to_owned();
1615 }
1616 }
1617
1618 panic!("failed to find version in {package}'s Cargo.toml")
1619 }
1620
1621 fn unstable_features(&self) -> bool {
1624 !matches!(&self.config.channel[..], "stable" | "beta")
1625 }
1626
1627 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1631 let mut ret = Vec::new();
1632 let mut list = vec![root.to_owned()];
1633 let mut visited = HashSet::new();
1634 while let Some(krate) = list.pop() {
1635 let krate = self
1636 .crates
1637 .get(&krate)
1638 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1639 ret.push(krate);
1640 for dep in &krate.deps {
1641 if !self.crates.contains_key(dep) {
1642 continue;
1644 }
1645 if visited.insert(dep)
1651 && (dep != "profiler_builtins"
1652 || target
1653 .map(|t| self.config.profiler_enabled(t))
1654 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1655 && (dep != "rustc_codegen_llvm"
1656 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1657 {
1658 list.push(dep.clone());
1659 }
1660 }
1661 }
1662 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1664 }
1665
1666 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1667 if self.config.dry_run() {
1668 return Vec::new();
1669 }
1670
1671 if !stamp.path().exists() {
1672 eprintln!(
1673 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1674 stamp.path().display()
1675 );
1676 crate::exit!(1);
1677 }
1678
1679 let mut paths = Vec::new();
1680 let contents = t!(fs::read(stamp.path()), stamp.path());
1681 for part in contents.split(|b| *b == 0) {
1684 if part.is_empty() {
1685 continue;
1686 }
1687 let dependency_type = match part[0] as char {
1688 'h' => DependencyType::Host,
1689 's' => DependencyType::TargetSelfContained,
1690 't' => DependencyType::Target,
1691 _ => unreachable!(),
1692 };
1693 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1694 paths.push((path, dependency_type));
1695 }
1696 paths
1697 }
1698
1699 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1704 self.copy_link_internal(src, dst, true);
1705 }
1706
1707 pub fn copy_link(&self, src: &Path, dst: &Path) {
1712 self.copy_link_internal(src, dst, false);
1713 }
1714
1715 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1716 if self.config.dry_run() {
1717 return;
1718 }
1719 self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1720 if src == dst {
1721 return;
1722 }
1723 if let Err(e) = fs::remove_file(dst) {
1724 if cfg!(windows) && e.kind() != io::ErrorKind::NotFound {
1725 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1728 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1729 }
1730 }
1731 let metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1732 let mut src = src.to_path_buf();
1733 if metadata.file_type().is_symlink() {
1734 if dereference_symlinks {
1735 src = t!(fs::canonicalize(src));
1736 } else {
1737 let link = t!(fs::read_link(src));
1738 t!(self.symlink_file(link, dst));
1739 return;
1740 }
1741 }
1742 if let Ok(()) = fs::hard_link(&src, dst) {
1743 } else {
1746 if let Err(e) = fs::copy(&src, dst) {
1747 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1748 }
1749 t!(fs::set_permissions(dst, metadata.permissions()));
1750
1751 let file_times = fs::FileTimes::new()
1754 .set_accessed(t!(metadata.accessed()))
1755 .set_modified(t!(metadata.modified()));
1756 t!(set_file_times(dst, file_times));
1757 }
1758 }
1759
1760 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1764 if self.config.dry_run() {
1765 return;
1766 }
1767 for f in self.read_dir(src) {
1768 let path = f.path();
1769 let name = path.file_name().unwrap();
1770 let dst = dst.join(name);
1771 if t!(f.file_type()).is_dir() {
1772 t!(fs::create_dir_all(&dst));
1773 self.cp_link_r(&path, &dst);
1774 } else {
1775 self.copy_link(&path, &dst);
1776 }
1777 }
1778 }
1779
1780 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1786 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1788 }
1789
1790 fn cp_link_filtered_recurse(
1792 &self,
1793 src: &Path,
1794 dst: &Path,
1795 relative: &Path,
1796 filter: &dyn Fn(&Path) -> bool,
1797 ) {
1798 for f in self.read_dir(src) {
1799 let path = f.path();
1800 let name = path.file_name().unwrap();
1801 let dst = dst.join(name);
1802 let relative = relative.join(name);
1803 if filter(&relative) {
1805 if t!(f.file_type()).is_dir() {
1806 let _ = fs::remove_dir_all(&dst);
1807 self.create_dir(&dst);
1808 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1809 } else {
1810 let _ = fs::remove_file(&dst);
1811 self.copy_link(&path, &dst);
1812 }
1813 }
1814 }
1815 }
1816
1817 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1818 let file_name = src.file_name().unwrap();
1819 let dest = dest_folder.join(file_name);
1820 self.copy_link(src, &dest);
1821 }
1822
1823 fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1824 if self.config.dry_run() {
1825 return;
1826 }
1827 let dst = dstdir.join(src.file_name().unwrap());
1828 self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1829 t!(fs::create_dir_all(dstdir));
1830 if !src.exists() {
1831 panic!("ERROR: File \"{}\" not found!", src.display());
1832 }
1833 self.copy_link_internal(src, &dst, true);
1834 chmod(&dst, perms);
1835 }
1836
1837 fn read(&self, path: &Path) -> String {
1838 if self.config.dry_run() {
1839 return String::new();
1840 }
1841 t!(fs::read_to_string(path))
1842 }
1843
1844 fn create_dir(&self, dir: &Path) {
1845 if self.config.dry_run() {
1846 return;
1847 }
1848 t!(fs::create_dir_all(dir))
1849 }
1850
1851 fn remove_dir(&self, dir: &Path) {
1852 if self.config.dry_run() {
1853 return;
1854 }
1855 t!(fs::remove_dir_all(dir))
1856 }
1857
1858 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1859 let iter = match fs::read_dir(dir) {
1860 Ok(v) => v,
1861 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1862 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1863 };
1864 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1865 }
1866
1867 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1868 #[cfg(unix)]
1869 use std::os::unix::fs::symlink as symlink_file;
1870 #[cfg(windows)]
1871 use std::os::windows::fs::symlink_file;
1872 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1873 }
1874
1875 fn ninja(&self) -> bool {
1878 let mut cmd_finder = crate::core::sanity::Finder::new();
1879
1880 if self.config.ninja_in_file {
1881 if cmd_finder.maybe_have("ninja-build").is_none()
1884 && cmd_finder.maybe_have("ninja").is_none()
1885 {
1886 eprintln!(
1887 "
1888Couldn't find required command: ninja (or ninja-build)
1889
1890You should install ninja as described at
1891<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1892or set `ninja = false` in the `[llvm]` section of `config.toml`.
1893Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1894to download LLVM rather than building it.
1895"
1896 );
1897 exit!(1);
1898 }
1899 }
1900
1901 if !self.config.ninja_in_file
1909 && self.config.build.is_msvc()
1910 && cmd_finder.maybe_have("ninja").is_some()
1911 {
1912 return true;
1913 }
1914
1915 self.config.ninja_in_file
1916 }
1917
1918 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1919 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1920 }
1921
1922 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1923 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1924 }
1925
1926 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1927 where
1928 C: Fn(ColorChoice) -> StandardStream,
1929 F: FnOnce(&mut dyn WriteColor) -> R,
1930 {
1931 let choice = match self.config.color {
1932 flags::Color::Always => ColorChoice::Always,
1933 flags::Color::Never => ColorChoice::Never,
1934 flags::Color::Auto if !is_tty => ColorChoice::Never,
1935 flags::Color::Auto => ColorChoice::Auto,
1936 };
1937 let mut stream = constructor(choice);
1938 let result = f(&mut stream);
1939 stream.reset().unwrap();
1940 result
1941 }
1942
1943 fn is_builder_target(&self, target: &TargetSelection) -> bool {
1945 &self.config.build == target
1946 }
1947}
1948
1949#[cfg(unix)]
1950fn chmod(path: &Path, perms: u32) {
1951 use std::os::unix::fs::*;
1952 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1953}
1954#[cfg(windows)]
1955fn chmod(_path: &Path, _perms: u32) {}
1956
1957impl Compiler {
1958 pub fn with_stage(mut self, stage: u32) -> Compiler {
1959 self.stage = stage;
1960 self
1961 }
1962
1963 pub fn is_snapshot(&self, build: &Build) -> bool {
1965 self.stage == 0 && self.host == build.build
1966 }
1967}
1968
1969fn envify(s: &str) -> String {
1970 s.chars()
1971 .map(|c| match c {
1972 '-' => '_',
1973 c => c,
1974 })
1975 .flat_map(|c| c.to_uppercase())
1976 .collect()
1977}
1978
1979pub fn prepare_behaviour_dump_dir(build: &Build) {
1981 static INITIALIZED: OnceLock<bool> = OnceLock::new();
1982
1983 let dump_path = build.out.join("bootstrap-shims-dump");
1984
1985 let initialized = INITIALIZED.get().unwrap_or(&false);
1986 if !initialized {
1987 if dump_path.exists() {
1989 t!(fs::remove_dir_all(&dump_path));
1990 }
1991
1992 t!(fs::create_dir_all(&dump_path));
1993
1994 t!(INITIALIZED.set(true));
1995 }
1996}