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
53const LLVM_TOOLS: &[&str] = &[
54 "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", ];
69
70const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
72
73#[allow(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
77 (None, "bootstrap", None),
78 (Some(Mode::Rustc), "llvm_enzyme", None),
79 (Some(Mode::Codegen), "llvm_enzyme", None),
80 (Some(Mode::ToolRustc), "llvm_enzyme", None),
81 (Some(Mode::ToolRustc), "rust_analyzer", None),
82 (Some(Mode::ToolStd), "rust_analyzer", None),
83 ];
87
88#[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
94pub struct Compiler {
95 stage: u32,
96 host: TargetSelection,
97}
98
99#[derive(PartialEq, Eq, Copy, Clone, Debug)]
100pub enum DocTests {
101 Yes,
103 No,
105 Only,
107}
108
109pub enum GitRepo {
110 Rustc,
111 Llvm,
112}
113
114#[derive(Clone)]
125pub struct Build {
126 config: Config,
128
129 version: String,
131
132 src: PathBuf,
134 out: PathBuf,
135 bootstrap_out: PathBuf,
136 cargo_info: GitInfo,
137 rust_analyzer_info: GitInfo,
138 clippy_info: GitInfo,
139 miri_info: GitInfo,
140 rustfmt_info: GitInfo,
141 enzyme_info: GitInfo,
142 in_tree_llvm_info: GitInfo,
143 in_tree_gcc_info: GitInfo,
144 local_rebuild: bool,
145 fail_fast: bool,
146 doc_tests: DocTests,
147 verbosity: usize,
148
149 build: TargetSelection,
151 hosts: Vec<TargetSelection>,
153 targets: Vec<TargetSelection>,
155
156 initial_rustc: PathBuf,
157 initial_rustdoc: PathBuf,
158 initial_cargo: PathBuf,
159 initial_lld: PathBuf,
160 initial_relative_libdir: PathBuf,
161 initial_sysroot: PathBuf,
162
163 cc: RefCell<HashMap<TargetSelection, cc::Tool>>,
166 cxx: RefCell<HashMap<TargetSelection, cc::Tool>>,
167 ar: RefCell<HashMap<TargetSelection, PathBuf>>,
168 ranlib: RefCell<HashMap<TargetSelection, PathBuf>>,
169 crates: HashMap<String, Crate>,
172 crate_paths: HashMap<PathBuf, String>,
173 is_sudo: bool,
174 delayed_failures: RefCell<Vec<String>>,
175 prerelease_version: Cell<Option<u32>>,
176
177 #[cfg(feature = "build-metrics")]
178 metrics: crate::utils::metrics::BuildMetrics,
179}
180
181#[derive(Debug, Clone)]
182struct Crate {
183 name: String,
184 deps: HashSet<String>,
185 path: PathBuf,
186 has_lib: bool,
187 features: Vec<String>,
188}
189
190impl Crate {
191 fn local_path(&self, build: &Build) -> PathBuf {
192 self.path.strip_prefix(&build.config.src).unwrap().into()
193 }
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
198pub enum DependencyType {
199 Host,
201 Target,
203 TargetSelfContained,
205}
206
207#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
212pub enum Mode {
213 Std,
215
216 Rustc,
218
219 Codegen,
221
222 ToolBootstrap,
229
230 ToolStd,
234
235 ToolRustc,
240}
241
242impl Mode {
243 pub fn is_tool(&self) -> bool {
244 matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
245 }
246
247 pub fn must_support_dlopen(&self) -> bool {
248 matches!(self, Mode::Std | Mode::Codegen)
249 }
250}
251
252#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
253pub enum CLang {
254 C,
255 Cxx,
256}
257
258macro_rules! forward {
259 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
260 impl Build {
261 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
262 self.config.$fn( $($param),* )
263 } )+
264 }
265 }
266}
267
268forward! {
269 verbose(f: impl Fn()),
270 is_verbose() -> bool,
271 create(path: &Path, s: &str),
272 remove(f: &Path),
273 tempdir() -> PathBuf,
274 llvm_link_shared() -> bool,
275 download_rustc() -> bool,
276 initial_rustfmt() -> Option<PathBuf>,
277}
278
279impl Build {
280 pub fn new(mut config: Config) -> Build {
285 let src = config.src.clone();
286 let out = config.out.clone();
287
288 #[cfg(unix)]
289 let is_sudo = match env::var_os("SUDO_USER") {
292 Some(_sudo_user) => {
293 let uid = unsafe { libc::getuid() };
298 uid == 0
299 }
300 None => false,
301 };
302 #[cfg(not(unix))]
303 let is_sudo = false;
304
305 let rust_info = config.rust_info.clone();
306 let cargo_info = config.cargo_info.clone();
307 let rust_analyzer_info = config.rust_analyzer_info.clone();
308 let clippy_info = config.clippy_info.clone();
309 let miri_info = config.miri_info.clone();
310 let rustfmt_info = config.rustfmt_info.clone();
311 let enzyme_info = config.enzyme_info.clone();
312 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
313 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
314
315 let initial_target_libdir_str =
316 config.initial_sysroot.join("lib/rustlib").join(config.build).join("lib");
317
318 let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
319 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
320
321 let initial_relative_libdir = initial_target_dir
322 .ancestors()
323 .nth(2)
324 .unwrap()
325 .strip_prefix(&config.initial_sysroot)
326 .expect("Couldn’t determine initial relative libdir.")
327 .to_path_buf();
328
329 let version = std::fs::read_to_string(src.join("src").join("version"))
330 .expect("failed to read src/version");
331 let version = version.trim();
332
333 let mut bootstrap_out = std::env::current_exe()
334 .expect("could not determine path to running process")
335 .parent()
336 .unwrap()
337 .to_path_buf();
338 if bootstrap_out.ends_with("deps") {
341 bootstrap_out.pop();
342 }
343 if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
344 panic!(
346 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
347 bootstrap_out.display()
348 )
349 }
350
351 if rust_info.is_from_tarball() && config.description.is_none() {
352 config.description = Some("built from a source tarball".to_owned());
353 }
354
355 let mut build = Build {
356 initial_lld,
357 initial_relative_libdir,
358 initial_rustc: config.initial_rustc.clone(),
359 initial_rustdoc: config.initial_rustc.with_file_name(exe("rustdoc", config.build)),
360 initial_cargo: config.initial_cargo.clone(),
361 initial_sysroot: config.initial_sysroot.clone(),
362 local_rebuild: config.local_rebuild,
363 fail_fast: config.cmd.fail_fast(),
364 doc_tests: config.cmd.doc_tests(),
365 verbosity: config.verbose,
366
367 build: config.build,
368 hosts: config.hosts.clone(),
369 targets: config.targets.clone(),
370
371 config,
372 version: version.to_string(),
373 src,
374 out,
375 bootstrap_out,
376
377 cargo_info,
378 rust_analyzer_info,
379 clippy_info,
380 miri_info,
381 rustfmt_info,
382 enzyme_info,
383 in_tree_llvm_info,
384 in_tree_gcc_info,
385 cc: RefCell::new(HashMap::new()),
386 cxx: RefCell::new(HashMap::new()),
387 ar: RefCell::new(HashMap::new()),
388 ranlib: RefCell::new(HashMap::new()),
389 crates: HashMap::new(),
390 crate_paths: HashMap::new(),
391 is_sudo,
392 delayed_failures: RefCell::new(Vec::new()),
393 prerelease_version: Cell::new(None),
394
395 #[cfg(feature = "build-metrics")]
396 metrics: crate::utils::metrics::BuildMetrics::init(),
397 };
398
399 let local_version_verbose =
402 output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
403 let local_release = local_version_verbose
404 .lines()
405 .filter_map(|x| x.strip_prefix("release:"))
406 .next()
407 .unwrap()
408 .trim();
409 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
410 build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
411 build.local_rebuild = true;
412 }
413
414 build.verbose(|| println!("finding compilers"));
415 utils::cc_detect::find(&build);
416 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
422 build.verbose(|| println!("running sanity check"));
423 crate::core::sanity::check(&mut build);
424
425 let rust_submodules = ["library/backtrace", "library/stdarch"];
428 for s in rust_submodules {
429 build.require_submodule(
430 s,
431 Some(
432 "The submodule is required for the standard library \
433 and the main Cargo workspace.",
434 ),
435 );
436 }
437 build.update_existing_submodules();
439
440 build.verbose(|| println!("learning about cargo"));
441 crate::core::metadata::build(&mut build);
442 }
443
444 let build_triple = build.out.join(build.build);
446 t!(fs::create_dir_all(&build_triple));
447 let host = build.out.join("host");
448 if host.is_symlink() {
449 #[cfg(windows)]
452 t!(fs::remove_dir(&host));
453 #[cfg(not(windows))]
454 t!(fs::remove_file(&host));
455 }
456 t!(
457 symlink_dir(&build.config, &build_triple, &host),
458 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
459 );
460
461 build
462 }
463
464 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
473 if cfg!(test) && !self.config.submodules() {
476 return;
477 }
478 self.config.update_submodule(submodule);
479 let absolute_path = self.config.src.join(submodule);
480 if dir_is_empty(&absolute_path) {
481 let maybe_enable = if !self.config.submodules()
482 && self.config.rust_info.is_managed_git_subrepository()
483 {
484 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
485 } else {
486 ""
487 };
488 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
489 eprintln!(
490 "submodule {submodule} does not appear to be checked out, \
491 but it is required for this step{maybe_enable}{err_hint}"
492 );
493 exit!(1);
494 }
495 }
496
497 pub fn require_and_update_all_submodules(&self) {
500 for submodule in build_helper::util::parse_gitmodules(&self.src) {
501 self.require_submodule(submodule, None);
502 }
503 }
504
505 fn update_existing_submodules(&self) {
508 if !self.config.submodules() {
511 return;
512 }
513 let output = helpers::git(Some(&self.src))
514 .args(["config", "--file"])
515 .arg(".gitmodules")
516 .args(["--get-regexp", "path"])
517 .run_capture(self)
518 .stdout();
519 std::thread::scope(|s| {
520 for line in output.lines() {
523 let submodule = line.split_once(' ').unwrap().1;
524 let config = self.config.clone();
525 s.spawn(move || {
526 Self::update_existing_submodule(&config, submodule);
527 });
528 }
529 });
530 }
531
532 pub fn update_existing_submodule(config: &Config, submodule: &str) {
534 if !config.submodules() {
536 return;
537 }
538
539 if GitInfo::new(false, Path::new(submodule)).is_managed_git_subrepository() {
540 config.update_submodule(submodule);
541 }
542 }
543
544 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
546 pub fn build(&mut self) {
547 trace!("setting up job management");
548 unsafe {
549 crate::utils::job::setup(self);
550 }
551
552 trace!("downloading rustfmt early");
554 let _ = &builder::Builder::new(self).initial_rustfmt();
555
556 {
558 #[cfg(feature = "tracing")]
559 let _hardcoded_span = span!(
560 tracing::Level::DEBUG,
561 "handling hardcoded subcommands (Format, Suggest, Perf)"
562 )
563 .entered();
564
565 match &self.config.cmd {
566 Subcommand::Format { check, all } => {
567 return core::build_steps::format::format(
568 &builder::Builder::new(self),
569 *check,
570 *all,
571 &self.config.paths,
572 );
573 }
574 Subcommand::Suggest { run } => {
575 return core::build_steps::suggest::suggest(&builder::Builder::new(self), *run);
576 }
577 Subcommand::Perf(args) => {
578 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
579 }
580 _cmd => {
581 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
582 }
583 }
584
585 debug!("handling subcommand normally");
586 }
587
588 if !self.config.dry_run() {
589 #[cfg(feature = "tracing")]
590 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
591
592 {
595 #[cfg(feature = "tracing")]
596 let _sanity_check_span =
597 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
598 self.config.dry_run = DryRun::SelfCheck;
599 let builder = builder::Builder::new(self);
600 builder.execute_cli();
601 }
602
603 {
605 #[cfg(feature = "tracing")]
606 let _actual_run_span =
607 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
608 self.config.dry_run = DryRun::Disabled;
609 let builder = builder::Builder::new(self);
610 builder.execute_cli();
611 }
612 } else {
613 #[cfg(feature = "tracing")]
614 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
615
616 let builder = builder::Builder::new(self);
617 builder.execute_cli();
618 }
619
620 #[cfg(feature = "tracing")]
621 debug!("checking for postponed test failures from `test --no-fail-fast`");
622
623 let failures = self.delayed_failures.borrow();
625 if failures.len() > 0 {
626 eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
627 for failure in failures.iter() {
628 eprintln!(" - {failure}\n");
629 }
630 exit!(1);
631 }
632
633 #[cfg(feature = "build-metrics")]
634 self.metrics.persist(self);
635 }
636
637 fn rust_info(&self) -> &GitInfo {
638 &self.config.rust_info
639 }
640
641 fn std_features(&self, target: TargetSelection) -> String {
644 let mut features: BTreeSet<&str> =
645 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
646
647 match self.config.llvm_libunwind(target) {
648 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
649 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
650 LlvmLibunwind::No => false,
651 };
652
653 if self.config.backtrace {
654 features.insert("backtrace");
655 }
656
657 if self.config.profiler_enabled(target) {
658 features.insert("profiler");
659 }
660
661 if target.contains("zkvm") {
663 features.insert("compiler-builtins-mem");
664 }
665
666 features.into_iter().collect::<Vec<_>>().join(" ")
667 }
668
669 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
671 let possible_features_by_crates: HashSet<_> = crates
672 .iter()
673 .flat_map(|krate| &self.crates[krate].features)
674 .map(std::ops::Deref::deref)
675 .collect();
676 let check = |feature: &str| -> bool {
677 crates.is_empty() || possible_features_by_crates.contains(feature)
678 };
679 let mut features = vec![];
680 if self.config.jemalloc && check("jemalloc") {
681 features.push("jemalloc");
682 }
683 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
684 features.push("llvm");
685 }
686 if self.config.rust_randomize_layout {
688 features.push("rustc_randomized_layouts");
689 }
690
691 if !self.config.rust_debug_logging && check("max_level_info") {
697 features.push("max_level_info");
698 }
699
700 features.join(" ")
701 }
702
703 fn cargo_dir(&self) -> &'static str {
706 if self.config.rust_optimize.is_release() { "release" } else { "debug" }
707 }
708
709 fn tools_dir(&self, compiler: Compiler) -> PathBuf {
710 let out = self.out.join(compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
711 t!(fs::create_dir_all(&out));
712 out
713 }
714
715 fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
720 let suffix = match mode {
721 Mode::Std => "-std",
722 Mode::Rustc => "-rustc",
723 Mode::Codegen => "-codegen",
724 Mode::ToolBootstrap => "-bootstrap-tools",
725 Mode::ToolStd | Mode::ToolRustc => "-tools",
726 };
727 self.out.join(compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
728 }
729
730 fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
734 self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
735 }
736
737 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
742 if self.config.llvm_from_ci && self.is_builder_target(&target) {
743 self.config.ci_llvm_root()
744 } else {
745 self.out.join(target).join("llvm")
746 }
747 }
748
749 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
750 self.out.join(&*target.triple).join("enzyme")
751 }
752
753 fn gcc_out(&self, target: TargetSelection) -> PathBuf {
754 self.out.join(&*target.triple).join("gcc")
755 }
756
757 fn lld_out(&self, target: TargetSelection) -> PathBuf {
758 self.out.join(target).join("lld")
759 }
760
761 fn doc_out(&self, target: TargetSelection) -> PathBuf {
763 self.out.join(target).join("doc")
764 }
765
766 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
768 self.out.join(target).join("json-doc")
769 }
770
771 fn test_out(&self, target: TargetSelection) -> PathBuf {
772 self.out.join(target).join("test")
773 }
774
775 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
777 self.out.join(target).join("compiler-doc")
778 }
779
780 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
782 self.out.join(target).join("md-doc")
783 }
784
785 fn is_system_llvm(&self, target: TargetSelection) -> bool {
790 match self.config.target_config.get(&target) {
791 Some(Target { llvm_config: Some(_), .. }) => {
792 let ci_llvm = self.config.llvm_from_ci && self.is_builder_target(&target);
793 !ci_llvm
794 }
795 Some(Target { llvm_config: None, .. }) => false,
797 None => false,
798 }
799 }
800
801 fn is_rust_llvm(&self, target: TargetSelection) -> bool {
805 match self.config.target_config.get(&target) {
806 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
810 _ => !self.is_system_llvm(target),
813 }
814 }
815
816 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
818 let target_config = self.config.target_config.get(&target);
819 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
820 s.to_path_buf()
821 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
822 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
823 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
824 if filecheck.exists() {
825 filecheck
826 } else {
827 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
830 let lib_filecheck =
831 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
832 if lib_filecheck.exists() {
833 lib_filecheck
834 } else {
835 filecheck
839 }
840 }
841 } else {
842 let base = self.llvm_out(target).join("build");
843 let base = if !self.ninja() && target.is_msvc() {
844 if self.config.llvm_optimize {
845 if self.config.llvm_release_debuginfo {
846 base.join("RelWithDebInfo")
847 } else {
848 base.join("Release")
849 }
850 } else {
851 base.join("Debug")
852 }
853 } else {
854 base
855 };
856 base.join("bin").join(exe("FileCheck", target))
857 }
858 }
859
860 fn native_dir(&self, target: TargetSelection) -> PathBuf {
862 self.out.join(target).join("native")
863 }
864
865 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
868 self.native_dir(target).join("rust-test-helpers")
869 }
870
871 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
873 if env::var_os("RUST_TEST_THREADS").is_none() {
874 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
875 }
876 }
877
878 fn rustc_snapshot_libdir(&self) -> PathBuf {
880 self.rustc_snapshot_sysroot().join(libdir(self.config.build))
881 }
882
883 fn rustc_snapshot_sysroot(&self) -> &Path {
885 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
886 SYSROOT_CACHE.get_or_init(|| {
887 let mut rustc = Command::new(&self.initial_rustc);
888 rustc.args(["--print", "sysroot"]);
889 output(&mut rustc).trim().into()
890 })
891 }
892
893 #[track_caller]
897 fn run(
898 &self,
899 command: &mut BootstrapCommand,
900 stdout: OutputMode,
901 stderr: OutputMode,
902 ) -> CommandOutput {
903 command.mark_as_executed();
904 if self.config.dry_run() && !command.run_always {
905 return CommandOutput::default();
906 }
907
908 #[cfg(feature = "tracing")]
909 let _run_span = trace_cmd!(command);
910
911 let created_at = command.get_created_location();
912 let executed_at = std::panic::Location::caller();
913
914 self.verbose(|| {
915 println!("running: {command:?} (created at {created_at}, executed at {executed_at})")
916 });
917
918 let cmd = command.as_command_mut();
919 cmd.stdout(stdout.stdio());
920 cmd.stderr(stderr.stdio());
921
922 let output = cmd.output();
923
924 use std::fmt::Write;
925
926 let mut message = String::new();
927 let output: CommandOutput = match output {
928 Ok(output) if output.status.success() => {
930 CommandOutput::from_output(output, stdout, stderr)
931 }
932 Ok(output) => {
934 writeln!(
935 message,
936 r#"
937Command {command:?} did not execute successfully.
938Expected success, got {}
939Created at: {created_at}
940Executed at: {executed_at}"#,
941 output.status,
942 )
943 .unwrap();
944
945 let output: CommandOutput = CommandOutput::from_output(output, stdout, stderr);
946
947 if stdout.captures() {
951 writeln!(message, "\nSTDOUT ----\n{}", output.stdout().trim()).unwrap();
952 }
953 if stderr.captures() {
954 writeln!(message, "\nSTDERR ----\n{}", output.stderr().trim()).unwrap();
955 }
956 output
957 }
958 Err(e) => {
960 writeln!(
961 message,
962 "\n\nCommand {command:?} did not execute successfully.\
963 \nIt was not possible to execute the command: {e:?}"
964 )
965 .unwrap();
966 CommandOutput::did_not_start(stdout, stderr)
967 }
968 };
969
970 let fail = |message: &str, output: CommandOutput| -> ! {
971 if self.is_verbose() {
972 println!("{message}");
973 } else {
974 let (stdout, stderr) = (output.stdout_if_present(), output.stderr_if_present());
975 if stdout.is_some() || stderr.is_some() {
979 if let Some(stdout) =
980 output.stdout_if_present().take_if(|s| !s.trim().is_empty())
981 {
982 println!("STDOUT:\n{stdout}\n");
983 }
984 if let Some(stderr) =
985 output.stderr_if_present().take_if(|s| !s.trim().is_empty())
986 {
987 println!("STDERR:\n{stderr}\n");
988 }
989 println!("Command {command:?} has failed. Rerun with -v to see more details.");
990 } else {
991 println!("Command has failed. Rerun with -v to see more details.");
992 }
993 }
994 exit!(1);
995 };
996
997 if !output.is_success() {
998 match command.failure_behavior {
999 BehaviorOnFailure::DelayFail => {
1000 if self.fail_fast {
1001 fail(&message, output);
1002 }
1003
1004 let mut failures = self.delayed_failures.borrow_mut();
1005 failures.push(message);
1006 }
1007 BehaviorOnFailure::Exit => {
1008 fail(&message, output);
1009 }
1010 BehaviorOnFailure::Ignore => {
1011 }
1015 }
1016 }
1017 output
1018 }
1019
1020 pub fn is_verbose_than(&self, level: usize) -> bool {
1022 self.verbosity > level
1023 }
1024
1025 fn verbose_than(&self, level: usize, f: impl Fn()) {
1027 if self.is_verbose_than(level) {
1028 f()
1029 }
1030 }
1031
1032 fn info(&self, msg: &str) {
1033 match self.config.dry_run {
1034 DryRun::SelfCheck => (),
1035 DryRun::Disabled | DryRun::UserSelected => {
1036 println!("{msg}");
1037 }
1038 }
1039 }
1040
1041 #[must_use = "Groups should not be dropped until the Step finishes running"]
1042 #[track_caller]
1043 fn msg_clippy(
1044 &self,
1045 what: impl Display,
1046 target: impl Into<Option<TargetSelection>>,
1047 ) -> Option<gha::Group> {
1048 self.msg(Kind::Clippy, self.config.stage, what, self.config.build, target)
1049 }
1050
1051 #[must_use = "Groups should not be dropped until the Step finishes running"]
1052 #[track_caller]
1053 fn msg_check(
1054 &self,
1055 what: impl Display,
1056 target: impl Into<Option<TargetSelection>>,
1057 ) -> Option<gha::Group> {
1058 self.msg(Kind::Check, self.config.stage, what, self.config.build, target)
1059 }
1060
1061 #[must_use = "Groups should not be dropped until the Step finishes running"]
1062 #[track_caller]
1063 fn msg_doc(
1064 &self,
1065 compiler: Compiler,
1066 what: impl Display,
1067 target: impl Into<Option<TargetSelection>> + Copy,
1068 ) -> Option<gha::Group> {
1069 self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into())
1070 }
1071
1072 #[must_use = "Groups should not be dropped until the Step finishes running"]
1073 #[track_caller]
1074 fn msg_build(
1075 &self,
1076 compiler: Compiler,
1077 what: impl Display,
1078 target: impl Into<Option<TargetSelection>>,
1079 ) -> Option<gha::Group> {
1080 self.msg(Kind::Build, compiler.stage, what, compiler.host, target)
1081 }
1082
1083 #[must_use = "Groups should not be dropped until the Step finishes running"]
1087 #[track_caller]
1088 fn msg(
1089 &self,
1090 action: impl Into<Kind>,
1091 stage: u32,
1092 what: impl Display,
1093 host: impl Into<Option<TargetSelection>>,
1094 target: impl Into<Option<TargetSelection>>,
1095 ) -> Option<gha::Group> {
1096 let action = action.into().description();
1097 let msg = |fmt| format!("{action} stage{stage} {what}{fmt}");
1098 let msg = if let Some(target) = target.into() {
1099 let host = host.into().unwrap();
1100 if host == target {
1101 msg(format_args!(" ({target})"))
1102 } else {
1103 msg(format_args!(" ({host} -> {target})"))
1104 }
1105 } else {
1106 msg(format_args!(""))
1107 };
1108 self.group(&msg)
1109 }
1110
1111 #[must_use = "Groups should not be dropped until the Step finishes running"]
1115 #[track_caller]
1116 fn msg_unstaged(
1117 &self,
1118 action: impl Into<Kind>,
1119 what: impl Display,
1120 target: TargetSelection,
1121 ) -> Option<gha::Group> {
1122 let action = action.into().description();
1123 let msg = format!("{action} {what} for {target}");
1124 self.group(&msg)
1125 }
1126
1127 #[must_use = "Groups should not be dropped until the Step finishes running"]
1128 #[track_caller]
1129 fn msg_sysroot_tool(
1130 &self,
1131 action: impl Into<Kind>,
1132 stage: u32,
1133 what: impl Display,
1134 host: TargetSelection,
1135 target: TargetSelection,
1136 ) -> Option<gha::Group> {
1137 let action = action.into().description();
1138 let msg = |fmt| format!("{action} {what} {fmt}");
1139 let msg = if host == target {
1140 msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1))
1141 } else {
1142 msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1))
1143 };
1144 self.group(&msg)
1145 }
1146
1147 #[track_caller]
1148 fn group(&self, msg: &str) -> Option<gha::Group> {
1149 match self.config.dry_run {
1150 DryRun::SelfCheck => None,
1151 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1152 }
1153 }
1154
1155 fn jobs(&self) -> u32 {
1158 self.config.jobs.unwrap_or_else(|| {
1159 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1160 })
1161 }
1162
1163 fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
1164 if !self.config.rust_remap_debuginfo {
1165 return None;
1166 }
1167
1168 match which {
1169 GitRepo::Rustc => {
1170 let sha = self.rust_sha().unwrap_or(&self.version);
1171 Some(format!("/rustc/{sha}"))
1172 }
1173 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1174 }
1175 }
1176
1177 fn cc(&self, target: TargetSelection) -> PathBuf {
1179 if self.config.dry_run() {
1180 return PathBuf::new();
1181 }
1182 self.cc.borrow()[&target].path().into()
1183 }
1184
1185 fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1188 if self.config.dry_run() {
1189 return Vec::new();
1190 }
1191 let base = match c {
1192 CLang::C => self.cc.borrow()[&target].clone(),
1193 CLang::Cxx => self.cxx.borrow()[&target].clone(),
1194 };
1195
1196 base.args()
1199 .iter()
1200 .map(|s| s.to_string_lossy().into_owned())
1201 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1202 .collect::<Vec<String>>()
1203 }
1204
1205 fn cc_unhandled_cflags(
1207 &self,
1208 target: TargetSelection,
1209 which: GitRepo,
1210 c: CLang,
1211 ) -> Vec<String> {
1212 let mut base = Vec::new();
1213
1214 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1218 base.push("-stdlib=libc++".into());
1219 }
1220
1221 if &*target.triple == "i686-pc-windows-gnu" {
1225 base.push("-fno-omit-frame-pointer".into());
1226 }
1227
1228 if let Some(map_to) = self.debuginfo_map_to(which) {
1229 let map = format!("{}={}", self.src.display(), map_to);
1230 let cc = self.cc(target);
1231 if cc.ends_with("clang") || cc.ends_with("gcc") {
1232 base.push(format!("-fdebug-prefix-map={map}"));
1233 } else if cc.ends_with("clang-cl.exe") {
1234 base.push("-Xclang".into());
1235 base.push(format!("-fdebug-prefix-map={map}"));
1236 }
1237 }
1238 base
1239 }
1240
1241 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1243 if self.config.dry_run() {
1244 return None;
1245 }
1246 self.ar.borrow().get(&target).cloned()
1247 }
1248
1249 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1251 if self.config.dry_run() {
1252 return None;
1253 }
1254 self.ranlib.borrow().get(&target).cloned()
1255 }
1256
1257 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1259 if self.config.dry_run() {
1260 return Ok(PathBuf::new());
1261 }
1262 match self.cxx.borrow().get(&target) {
1263 Some(p) => Ok(p.path().into()),
1264 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1265 }
1266 }
1267
1268 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1270 if self.config.dry_run() {
1271 return Some(PathBuf::new());
1272 }
1273 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1274 {
1275 Some(linker)
1276 } else if target.contains("vxworks") {
1277 Some(self.cxx.borrow()[&target].path().into())
1280 } else if !self.is_builder_target(&target)
1281 && helpers::use_host_linker(target)
1282 && !target.is_msvc()
1283 {
1284 Some(self.cc(target))
1285 } else if self.config.lld_mode.is_used()
1286 && self.is_lld_direct_linker(target)
1287 && self.build == target
1288 {
1289 match self.config.lld_mode {
1290 LldMode::SelfContained => Some(self.initial_lld.clone()),
1291 LldMode::External => Some("lld".into()),
1292 LldMode::Unused => None,
1293 }
1294 } else {
1295 None
1296 }
1297 }
1298
1299 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1302 target.is_msvc()
1303 }
1304
1305 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1307 if target.contains("pc-windows-msvc") {
1308 Some(true)
1309 } else {
1310 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1311 }
1312 }
1313
1314 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1316 self.config
1317 .target_config
1318 .get(&target)
1319 .and_then(|t| t.musl_root.as_ref())
1320 .or(self.config.musl_root.as_ref())
1321 .map(|p| &**p)
1322 }
1323
1324 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1326 let t = self.config.target_config.get(&target)?;
1327 if let libdir @ Some(_) = &t.musl_libdir {
1328 return libdir.clone();
1329 }
1330 self.musl_root(target).map(|root| root.join("lib"))
1331 }
1332
1333 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1340 let configured =
1341 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1342 if let Some(path) = configured {
1343 return Some(path.join("lib").join(target.to_string()));
1344 }
1345 let mut env_root = PathBuf::from(std::env::var_os("WASI_SDK_PATH")?);
1346 env_root.push("share");
1347 env_root.push("wasi-sysroot");
1348 env_root.push("lib");
1349 env_root.push(target.to_string());
1350 Some(env_root)
1351 }
1352
1353 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1355 self.config.target_config.get(&target).map(|t| t.no_std)
1356 }
1357
1358 fn remote_tested(&self, target: TargetSelection) -> bool {
1361 self.qemu_rootfs(target).is_some()
1362 || target.contains("android")
1363 || env::var_os("TEST_DEVICE_ADDR").is_some()
1364 }
1365
1366 fn runner(&self, target: TargetSelection) -> Option<String> {
1372 let configured_runner =
1373 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1374 if let Some(runner) = configured_runner {
1375 return Some(runner.to_owned());
1376 }
1377
1378 if target.starts_with("wasm") && target.contains("wasi") {
1379 self.default_wasi_runner(target)
1380 } else {
1381 None
1382 }
1383 }
1384
1385 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1389 let mut finder = crate::core::sanity::Finder::new();
1390
1391 if let Some(path) = finder.maybe_have("wasmtime") {
1395 if let Ok(mut path) = path.into_os_string().into_string() {
1396 path.push_str(" run -C cache=n --dir .");
1397 path.push_str(" --env RUSTC_BOOTSTRAP");
1404
1405 if target.contains("wasip2") {
1406 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1407 }
1408
1409 return Some(path);
1410 }
1411 }
1412
1413 None
1414 }
1415
1416 fn tool_enabled(&self, tool: &str) -> bool {
1421 if !self.config.extended {
1422 return false;
1423 }
1424 match &self.config.tools {
1425 Some(set) => set.contains(tool),
1426 None => true,
1427 }
1428 }
1429
1430 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1436 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1437 }
1438
1439 fn python(&self) -> &Path {
1441 if self.config.build.ends_with("apple-darwin") {
1442 Path::new("/usr/bin/python3")
1446 } else {
1447 self.config
1448 .python
1449 .as_ref()
1450 .expect("python is required for running LLDB or rustdoc tests")
1451 }
1452 }
1453
1454 fn extended_error_dir(&self) -> PathBuf {
1456 self.out.join("tmp/extended-error-metadata")
1457 }
1458
1459 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1478 !self.config.full_bootstrap
1479 && !self.config.download_rustc()
1480 && stage >= 2
1481 && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1482 }
1483
1484 fn force_use_stage2(&self, stage: u32) -> bool {
1490 self.config.download_rustc() && stage >= 2
1491 }
1492
1493 fn release(&self, num: &str) -> String {
1499 match &self.config.channel[..] {
1500 "stable" => num.to_string(),
1501 "beta" => {
1502 if !self.config.omit_git_hash {
1503 format!("{}-beta.{}", num, self.beta_prerelease_version())
1504 } else {
1505 format!("{num}-beta")
1506 }
1507 }
1508 "nightly" => format!("{num}-nightly"),
1509 _ => format!("{num}-dev"),
1510 }
1511 }
1512
1513 fn beta_prerelease_version(&self) -> u32 {
1514 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1515 let version = fs::read_to_string(version_file).ok()?;
1516
1517 helpers::extract_beta_rev(&version)
1518 }
1519
1520 if let Some(s) = self.prerelease_version.get() {
1521 return s;
1522 }
1523
1524 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1528 helpers::git(Some(&self.src))
1532 .arg("rev-list")
1533 .arg("--count")
1534 .arg("--merges")
1535 .arg(format!(
1536 "refs/remotes/origin/{}..HEAD",
1537 self.config.stage0_metadata.config.nightly_branch
1538 ))
1539 .run_always()
1540 .run_capture(self)
1541 .stdout()
1542 });
1543 let n = count.trim().parse().unwrap();
1544 self.prerelease_version.set(Some(n));
1545 n
1546 }
1547
1548 fn rust_release(&self) -> String {
1550 self.release(&self.version)
1551 }
1552
1553 fn package_vers(&self, num: &str) -> String {
1560 match &self.config.channel[..] {
1561 "stable" => num.to_string(),
1562 "beta" => "beta".to_string(),
1563 "nightly" => "nightly".to_string(),
1564 _ => format!("{num}-dev"),
1565 }
1566 }
1567
1568 fn rust_package_vers(&self) -> String {
1570 self.package_vers(&self.version)
1571 }
1572
1573 fn rust_version(&self) -> String {
1579 let mut version = self.rust_info().version(self, &self.version);
1580 if let Some(ref s) = self.config.description {
1581 if !s.is_empty() {
1582 version.push_str(" (");
1583 version.push_str(s);
1584 version.push(')');
1585 }
1586 }
1587 version
1588 }
1589
1590 fn rust_sha(&self) -> Option<&str> {
1592 self.rust_info().sha()
1593 }
1594
1595 fn release_num(&self, package: &str) -> String {
1597 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1598 let toml = t!(fs::read_to_string(toml_file_name));
1599 for line in toml.lines() {
1600 if let Some(stripped) =
1601 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1602 {
1603 return stripped.to_owned();
1604 }
1605 }
1606
1607 panic!("failed to find version in {package}'s Cargo.toml")
1608 }
1609
1610 fn unstable_features(&self) -> bool {
1613 !matches!(&self.config.channel[..], "stable" | "beta")
1614 }
1615
1616 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1620 let mut ret = Vec::new();
1621 let mut list = vec![root.to_owned()];
1622 let mut visited = HashSet::new();
1623 while let Some(krate) = list.pop() {
1624 let krate = self
1625 .crates
1626 .get(&krate)
1627 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1628 ret.push(krate);
1629 for dep in &krate.deps {
1630 if !self.crates.contains_key(dep) {
1631 continue;
1633 }
1634 if visited.insert(dep)
1640 && (dep != "profiler_builtins"
1641 || target
1642 .map(|t| self.config.profiler_enabled(t))
1643 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1644 && (dep != "rustc_codegen_llvm"
1645 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1646 {
1647 list.push(dep.clone());
1648 }
1649 }
1650 }
1651 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1653 }
1654
1655 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1656 if self.config.dry_run() {
1657 return Vec::new();
1658 }
1659
1660 if !stamp.path().exists() {
1661 eprintln!(
1662 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1663 stamp.path().display()
1664 );
1665 crate::exit!(1);
1666 }
1667
1668 let mut paths = Vec::new();
1669 let contents = t!(fs::read(stamp.path()), stamp.path());
1670 for part in contents.split(|b| *b == 0) {
1673 if part.is_empty() {
1674 continue;
1675 }
1676 let dependency_type = match part[0] as char {
1677 'h' => DependencyType::Host,
1678 's' => DependencyType::TargetSelfContained,
1679 't' => DependencyType::Target,
1680 _ => unreachable!(),
1681 };
1682 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1683 paths.push((path, dependency_type));
1684 }
1685 paths
1686 }
1687
1688 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1693 self.copy_link_internal(src, dst, true);
1694 }
1695
1696 pub fn copy_link(&self, src: &Path, dst: &Path) {
1701 self.copy_link_internal(src, dst, false);
1702 }
1703
1704 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1705 if self.config.dry_run() {
1706 return;
1707 }
1708 self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1709 if src == dst {
1710 return;
1711 }
1712 if let Err(e) = fs::remove_file(dst) {
1713 if cfg!(windows) && e.kind() != io::ErrorKind::NotFound {
1714 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1717 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1718 }
1719 }
1720 let metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1721 let mut src = src.to_path_buf();
1722 if metadata.file_type().is_symlink() {
1723 if dereference_symlinks {
1724 src = t!(fs::canonicalize(src));
1725 } else {
1726 let link = t!(fs::read_link(src));
1727 t!(self.symlink_file(link, dst));
1728 return;
1729 }
1730 }
1731 if let Ok(()) = fs::hard_link(&src, dst) {
1732 } else {
1735 if let Err(e) = fs::copy(&src, dst) {
1736 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1737 }
1738 t!(fs::set_permissions(dst, metadata.permissions()));
1739
1740 let file_times = fs::FileTimes::new()
1743 .set_accessed(t!(metadata.accessed()))
1744 .set_modified(t!(metadata.modified()));
1745 t!(set_file_times(dst, file_times));
1746 }
1747 }
1748
1749 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1753 if self.config.dry_run() {
1754 return;
1755 }
1756 for f in self.read_dir(src) {
1757 let path = f.path();
1758 let name = path.file_name().unwrap();
1759 let dst = dst.join(name);
1760 if t!(f.file_type()).is_dir() {
1761 t!(fs::create_dir_all(&dst));
1762 self.cp_link_r(&path, &dst);
1763 } else {
1764 self.copy_link(&path, &dst);
1765 }
1766 }
1767 }
1768
1769 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1775 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1777 }
1778
1779 fn cp_link_filtered_recurse(
1781 &self,
1782 src: &Path,
1783 dst: &Path,
1784 relative: &Path,
1785 filter: &dyn Fn(&Path) -> bool,
1786 ) {
1787 for f in self.read_dir(src) {
1788 let path = f.path();
1789 let name = path.file_name().unwrap();
1790 let dst = dst.join(name);
1791 let relative = relative.join(name);
1792 if filter(&relative) {
1794 if t!(f.file_type()).is_dir() {
1795 let _ = fs::remove_dir_all(&dst);
1796 self.create_dir(&dst);
1797 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1798 } else {
1799 let _ = fs::remove_file(&dst);
1800 self.copy_link(&path, &dst);
1801 }
1802 }
1803 }
1804 }
1805
1806 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1807 let file_name = src.file_name().unwrap();
1808 let dest = dest_folder.join(file_name);
1809 self.copy_link(src, &dest);
1810 }
1811
1812 fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1813 if self.config.dry_run() {
1814 return;
1815 }
1816 let dst = dstdir.join(src.file_name().unwrap());
1817 self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1818 t!(fs::create_dir_all(dstdir));
1819 if !src.exists() {
1820 panic!("ERROR: File \"{}\" not found!", src.display());
1821 }
1822 self.copy_link_internal(src, &dst, true);
1823 chmod(&dst, perms);
1824 }
1825
1826 fn read(&self, path: &Path) -> String {
1827 if self.config.dry_run() {
1828 return String::new();
1829 }
1830 t!(fs::read_to_string(path))
1831 }
1832
1833 fn create_dir(&self, dir: &Path) {
1834 if self.config.dry_run() {
1835 return;
1836 }
1837 t!(fs::create_dir_all(dir))
1838 }
1839
1840 fn remove_dir(&self, dir: &Path) {
1841 if self.config.dry_run() {
1842 return;
1843 }
1844 t!(fs::remove_dir_all(dir))
1845 }
1846
1847 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1848 let iter = match fs::read_dir(dir) {
1849 Ok(v) => v,
1850 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1851 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1852 };
1853 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1854 }
1855
1856 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1857 #[cfg(unix)]
1858 use std::os::unix::fs::symlink as symlink_file;
1859 #[cfg(windows)]
1860 use std::os::windows::fs::symlink_file;
1861 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1862 }
1863
1864 fn ninja(&self) -> bool {
1867 let mut cmd_finder = crate::core::sanity::Finder::new();
1868
1869 if self.config.ninja_in_file {
1870 if cmd_finder.maybe_have("ninja-build").is_none()
1873 && cmd_finder.maybe_have("ninja").is_none()
1874 {
1875 eprintln!(
1876 "
1877Couldn't find required command: ninja (or ninja-build)
1878
1879You should install ninja as described at
1880<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1881or set `ninja = false` in the `[llvm]` section of `config.toml`.
1882Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1883to download LLVM rather than building it.
1884"
1885 );
1886 exit!(1);
1887 }
1888 }
1889
1890 if !self.config.ninja_in_file
1898 && self.config.build.is_msvc()
1899 && cmd_finder.maybe_have("ninja").is_some()
1900 {
1901 return true;
1902 }
1903
1904 self.config.ninja_in_file
1905 }
1906
1907 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1908 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1909 }
1910
1911 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1912 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1913 }
1914
1915 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1916 where
1917 C: Fn(ColorChoice) -> StandardStream,
1918 F: FnOnce(&mut dyn WriteColor) -> R,
1919 {
1920 let choice = match self.config.color {
1921 flags::Color::Always => ColorChoice::Always,
1922 flags::Color::Never => ColorChoice::Never,
1923 flags::Color::Auto if !is_tty => ColorChoice::Never,
1924 flags::Color::Auto => ColorChoice::Auto,
1925 };
1926 let mut stream = constructor(choice);
1927 let result = f(&mut stream);
1928 stream.reset().unwrap();
1929 result
1930 }
1931
1932 fn is_builder_target(&self, target: &TargetSelection) -> bool {
1934 &self.config.build == target
1935 }
1936}
1937
1938#[cfg(unix)]
1939fn chmod(path: &Path, perms: u32) {
1940 use std::os::unix::fs::*;
1941 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1942}
1943#[cfg(windows)]
1944fn chmod(_path: &Path, _perms: u32) {}
1945
1946impl Compiler {
1947 pub fn with_stage(mut self, stage: u32) -> Compiler {
1948 self.stage = stage;
1949 self
1950 }
1951
1952 pub fn is_snapshot(&self, build: &Build) -> bool {
1954 self.stage == 0 && self.host == build.build
1955 }
1956}
1957
1958fn envify(s: &str) -> String {
1959 s.chars()
1960 .map(|c| match c {
1961 '-' => '_',
1962 c => c,
1963 })
1964 .flat_map(|c| c.to_uppercase())
1965 .collect()
1966}
1967
1968pub fn prepare_behaviour_dump_dir(build: &Build) {
1970 static INITIALIZED: OnceLock<bool> = OnceLock::new();
1971
1972 let dump_path = build.out.join("bootstrap-shims-dump");
1973
1974 let initialized = INITIALIZED.get().unwrap_or(&false);
1975 if !initialized {
1976 if dump_path.exists() {
1978 t!(fs::remove_dir_all(&dump_path));
1979 }
1980
1981 t!(fs::create_dir_all(&dump_path));
1982
1983 t!(INITIALIZED.set(true));
1984 }
1985}