1#![cfg_attr(test, allow(unused))]
19
20use std::cell::{Cell, RefCell};
21use std::collections::{BTreeSet, HashMap, HashSet};
22use std::fmt::Display;
23use std::path::{Path, PathBuf};
24use std::process::Command;
25use std::sync::OnceLock;
26use std::time::SystemTime;
27use std::{env, fs, io, str};
28
29use build_helper::ci::gha;
30use build_helper::exit;
31use cc::Tool;
32use termcolor::{ColorChoice, StandardStream, WriteColor};
33use utils::build_stamp::BuildStamp;
34use utils::channel::GitInfo;
35
36use crate::core::builder;
37use crate::core::builder::Kind;
38use crate::core::config::{DryRun, LldMode, LlvmLibunwind, Target, TargetSelection, flags};
39use crate::utils::exec::{BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode, command};
40use crate::utils::helpers::{self, dir_is_empty, exe, libdir, output, set_file_times, symlink_dir};
41
42mod core;
43mod utils;
44
45pub use core::builder::PathSet;
46pub use core::config::Config;
47pub use core::config::flags::{Flags, Subcommand};
48
49#[cfg(feature = "tracing")]
50use tracing::{instrument, span};
51pub use utils::change_tracker::{
52 CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
53};
54
55use crate::core::build_steps::vendor::VENDOR_DIR;
56
57const LLVM_TOOLS: &[&str] = &[
58 "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", ];
73
74const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
76
77#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
81 (None, "bootstrap", None),
82 (Some(Mode::Rustc), "llvm_enzyme", None),
83 (Some(Mode::Codegen), "llvm_enzyme", None),
84 (Some(Mode::ToolRustc), "llvm_enzyme", None),
85 (Some(Mode::ToolRustc), "rust_analyzer", None),
86 (Some(Mode::ToolStd), "rust_analyzer", None),
87 ];
91
92#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
98pub struct Compiler {
99 stage: u32,
100 host: TargetSelection,
101 forced_compiler: bool,
105}
106
107impl std::hash::Hash for Compiler {
108 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
109 self.stage.hash(state);
110 self.host.hash(state);
111 }
112}
113
114impl PartialEq for Compiler {
115 fn eq(&self, other: &Self) -> bool {
116 self.stage == other.stage && self.host == other.host
117 }
118}
119
120#[derive(PartialEq, Eq, Copy, Clone, Debug)]
121pub enum DocTests {
122 Yes,
124 No,
126 Only,
128}
129
130pub enum GitRepo {
131 Rustc,
132 Llvm,
133}
134
135#[derive(Clone)]
146pub struct Build {
147 config: Config,
149
150 version: String,
152
153 src: PathBuf,
155 out: PathBuf,
156 bootstrap_out: PathBuf,
157 cargo_info: GitInfo,
158 rust_analyzer_info: GitInfo,
159 clippy_info: GitInfo,
160 miri_info: GitInfo,
161 rustfmt_info: GitInfo,
162 enzyme_info: GitInfo,
163 in_tree_llvm_info: GitInfo,
164 in_tree_gcc_info: GitInfo,
165 local_rebuild: bool,
166 fail_fast: bool,
167 doc_tests: DocTests,
168 verbosity: usize,
169
170 build: TargetSelection,
172 hosts: Vec<TargetSelection>,
174 targets: Vec<TargetSelection>,
176
177 initial_rustc: PathBuf,
178 initial_rustdoc: PathBuf,
179 initial_cargo: PathBuf,
180 initial_lld: PathBuf,
181 initial_relative_libdir: PathBuf,
182 initial_sysroot: PathBuf,
183
184 cc: RefCell<HashMap<TargetSelection, cc::Tool>>,
187 cxx: RefCell<HashMap<TargetSelection, cc::Tool>>,
188 ar: RefCell<HashMap<TargetSelection, PathBuf>>,
189 ranlib: RefCell<HashMap<TargetSelection, PathBuf>>,
190 crates: HashMap<String, Crate>,
193 crate_paths: HashMap<PathBuf, String>,
194 is_sudo: bool,
195 delayed_failures: RefCell<Vec<String>>,
196 prerelease_version: Cell<Option<u32>>,
197
198 #[cfg(feature = "build-metrics")]
199 metrics: crate::utils::metrics::BuildMetrics,
200}
201
202#[derive(Debug, Clone)]
203struct Crate {
204 name: String,
205 deps: HashSet<String>,
206 path: PathBuf,
207 features: Vec<String>,
208}
209
210impl Crate {
211 fn local_path(&self, build: &Build) -> PathBuf {
212 self.path.strip_prefix(&build.config.src).unwrap().into()
213 }
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
218pub enum DependencyType {
219 Host,
221 Target,
223 TargetSelfContained,
225}
226
227#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
232pub enum Mode {
233 Std,
235
236 Rustc,
238
239 Codegen,
241
242 ToolBootstrap,
249
250 ToolStd,
254
255 ToolRustc,
260}
261
262impl Mode {
263 pub fn is_tool(&self) -> bool {
264 matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
265 }
266
267 pub fn must_support_dlopen(&self) -> bool {
268 matches!(self, Mode::Std | Mode::Codegen)
269 }
270}
271
272#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
273pub enum CLang {
274 C,
275 Cxx,
276}
277
278macro_rules! forward {
279 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
280 impl Build {
281 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
282 self.config.$fn( $($param),* )
283 } )+
284 }
285 }
286}
287
288forward! {
289 verbose(f: impl Fn()),
290 is_verbose() -> bool,
291 create(path: &Path, s: &str),
292 remove(f: &Path),
293 tempdir() -> PathBuf,
294 llvm_link_shared() -> bool,
295 download_rustc() -> bool,
296 initial_rustfmt() -> Option<PathBuf>,
297}
298
299impl Build {
300 pub fn new(mut config: Config) -> Build {
305 let src = config.src.clone();
306 let out = config.out.clone();
307
308 #[cfg(unix)]
309 let is_sudo = match env::var_os("SUDO_USER") {
312 Some(_sudo_user) => {
313 let uid = unsafe { libc::getuid() };
318 uid == 0
319 }
320 None => false,
321 };
322 #[cfg(not(unix))]
323 let is_sudo = false;
324
325 let rust_info = config.rust_info.clone();
326 let cargo_info = config.cargo_info.clone();
327 let rust_analyzer_info = config.rust_analyzer_info.clone();
328 let clippy_info = config.clippy_info.clone();
329 let miri_info = config.miri_info.clone();
330 let rustfmt_info = config.rustfmt_info.clone();
331 let enzyme_info = config.enzyme_info.clone();
332 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
333 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
334
335 let initial_target_libdir_str =
336 config.initial_sysroot.join("lib/rustlib").join(config.build).join("lib");
337
338 let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
339 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
340
341 let initial_relative_libdir = initial_target_dir
342 .ancestors()
343 .nth(2)
344 .unwrap()
345 .strip_prefix(&config.initial_sysroot)
346 .expect("Couldn’t determine initial relative libdir.")
347 .to_path_buf();
348
349 let version = std::fs::read_to_string(src.join("src").join("version"))
350 .expect("failed to read src/version");
351 let version = version.trim();
352
353 let mut bootstrap_out = std::env::current_exe()
354 .expect("could not determine path to running process")
355 .parent()
356 .unwrap()
357 .to_path_buf();
358 if bootstrap_out.ends_with("deps") {
361 bootstrap_out.pop();
362 }
363 if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
364 panic!(
366 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
367 bootstrap_out.display()
368 )
369 }
370
371 if rust_info.is_from_tarball() && config.description.is_none() {
372 config.description = Some("built from a source tarball".to_owned());
373 }
374
375 let mut build = Build {
376 initial_lld,
377 initial_relative_libdir,
378 initial_rustc: config.initial_rustc.clone(),
379 initial_rustdoc: config.initial_rustc.with_file_name(exe("rustdoc", config.build)),
380 initial_cargo: config.initial_cargo.clone(),
381 initial_sysroot: config.initial_sysroot.clone(),
382 local_rebuild: config.local_rebuild,
383 fail_fast: config.cmd.fail_fast(),
384 doc_tests: config.cmd.doc_tests(),
385 verbosity: config.verbose,
386
387 build: config.build,
388 hosts: config.hosts.clone(),
389 targets: config.targets.clone(),
390
391 config,
392 version: version.to_string(),
393 src,
394 out,
395 bootstrap_out,
396
397 cargo_info,
398 rust_analyzer_info,
399 clippy_info,
400 miri_info,
401 rustfmt_info,
402 enzyme_info,
403 in_tree_llvm_info,
404 in_tree_gcc_info,
405 cc: RefCell::new(HashMap::new()),
406 cxx: RefCell::new(HashMap::new()),
407 ar: RefCell::new(HashMap::new()),
408 ranlib: RefCell::new(HashMap::new()),
409 crates: HashMap::new(),
410 crate_paths: HashMap::new(),
411 is_sudo,
412 delayed_failures: RefCell::new(Vec::new()),
413 prerelease_version: Cell::new(None),
414
415 #[cfg(feature = "build-metrics")]
416 metrics: crate::utils::metrics::BuildMetrics::init(),
417 };
418
419 let local_version_verbose =
422 output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
423 let local_release = local_version_verbose
424 .lines()
425 .filter_map(|x| x.strip_prefix("release:"))
426 .next()
427 .unwrap()
428 .trim();
429 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
430 build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
431 build.local_rebuild = true;
432 }
433
434 build.verbose(|| println!("finding compilers"));
435 utils::cc_detect::find(&build);
436 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
442 build.verbose(|| println!("running sanity check"));
443 crate::core::sanity::check(&mut build);
444
445 let rust_submodules = ["library/backtrace", "library/stdarch"];
448 for s in rust_submodules {
449 build.require_submodule(
450 s,
451 Some(
452 "The submodule is required for the standard library \
453 and the main Cargo workspace.",
454 ),
455 );
456 }
457 build.update_existing_submodules();
459
460 build.verbose(|| println!("learning about cargo"));
461 crate::core::metadata::build(&mut build);
462 }
463
464 let build_triple = build.out.join(build.build);
466 t!(fs::create_dir_all(&build_triple));
467 let host = build.out.join("host");
468 if host.is_symlink() {
469 #[cfg(windows)]
472 t!(fs::remove_dir(&host));
473 #[cfg(not(windows))]
474 t!(fs::remove_file(&host));
475 }
476 t!(
477 symlink_dir(&build.config, &build_triple, &host),
478 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
479 );
480
481 build
482 }
483
484 #[cfg_attr(
493 feature = "tracing",
494 instrument(
495 level = "trace",
496 name = "Build::require_submodule",
497 skip_all,
498 fields(submodule = submodule),
499 ),
500 )]
501 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
502 if self.rust_info().is_from_tarball() {
503 return;
504 }
505
506 if cfg!(test) && !self.config.submodules() {
509 return;
510 }
511 self.config.update_submodule(submodule);
512 let absolute_path = self.config.src.join(submodule);
513 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
514 let maybe_enable = if !self.config.submodules()
515 && self.config.rust_info.is_managed_git_subrepository()
516 {
517 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
518 } else {
519 ""
520 };
521 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
522 eprintln!(
523 "submodule {submodule} does not appear to be checked out, \
524 but it is required for this step{maybe_enable}{err_hint}"
525 );
526 exit!(1);
527 }
528 }
529
530 pub fn require_and_update_all_submodules(&self) {
533 for submodule in build_helper::util::parse_gitmodules(&self.src) {
534 self.require_submodule(submodule, None);
535 }
536 }
537
538 fn update_existing_submodules(&self) {
541 if !self.config.submodules() {
544 return;
545 }
546 let output = helpers::git(Some(&self.src))
547 .args(["config", "--file"])
548 .arg(".gitmodules")
549 .args(["--get-regexp", "path"])
550 .run_capture(self)
551 .stdout();
552 std::thread::scope(|s| {
553 for line in output.lines() {
556 let submodule = line.split_once(' ').unwrap().1;
557 let config = self.config.clone();
558 s.spawn(move || {
559 Self::update_existing_submodule(&config, submodule);
560 });
561 }
562 });
563 }
564
565 pub fn update_existing_submodule(config: &Config, submodule: &str) {
567 if !config.submodules() {
569 return;
570 }
571
572 if GitInfo::new(false, Path::new(submodule)).is_managed_git_subrepository() {
573 config.update_submodule(submodule);
574 }
575 }
576
577 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
579 pub fn build(&mut self) {
580 trace!("setting up job management");
581 unsafe {
582 crate::utils::job::setup(self);
583 }
584
585 trace!("downloading rustfmt early");
587 let _ = &builder::Builder::new(self).initial_rustfmt();
588
589 {
591 #[cfg(feature = "tracing")]
592 let _hardcoded_span = span!(
593 tracing::Level::DEBUG,
594 "handling hardcoded subcommands (Format, Suggest, Perf)"
595 )
596 .entered();
597
598 match &self.config.cmd {
599 Subcommand::Format { check, all } => {
600 return core::build_steps::format::format(
601 &builder::Builder::new(self),
602 *check,
603 *all,
604 &self.config.paths,
605 );
606 }
607 Subcommand::Suggest { run } => {
608 return core::build_steps::suggest::suggest(&builder::Builder::new(self), *run);
609 }
610 Subcommand::Perf(args) => {
611 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
612 }
613 _cmd => {
614 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
615 }
616 }
617
618 debug!("handling subcommand normally");
619 }
620
621 if !self.config.dry_run() {
622 #[cfg(feature = "tracing")]
623 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
624
625 {
628 #[cfg(feature = "tracing")]
629 let _sanity_check_span =
630 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
631 self.config.dry_run = DryRun::SelfCheck;
632 let builder = builder::Builder::new(self);
633 builder.execute_cli();
634 }
635
636 {
638 #[cfg(feature = "tracing")]
639 let _actual_run_span =
640 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
641 self.config.dry_run = DryRun::Disabled;
642 let builder = builder::Builder::new(self);
643 builder.execute_cli();
644 }
645 } else {
646 #[cfg(feature = "tracing")]
647 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
648
649 let builder = builder::Builder::new(self);
650 builder.execute_cli();
651 }
652
653 #[cfg(feature = "tracing")]
654 debug!("checking for postponed test failures from `test --no-fail-fast`");
655
656 let failures = self.delayed_failures.borrow();
658 if !failures.is_empty() {
659 eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
660 for failure in failures.iter() {
661 eprintln!(" - {failure}\n");
662 }
663 exit!(1);
664 }
665
666 #[cfg(feature = "build-metrics")]
667 self.metrics.persist(self);
668 }
669
670 fn rust_info(&self) -> &GitInfo {
671 &self.config.rust_info
672 }
673
674 fn std_features(&self, target: TargetSelection) -> String {
677 let mut features: BTreeSet<&str> =
678 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
679
680 match self.config.llvm_libunwind(target) {
681 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
682 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
683 LlvmLibunwind::No => false,
684 };
685
686 if self.config.backtrace {
687 features.insert("backtrace");
688 }
689
690 if self.config.profiler_enabled(target) {
691 features.insert("profiler");
692 }
693
694 if target.contains("zkvm") {
696 features.insert("compiler-builtins-mem");
697 }
698
699 features.into_iter().collect::<Vec<_>>().join(" ")
700 }
701
702 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
704 let possible_features_by_crates: HashSet<_> = crates
705 .iter()
706 .flat_map(|krate| &self.crates[krate].features)
707 .map(std::ops::Deref::deref)
708 .collect();
709 let check = |feature: &str| -> bool {
710 crates.is_empty() || possible_features_by_crates.contains(feature)
711 };
712 let mut features = vec![];
713 if self.config.jemalloc(target) && check("jemalloc") {
714 features.push("jemalloc");
715 }
716 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
717 features.push("llvm");
718 }
719 if self.config.rust_randomize_layout {
721 features.push("rustc_randomized_layouts");
722 }
723
724 if !self.config.rust_debug_logging && check("max_level_info") {
730 features.push("max_level_info");
731 }
732
733 features.join(" ")
734 }
735
736 fn cargo_dir(&self) -> &'static str {
739 if self.config.rust_optimize.is_release() { "release" } else { "debug" }
740 }
741
742 fn tools_dir(&self, compiler: Compiler) -> PathBuf {
743 let out = self.out.join(compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
744 t!(fs::create_dir_all(&out));
745 out
746 }
747
748 fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
753 let suffix = match mode {
754 Mode::Std => "-std",
755 Mode::Rustc => "-rustc",
756 Mode::Codegen => "-codegen",
757 Mode::ToolBootstrap => "-bootstrap-tools",
758 Mode::ToolStd | Mode::ToolRustc => "-tools",
759 };
760 self.out.join(compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
761 }
762
763 fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
767 self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
768 }
769
770 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
775 if self.config.llvm_from_ci && self.is_builder_target(target) {
776 self.config.ci_llvm_root()
777 } else {
778 self.out.join(target).join("llvm")
779 }
780 }
781
782 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
783 self.out.join(&*target.triple).join("enzyme")
784 }
785
786 fn gcc_out(&self, target: TargetSelection) -> PathBuf {
787 self.out.join(&*target.triple).join("gcc")
788 }
789
790 fn lld_out(&self, target: TargetSelection) -> PathBuf {
791 self.out.join(target).join("lld")
792 }
793
794 fn doc_out(&self, target: TargetSelection) -> PathBuf {
796 self.out.join(target).join("doc")
797 }
798
799 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
801 self.out.join(target).join("json-doc")
802 }
803
804 fn test_out(&self, target: TargetSelection) -> PathBuf {
805 self.out.join(target).join("test")
806 }
807
808 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
810 self.out.join(target).join("compiler-doc")
811 }
812
813 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
815 self.out.join(target).join("md-doc")
816 }
817
818 fn vendored_crates_path(&self) -> Option<PathBuf> {
820 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
821 }
822
823 fn is_system_llvm(&self, target: TargetSelection) -> bool {
828 match self.config.target_config.get(&target) {
829 Some(Target { llvm_config: Some(_), .. }) => {
830 let ci_llvm = self.config.llvm_from_ci && self.is_builder_target(target);
831 !ci_llvm
832 }
833 Some(Target { llvm_config: None, .. }) => false,
835 None => false,
836 }
837 }
838
839 fn is_rust_llvm(&self, target: TargetSelection) -> bool {
843 match self.config.target_config.get(&target) {
844 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
848 _ => !self.is_system_llvm(target),
851 }
852 }
853
854 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
856 let target_config = self.config.target_config.get(&target);
857 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
858 s.to_path_buf()
859 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
860 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
861 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
862 if filecheck.exists() {
863 filecheck
864 } else {
865 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
868 let lib_filecheck =
869 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
870 if lib_filecheck.exists() {
871 lib_filecheck
872 } else {
873 filecheck
877 }
878 }
879 } else {
880 let base = self.llvm_out(target).join("build");
881 let base = if !self.ninja() && target.is_msvc() {
882 if self.config.llvm_optimize {
883 if self.config.llvm_release_debuginfo {
884 base.join("RelWithDebInfo")
885 } else {
886 base.join("Release")
887 }
888 } else {
889 base.join("Debug")
890 }
891 } else {
892 base
893 };
894 base.join("bin").join(exe("FileCheck", target))
895 }
896 }
897
898 fn native_dir(&self, target: TargetSelection) -> PathBuf {
900 self.out.join(target).join("native")
901 }
902
903 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
906 self.native_dir(target).join("rust-test-helpers")
907 }
908
909 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
911 if env::var_os("RUST_TEST_THREADS").is_none() {
912 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
913 }
914 }
915
916 fn rustc_snapshot_libdir(&self) -> PathBuf {
918 self.rustc_snapshot_sysroot().join(libdir(self.config.build))
919 }
920
921 fn rustc_snapshot_sysroot(&self) -> &Path {
923 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
924 SYSROOT_CACHE.get_or_init(|| {
925 let mut rustc = Command::new(&self.initial_rustc);
926 rustc.args(["--print", "sysroot"]);
927 output(&mut rustc).trim().into()
928 })
929 }
930
931 #[track_caller]
935 fn run(
936 &self,
937 command: &mut BootstrapCommand,
938 stdout: OutputMode,
939 stderr: OutputMode,
940 ) -> CommandOutput {
941 command.mark_as_executed();
942 if self.config.dry_run() && !command.run_always {
943 return CommandOutput::default();
944 }
945
946 #[cfg(feature = "tracing")]
947 let _run_span = trace_cmd!(command);
948
949 let created_at = command.get_created_location();
950 let executed_at = std::panic::Location::caller();
951
952 self.verbose(|| {
953 println!("running: {command:?} (created at {created_at}, executed at {executed_at})")
954 });
955
956 let cmd = command.as_command_mut();
957 cmd.stdout(stdout.stdio());
958 cmd.stderr(stderr.stdio());
959
960 let output = cmd.output();
961
962 use std::fmt::Write;
963
964 let mut message = String::new();
965 let output: CommandOutput = match output {
966 Ok(output) if output.status.success() => {
968 CommandOutput::from_output(output, stdout, stderr)
969 }
970 Ok(output) => {
972 writeln!(
973 message,
974 r#"
975Command {command:?} did not execute successfully.
976Expected success, got {}
977Created at: {created_at}
978Executed at: {executed_at}"#,
979 output.status,
980 )
981 .unwrap();
982
983 let output: CommandOutput = CommandOutput::from_output(output, stdout, stderr);
984
985 if stdout.captures() {
989 writeln!(message, "\nSTDOUT ----\n{}", output.stdout().trim()).unwrap();
990 }
991 if stderr.captures() {
992 writeln!(message, "\nSTDERR ----\n{}", output.stderr().trim()).unwrap();
993 }
994 output
995 }
996 Err(e) => {
998 writeln!(
999 message,
1000 "\n\nCommand {command:?} did not execute successfully.\
1001 \nIt was not possible to execute the command: {e:?}"
1002 )
1003 .unwrap();
1004 CommandOutput::did_not_start(stdout, stderr)
1005 }
1006 };
1007
1008 let fail = |message: &str, output: CommandOutput| -> ! {
1009 if self.is_verbose() {
1010 println!("{message}");
1011 } else {
1012 let (stdout, stderr) = (output.stdout_if_present(), output.stderr_if_present());
1013 if stdout.is_some() || stderr.is_some() {
1017 if let Some(stdout) =
1018 output.stdout_if_present().take_if(|s| !s.trim().is_empty())
1019 {
1020 println!("STDOUT:\n{stdout}\n");
1021 }
1022 if let Some(stderr) =
1023 output.stderr_if_present().take_if(|s| !s.trim().is_empty())
1024 {
1025 println!("STDERR:\n{stderr}\n");
1026 }
1027 println!("Command {command:?} has failed. Rerun with -v to see more details.");
1028 } else {
1029 println!("Command has failed. Rerun with -v to see more details.");
1030 }
1031 }
1032 exit!(1);
1033 };
1034
1035 if !output.is_success() {
1036 match command.failure_behavior {
1037 BehaviorOnFailure::DelayFail => {
1038 if self.fail_fast {
1039 fail(&message, output);
1040 }
1041
1042 let mut failures = self.delayed_failures.borrow_mut();
1043 failures.push(message);
1044 }
1045 BehaviorOnFailure::Exit => {
1046 fail(&message, output);
1047 }
1048 BehaviorOnFailure::Ignore => {
1049 }
1053 }
1054 }
1055 output
1056 }
1057
1058 pub fn is_verbose_than(&self, level: usize) -> bool {
1060 self.verbosity > level
1061 }
1062
1063 fn verbose_than(&self, level: usize, f: impl Fn()) {
1065 if self.is_verbose_than(level) {
1066 f()
1067 }
1068 }
1069
1070 fn info(&self, msg: &str) {
1071 match self.config.dry_run {
1072 DryRun::SelfCheck => (),
1073 DryRun::Disabled | DryRun::UserSelected => {
1074 println!("{msg}");
1075 }
1076 }
1077 }
1078
1079 #[must_use = "Groups should not be dropped until the Step finishes running"]
1080 #[track_caller]
1081 fn msg_clippy(
1082 &self,
1083 what: impl Display,
1084 target: impl Into<Option<TargetSelection>>,
1085 ) -> Option<gha::Group> {
1086 self.msg(Kind::Clippy, self.config.stage, what, self.config.build, target)
1087 }
1088
1089 #[must_use = "Groups should not be dropped until the Step finishes running"]
1090 #[track_caller]
1091 fn msg_check(
1092 &self,
1093 what: impl Display,
1094 target: impl Into<Option<TargetSelection>>,
1095 ) -> Option<gha::Group> {
1096 self.msg(Kind::Check, self.config.stage, what, self.config.build, target)
1097 }
1098
1099 #[must_use = "Groups should not be dropped until the Step finishes running"]
1100 #[track_caller]
1101 fn msg_doc(
1102 &self,
1103 compiler: Compiler,
1104 what: impl Display,
1105 target: impl Into<Option<TargetSelection>> + Copy,
1106 ) -> Option<gha::Group> {
1107 self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into())
1108 }
1109
1110 #[must_use = "Groups should not be dropped until the Step finishes running"]
1111 #[track_caller]
1112 fn msg_build(
1113 &self,
1114 compiler: Compiler,
1115 what: impl Display,
1116 target: impl Into<Option<TargetSelection>>,
1117 ) -> Option<gha::Group> {
1118 self.msg(Kind::Build, compiler.stage, what, compiler.host, target)
1119 }
1120
1121 #[must_use = "Groups should not be dropped until the Step finishes running"]
1125 #[track_caller]
1126 fn msg(
1127 &self,
1128 action: impl Into<Kind>,
1129 stage: u32,
1130 what: impl Display,
1131 host: impl Into<Option<TargetSelection>>,
1132 target: impl Into<Option<TargetSelection>>,
1133 ) -> Option<gha::Group> {
1134 let action = action.into().description();
1135 let msg = |fmt| format!("{action} stage{stage} {what}{fmt}");
1136 let msg = if let Some(target) = target.into() {
1137 let host = host.into().unwrap();
1138 if host == target {
1139 msg(format_args!(" ({target})"))
1140 } else {
1141 msg(format_args!(" ({host} -> {target})"))
1142 }
1143 } else {
1144 msg(format_args!(""))
1145 };
1146 self.group(&msg)
1147 }
1148
1149 #[must_use = "Groups should not be dropped until the Step finishes running"]
1153 #[track_caller]
1154 fn msg_unstaged(
1155 &self,
1156 action: impl Into<Kind>,
1157 what: impl Display,
1158 target: TargetSelection,
1159 ) -> Option<gha::Group> {
1160 let action = action.into().description();
1161 let msg = format!("{action} {what} for {target}");
1162 self.group(&msg)
1163 }
1164
1165 #[must_use = "Groups should not be dropped until the Step finishes running"]
1166 #[track_caller]
1167 fn msg_sysroot_tool(
1168 &self,
1169 action: impl Into<Kind>,
1170 stage: u32,
1171 what: impl Display,
1172 host: TargetSelection,
1173 target: TargetSelection,
1174 ) -> Option<gha::Group> {
1175 let action = action.into().description();
1176 let msg = |fmt| format!("{action} {what} {fmt}");
1177 let msg = if host == target {
1178 msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1))
1179 } else {
1180 msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1))
1181 };
1182 self.group(&msg)
1183 }
1184
1185 #[track_caller]
1186 fn group(&self, msg: &str) -> Option<gha::Group> {
1187 match self.config.dry_run {
1188 DryRun::SelfCheck => None,
1189 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1190 }
1191 }
1192
1193 fn jobs(&self) -> u32 {
1196 self.config.jobs.unwrap_or_else(|| {
1197 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1198 })
1199 }
1200
1201 fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
1202 if !self.config.rust_remap_debuginfo {
1203 return None;
1204 }
1205
1206 match which {
1207 GitRepo::Rustc => {
1208 let sha = self.rust_sha().unwrap_or(&self.version);
1209 Some(format!("/rustc/{sha}"))
1210 }
1211 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1212 }
1213 }
1214
1215 fn cc(&self, target: TargetSelection) -> PathBuf {
1217 if self.config.dry_run() {
1218 return PathBuf::new();
1219 }
1220 self.cc.borrow()[&target].path().into()
1221 }
1222
1223 fn cc_tool(&self, target: TargetSelection) -> Tool {
1225 self.cc.borrow()[&target].clone()
1226 }
1227
1228 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1230 self.cxx.borrow()[&target].clone()
1231 }
1232
1233 fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1236 if self.config.dry_run() {
1237 return Vec::new();
1238 }
1239 let base = match c {
1240 CLang::C => self.cc.borrow()[&target].clone(),
1241 CLang::Cxx => self.cxx.borrow()[&target].clone(),
1242 };
1243
1244 base.args()
1247 .iter()
1248 .map(|s| s.to_string_lossy().into_owned())
1249 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1250 .collect::<Vec<String>>()
1251 }
1252
1253 fn cc_unhandled_cflags(
1255 &self,
1256 target: TargetSelection,
1257 which: GitRepo,
1258 c: CLang,
1259 ) -> Vec<String> {
1260 let mut base = Vec::new();
1261
1262 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1266 base.push("-stdlib=libc++".into());
1267 }
1268
1269 if &*target.triple == "i686-pc-windows-gnu" {
1273 base.push("-fno-omit-frame-pointer".into());
1274 }
1275
1276 if let Some(map_to) = self.debuginfo_map_to(which) {
1277 let map = format!("{}={}", self.src.display(), map_to);
1278 let cc = self.cc(target);
1279 if cc.ends_with("clang") || cc.ends_with("gcc") {
1280 base.push(format!("-fdebug-prefix-map={map}"));
1281 } else if cc.ends_with("clang-cl.exe") {
1282 base.push("-Xclang".into());
1283 base.push(format!("-fdebug-prefix-map={map}"));
1284 }
1285 }
1286 base
1287 }
1288
1289 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1291 if self.config.dry_run() {
1292 return None;
1293 }
1294 self.ar.borrow().get(&target).cloned()
1295 }
1296
1297 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1299 if self.config.dry_run() {
1300 return None;
1301 }
1302 self.ranlib.borrow().get(&target).cloned()
1303 }
1304
1305 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1307 if self.config.dry_run() {
1308 return Ok(PathBuf::new());
1309 }
1310 match self.cxx.borrow().get(&target) {
1311 Some(p) => Ok(p.path().into()),
1312 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1313 }
1314 }
1315
1316 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1318 if self.config.dry_run() {
1319 return Some(PathBuf::new());
1320 }
1321 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1322 {
1323 Some(linker)
1324 } else if target.contains("vxworks") {
1325 Some(self.cxx.borrow()[&target].path().into())
1328 } else if !self.is_builder_target(target)
1329 && helpers::use_host_linker(target)
1330 && !target.is_msvc()
1331 {
1332 Some(self.cc(target))
1333 } else if self.config.lld_mode.is_used()
1334 && self.is_lld_direct_linker(target)
1335 && self.build == target
1336 {
1337 match self.config.lld_mode {
1338 LldMode::SelfContained => Some(self.initial_lld.clone()),
1339 LldMode::External => Some("lld".into()),
1340 LldMode::Unused => None,
1341 }
1342 } else {
1343 None
1344 }
1345 }
1346
1347 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1350 target.is_msvc()
1351 }
1352
1353 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1355 if target.contains("pc-windows-msvc") {
1356 Some(true)
1357 } else {
1358 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1359 }
1360 }
1361
1362 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1364 self.config
1365 .target_config
1366 .get(&target)
1367 .and_then(|t| t.musl_root.as_ref())
1368 .or(self.config.musl_root.as_ref())
1369 .map(|p| &**p)
1370 }
1371
1372 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1374 let t = self.config.target_config.get(&target)?;
1375 if let libdir @ Some(_) = &t.musl_libdir {
1376 return libdir.clone();
1377 }
1378 self.musl_root(target).map(|root| root.join("lib"))
1379 }
1380
1381 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1388 let configured =
1389 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1390 if let Some(path) = configured {
1391 return Some(path.join("lib").join(target.to_string()));
1392 }
1393 let mut env_root = PathBuf::from(std::env::var_os("WASI_SDK_PATH")?);
1394 env_root.push("share");
1395 env_root.push("wasi-sysroot");
1396 env_root.push("lib");
1397 env_root.push(target.to_string());
1398 Some(env_root)
1399 }
1400
1401 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1403 self.config.target_config.get(&target).map(|t| t.no_std)
1404 }
1405
1406 fn remote_tested(&self, target: TargetSelection) -> bool {
1409 self.qemu_rootfs(target).is_some()
1410 || target.contains("android")
1411 || env::var_os("TEST_DEVICE_ADDR").is_some()
1412 }
1413
1414 fn runner(&self, target: TargetSelection) -> Option<String> {
1420 let configured_runner =
1421 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1422 if let Some(runner) = configured_runner {
1423 return Some(runner.to_owned());
1424 }
1425
1426 if target.starts_with("wasm") && target.contains("wasi") {
1427 self.default_wasi_runner(target)
1428 } else {
1429 None
1430 }
1431 }
1432
1433 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1437 let mut finder = crate::core::sanity::Finder::new();
1438
1439 if let Some(path) = finder.maybe_have("wasmtime") {
1443 if let Ok(mut path) = path.into_os_string().into_string() {
1444 path.push_str(" run -C cache=n --dir .");
1445 path.push_str(" --env RUSTC_BOOTSTRAP");
1452
1453 if target.contains("wasip2") {
1454 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1455 }
1456
1457 return Some(path);
1458 }
1459 }
1460
1461 None
1462 }
1463
1464 fn tool_enabled(&self, tool: &str) -> bool {
1469 if !self.config.extended {
1470 return false;
1471 }
1472 match &self.config.tools {
1473 Some(set) => set.contains(tool),
1474 None => true,
1475 }
1476 }
1477
1478 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1484 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1485 }
1486
1487 fn python(&self) -> &Path {
1489 if self.config.build.ends_with("apple-darwin") {
1490 Path::new("/usr/bin/python3")
1494 } else {
1495 self.config
1496 .python
1497 .as_ref()
1498 .expect("python is required for running LLDB or rustdoc tests")
1499 }
1500 }
1501
1502 fn extended_error_dir(&self) -> PathBuf {
1504 self.out.join("tmp/extended-error-metadata")
1505 }
1506
1507 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1526 !self.config.full_bootstrap
1527 && !self.config.download_rustc()
1528 && stage >= 2
1529 && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1530 }
1531
1532 fn force_use_stage2(&self, stage: u32) -> bool {
1538 self.config.download_rustc() && stage >= 2
1539 }
1540
1541 fn release(&self, num: &str) -> String {
1547 match &self.config.channel[..] {
1548 "stable" => num.to_string(),
1549 "beta" => {
1550 if !self.config.omit_git_hash {
1551 format!("{}-beta.{}", num, self.beta_prerelease_version())
1552 } else {
1553 format!("{num}-beta")
1554 }
1555 }
1556 "nightly" => format!("{num}-nightly"),
1557 _ => format!("{num}-dev"),
1558 }
1559 }
1560
1561 fn beta_prerelease_version(&self) -> u32 {
1562 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1563 let version = fs::read_to_string(version_file).ok()?;
1564
1565 helpers::extract_beta_rev(&version)
1566 }
1567
1568 if let Some(s) = self.prerelease_version.get() {
1569 return s;
1570 }
1571
1572 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1576 helpers::git(Some(&self.src))
1580 .arg("rev-list")
1581 .arg("--count")
1582 .arg("--merges")
1583 .arg(format!(
1584 "refs/remotes/origin/{}..HEAD",
1585 self.config.stage0_metadata.config.nightly_branch
1586 ))
1587 .run_always()
1588 .run_capture(self)
1589 .stdout()
1590 });
1591 let n = count.trim().parse().unwrap();
1592 self.prerelease_version.set(Some(n));
1593 n
1594 }
1595
1596 fn rust_release(&self) -> String {
1598 self.release(&self.version)
1599 }
1600
1601 fn package_vers(&self, num: &str) -> String {
1608 match &self.config.channel[..] {
1609 "stable" => num.to_string(),
1610 "beta" => "beta".to_string(),
1611 "nightly" => "nightly".to_string(),
1612 _ => format!("{num}-dev"),
1613 }
1614 }
1615
1616 fn rust_package_vers(&self) -> String {
1618 self.package_vers(&self.version)
1619 }
1620
1621 fn rust_version(&self) -> String {
1627 let mut version = self.rust_info().version(self, &self.version);
1628 if let Some(ref s) = self.config.description {
1629 if !s.is_empty() {
1630 version.push_str(" (");
1631 version.push_str(s);
1632 version.push(')');
1633 }
1634 }
1635 version
1636 }
1637
1638 fn rust_sha(&self) -> Option<&str> {
1640 self.rust_info().sha()
1641 }
1642
1643 fn release_num(&self, package: &str) -> String {
1645 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1646 let toml = t!(fs::read_to_string(toml_file_name));
1647 for line in toml.lines() {
1648 if let Some(stripped) =
1649 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1650 {
1651 return stripped.to_owned();
1652 }
1653 }
1654
1655 panic!("failed to find version in {package}'s Cargo.toml")
1656 }
1657
1658 fn unstable_features(&self) -> bool {
1661 !matches!(&self.config.channel[..], "stable" | "beta")
1662 }
1663
1664 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1668 let mut ret = Vec::new();
1669 let mut list = vec![root.to_owned()];
1670 let mut visited = HashSet::new();
1671 while let Some(krate) = list.pop() {
1672 let krate = self
1673 .crates
1674 .get(&krate)
1675 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1676 ret.push(krate);
1677 for dep in &krate.deps {
1678 if !self.crates.contains_key(dep) {
1679 continue;
1681 }
1682 if visited.insert(dep)
1688 && (dep != "profiler_builtins"
1689 || target
1690 .map(|t| self.config.profiler_enabled(t))
1691 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1692 && (dep != "rustc_codegen_llvm"
1693 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1694 {
1695 list.push(dep.clone());
1696 }
1697 }
1698 }
1699 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1701 }
1702
1703 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1704 if self.config.dry_run() {
1705 return Vec::new();
1706 }
1707
1708 if !stamp.path().exists() {
1709 eprintln!(
1710 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1711 stamp.path().display()
1712 );
1713 crate::exit!(1);
1714 }
1715
1716 let mut paths = Vec::new();
1717 let contents = t!(fs::read(stamp.path()), stamp.path());
1718 for part in contents.split(|b| *b == 0) {
1721 if part.is_empty() {
1722 continue;
1723 }
1724 let dependency_type = match part[0] as char {
1725 'h' => DependencyType::Host,
1726 's' => DependencyType::TargetSelfContained,
1727 't' => DependencyType::Target,
1728 _ => unreachable!(),
1729 };
1730 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1731 paths.push((path, dependency_type));
1732 }
1733 paths
1734 }
1735
1736 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1741 self.copy_link_internal(src, dst, true);
1742 }
1743
1744 pub fn copy_link(&self, src: &Path, dst: &Path) {
1749 self.copy_link_internal(src, dst, false);
1750 }
1751
1752 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1753 if self.config.dry_run() {
1754 return;
1755 }
1756 self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1757 if src == dst {
1758 return;
1759 }
1760 if let Err(e) = fs::remove_file(dst) {
1761 if cfg!(windows) && e.kind() != io::ErrorKind::NotFound {
1762 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1765 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1766 }
1767 }
1768 let metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1769 let mut src = src.to_path_buf();
1770 if metadata.file_type().is_symlink() {
1771 if dereference_symlinks {
1772 src = t!(fs::canonicalize(src));
1773 } else {
1774 let link = t!(fs::read_link(src));
1775 t!(self.symlink_file(link, dst));
1776 return;
1777 }
1778 }
1779 if let Ok(()) = fs::hard_link(&src, dst) {
1780 } else {
1783 if let Err(e) = fs::copy(&src, dst) {
1784 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1785 }
1786 t!(fs::set_permissions(dst, metadata.permissions()));
1787
1788 let file_times = fs::FileTimes::new()
1791 .set_accessed(t!(metadata.accessed()))
1792 .set_modified(t!(metadata.modified()));
1793 t!(set_file_times(dst, file_times));
1794 }
1795 }
1796
1797 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1801 if self.config.dry_run() {
1802 return;
1803 }
1804 for f in self.read_dir(src) {
1805 let path = f.path();
1806 let name = path.file_name().unwrap();
1807 let dst = dst.join(name);
1808 if t!(f.file_type()).is_dir() {
1809 t!(fs::create_dir_all(&dst));
1810 self.cp_link_r(&path, &dst);
1811 } else {
1812 self.copy_link(&path, &dst);
1813 }
1814 }
1815 }
1816
1817 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1823 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1825 }
1826
1827 fn cp_link_filtered_recurse(
1829 &self,
1830 src: &Path,
1831 dst: &Path,
1832 relative: &Path,
1833 filter: &dyn Fn(&Path) -> bool,
1834 ) {
1835 for f in self.read_dir(src) {
1836 let path = f.path();
1837 let name = path.file_name().unwrap();
1838 let dst = dst.join(name);
1839 let relative = relative.join(name);
1840 if filter(&relative) {
1842 if t!(f.file_type()).is_dir() {
1843 let _ = fs::remove_dir_all(&dst);
1844 self.create_dir(&dst);
1845 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1846 } else {
1847 let _ = fs::remove_file(&dst);
1848 self.copy_link(&path, &dst);
1849 }
1850 }
1851 }
1852 }
1853
1854 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1855 let file_name = src.file_name().unwrap();
1856 let dest = dest_folder.join(file_name);
1857 self.copy_link(src, &dest);
1858 }
1859
1860 fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1861 if self.config.dry_run() {
1862 return;
1863 }
1864 let dst = dstdir.join(src.file_name().unwrap());
1865 self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1866 t!(fs::create_dir_all(dstdir));
1867 if !src.exists() {
1868 panic!("ERROR: File \"{}\" not found!", src.display());
1869 }
1870 self.copy_link_internal(src, &dst, true);
1871 chmod(&dst, perms);
1872 }
1873
1874 fn read(&self, path: &Path) -> String {
1875 if self.config.dry_run() {
1876 return String::new();
1877 }
1878 t!(fs::read_to_string(path))
1879 }
1880
1881 fn create_dir(&self, dir: &Path) {
1882 if self.config.dry_run() {
1883 return;
1884 }
1885 t!(fs::create_dir_all(dir))
1886 }
1887
1888 fn remove_dir(&self, dir: &Path) {
1889 if self.config.dry_run() {
1890 return;
1891 }
1892 t!(fs::remove_dir_all(dir))
1893 }
1894
1895 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1896 let iter = match fs::read_dir(dir) {
1897 Ok(v) => v,
1898 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1899 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1900 };
1901 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1902 }
1903
1904 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1905 #[cfg(unix)]
1906 use std::os::unix::fs::symlink as symlink_file;
1907 #[cfg(windows)]
1908 use std::os::windows::fs::symlink_file;
1909 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1910 }
1911
1912 fn ninja(&self) -> bool {
1915 let mut cmd_finder = crate::core::sanity::Finder::new();
1916
1917 if self.config.ninja_in_file {
1918 if cmd_finder.maybe_have("ninja-build").is_none()
1921 && cmd_finder.maybe_have("ninja").is_none()
1922 {
1923 eprintln!(
1924 "
1925Couldn't find required command: ninja (or ninja-build)
1926
1927You should install ninja as described at
1928<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1929or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
1930Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1931to download LLVM rather than building it.
1932"
1933 );
1934 exit!(1);
1935 }
1936 }
1937
1938 if !self.config.ninja_in_file
1946 && self.config.build.is_msvc()
1947 && cmd_finder.maybe_have("ninja").is_some()
1948 {
1949 return true;
1950 }
1951
1952 self.config.ninja_in_file
1953 }
1954
1955 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1956 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1957 }
1958
1959 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1960 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1961 }
1962
1963 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1964 where
1965 C: Fn(ColorChoice) -> StandardStream,
1966 F: FnOnce(&mut dyn WriteColor) -> R,
1967 {
1968 let choice = match self.config.color {
1969 flags::Color::Always => ColorChoice::Always,
1970 flags::Color::Never => ColorChoice::Never,
1971 flags::Color::Auto if !is_tty => ColorChoice::Never,
1972 flags::Color::Auto => ColorChoice::Auto,
1973 };
1974 let mut stream = constructor(choice);
1975 let result = f(&mut stream);
1976 stream.reset().unwrap();
1977 result
1978 }
1979
1980 fn is_builder_target(&self, target: TargetSelection) -> bool {
1982 self.config.build == target
1983 }
1984}
1985
1986#[cfg(unix)]
1987fn chmod(path: &Path, perms: u32) {
1988 use std::os::unix::fs::*;
1989 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1990}
1991#[cfg(windows)]
1992fn chmod(_path: &Path, _perms: u32) {}
1993
1994impl Compiler {
1995 pub fn new(stage: u32, host: TargetSelection) -> Self {
1996 Self { stage, host, forced_compiler: false }
1997 }
1998
1999 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2000 self.forced_compiler = forced_compiler;
2001 }
2002
2003 pub fn with_stage(mut self, stage: u32) -> Compiler {
2004 self.stage = stage;
2005 self
2006 }
2007
2008 pub fn is_snapshot(&self, build: &Build) -> bool {
2010 self.stage == 0 && self.host == build.build
2011 }
2012
2013 pub fn is_forced_compiler(&self) -> bool {
2015 self.forced_compiler
2016 }
2017}
2018
2019fn envify(s: &str) -> String {
2020 s.chars()
2021 .map(|c| match c {
2022 '-' => '_',
2023 c => c,
2024 })
2025 .flat_map(|c| c.to_uppercase())
2026 .collect()
2027}
2028
2029pub fn prepare_behaviour_dump_dir(build: &Build) {
2031 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2032
2033 let dump_path = build.out.join("bootstrap-shims-dump");
2034
2035 let initialized = INITIALIZED.get().unwrap_or(&false);
2036 if !initialized {
2037 if dump_path.exists() {
2039 t!(fs::remove_dir_all(&dump_path));
2040 }
2041
2042 t!(fs::create_dir_all(&dump_path));
2043
2044 t!(INITIALIZED.set(true));
2045 }
2046}