1#![cfg_attr(test, allow(unused))]
19
20use std::cell::Cell;
21use std::collections::{BTreeSet, HashMap, HashSet};
22use std::fmt::Display;
23use std::path::{Path, PathBuf};
24use std::sync::OnceLock;
25use std::time::{Instant, SystemTime};
26use std::{env, fs, io, str};
27
28use build_helper::ci::gha;
29use build_helper::exit;
30use cc::Tool;
31use termcolor::{ColorChoice, StandardStream, WriteColor};
32use utils::build_stamp::BuildStamp;
33use utils::channel::GitInfo;
34use utils::exec::ExecutionContext;
35
36use crate::core::builder;
37use crate::core::builder::Kind;
38use crate::core::config::{DryRun, LldMode, LlvmLibunwind, TargetSelection, flags};
39use crate::utils::exec::{BootstrapCommand, command};
40use crate::utils::helpers::{
41 self, dir_is_empty, exe, libdir, set_file_times, split_debuginfo, symlink_dir,
42};
43
44mod core;
45mod utils;
46
47pub use core::builder::PathSet;
48pub use core::config::flags::{Flags, Subcommand};
49pub use core::config::{ChangeId, Config};
50
51#[cfg(feature = "tracing")]
52use tracing::{instrument, span};
53pub use utils::change_tracker::{
54 CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
55};
56pub use utils::helpers::PanicTracker;
57
58use crate::core::build_steps::vendor::VENDOR_DIR;
59
60const LLVM_TOOLS: &[&str] = &[
61 "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", ];
76
77const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
79
80#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
84 (Some(Mode::Rustc), "bootstrap", None),
85 (Some(Mode::Codegen), "bootstrap", None),
86 (Some(Mode::ToolRustc), "bootstrap", None),
87 (Some(Mode::ToolStd), "bootstrap", None),
88 (Some(Mode::Rustc), "llvm_enzyme", None),
89 (Some(Mode::Codegen), "llvm_enzyme", None),
90 (Some(Mode::ToolRustc), "llvm_enzyme", None),
91 (Some(Mode::ToolRustc), "rust_analyzer", None),
92 (Some(Mode::ToolStd), "rust_analyzer", None),
93 ];
97
98#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
104pub struct Compiler {
105 stage: u32,
106 host: TargetSelection,
107 forced_compiler: bool,
111}
112
113impl std::hash::Hash for Compiler {
114 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
115 self.stage.hash(state);
116 self.host.hash(state);
117 }
118}
119
120impl PartialEq for Compiler {
121 fn eq(&self, other: &Self) -> bool {
122 self.stage == other.stage && self.host == other.host
123 }
124}
125
126#[derive(PartialEq, Eq, Copy, Clone, Debug)]
127pub enum DocTests {
128 Yes,
130 No,
132 Only,
134}
135
136pub enum GitRepo {
137 Rustc,
138 Llvm,
139}
140
141#[derive(Clone)]
152pub struct Build {
153 config: Config,
155
156 version: String,
158
159 src: PathBuf,
161 out: PathBuf,
162 bootstrap_out: PathBuf,
163 cargo_info: GitInfo,
164 rust_analyzer_info: GitInfo,
165 clippy_info: GitInfo,
166 miri_info: GitInfo,
167 rustfmt_info: GitInfo,
168 enzyme_info: GitInfo,
169 in_tree_llvm_info: GitInfo,
170 in_tree_gcc_info: GitInfo,
171 local_rebuild: bool,
172 fail_fast: bool,
173 doc_tests: DocTests,
174 verbosity: usize,
175
176 host_target: TargetSelection,
178 hosts: Vec<TargetSelection>,
180 targets: Vec<TargetSelection>,
182
183 initial_rustc: PathBuf,
184 initial_rustdoc: PathBuf,
185 initial_cargo: PathBuf,
186 initial_lld: PathBuf,
187 initial_relative_libdir: PathBuf,
188 initial_sysroot: PathBuf,
189
190 cc: HashMap<TargetSelection, cc::Tool>,
193 cxx: HashMap<TargetSelection, cc::Tool>,
194 ar: HashMap<TargetSelection, PathBuf>,
195 ranlib: HashMap<TargetSelection, PathBuf>,
196 wasi_sdk_path: Option<PathBuf>,
197
198 crates: HashMap<String, Crate>,
201 crate_paths: HashMap<PathBuf, String>,
202 is_sudo: bool,
203 prerelease_version: Cell<Option<u32>>,
204
205 #[cfg(feature = "build-metrics")]
206 metrics: crate::utils::metrics::BuildMetrics,
207}
208
209#[derive(Debug, Clone)]
210struct Crate {
211 name: String,
212 deps: HashSet<String>,
213 path: PathBuf,
214 features: Vec<String>,
215}
216
217impl Crate {
218 fn local_path(&self, build: &Build) -> PathBuf {
219 self.path.strip_prefix(&build.config.src).unwrap().into()
220 }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
225pub enum DependencyType {
226 Host,
228 Target,
230 TargetSelfContained,
232}
233
234#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
239pub enum Mode {
240 Std,
242
243 Rustc,
245
246 Codegen,
248
249 ToolBootstrap,
261
262 ToolStd,
266
267 ToolRustc,
272}
273
274impl Mode {
275 pub fn is_tool(&self) -> bool {
276 matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
277 }
278
279 pub fn must_support_dlopen(&self) -> bool {
280 matches!(self, Mode::Std | Mode::Codegen)
281 }
282}
283
284pub enum RemapScheme {
288 Compiler,
290 NonCompiler,
292}
293
294#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
295pub enum CLang {
296 C,
297 Cxx,
298}
299
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum FileType {
302 Executable,
304 NativeLibrary,
306 Script,
308 Regular,
310}
311
312impl FileType {
313 pub fn perms(self) -> u32 {
315 match self {
316 FileType::Executable | FileType::Script => 0o755,
317 FileType::Regular | FileType::NativeLibrary => 0o644,
318 }
319 }
320
321 pub fn could_have_split_debuginfo(self) -> bool {
322 match self {
323 FileType::Executable | FileType::NativeLibrary => true,
324 FileType::Script | FileType::Regular => false,
325 }
326 }
327}
328
329macro_rules! forward {
330 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
331 impl Build {
332 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
333 self.config.$fn( $($param),* )
334 } )+
335 }
336 }
337}
338
339forward! {
340 verbose(f: impl Fn()),
341 is_verbose() -> bool,
342 create(path: &Path, s: &str),
343 remove(f: &Path),
344 tempdir() -> PathBuf,
345 llvm_link_shared() -> bool,
346 download_rustc() -> bool,
347}
348
349impl Build {
350 pub fn new(mut config: Config) -> Build {
355 let src = config.src.clone();
356 let out = config.out.clone();
357
358 #[cfg(unix)]
359 let is_sudo = match env::var_os("SUDO_USER") {
362 Some(_sudo_user) => {
363 let uid = unsafe { libc::getuid() };
368 uid == 0
369 }
370 None => false,
371 };
372 #[cfg(not(unix))]
373 let is_sudo = false;
374
375 let rust_info = config.rust_info.clone();
376 let cargo_info = config.cargo_info.clone();
377 let rust_analyzer_info = config.rust_analyzer_info.clone();
378 let clippy_info = config.clippy_info.clone();
379 let miri_info = config.miri_info.clone();
380 let rustfmt_info = config.rustfmt_info.clone();
381 let enzyme_info = config.enzyme_info.clone();
382 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
383 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
384
385 let initial_target_libdir = command(&config.initial_rustc)
386 .run_in_dry_run()
387 .args(["--print", "target-libdir"])
388 .run_capture_stdout(&config)
389 .stdout()
390 .trim()
391 .to_owned();
392
393 let initial_target_dir = Path::new(&initial_target_libdir)
394 .parent()
395 .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent"));
396
397 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
398
399 let initial_relative_libdir = if cfg!(test) {
400 PathBuf::default()
402 } else {
403 let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
404 panic!("Not enough ancestors for {}", initial_target_dir.display())
405 });
406
407 ancestor
408 .strip_prefix(&config.initial_sysroot)
409 .unwrap_or_else(|_| {
410 panic!(
411 "Couldn’t resolve the initial relative libdir from {}",
412 initial_target_dir.display()
413 )
414 })
415 .to_path_buf()
416 };
417
418 let version = std::fs::read_to_string(src.join("src").join("version"))
419 .expect("failed to read src/version");
420 let version = version.trim();
421
422 let mut bootstrap_out = std::env::current_exe()
423 .expect("could not determine path to running process")
424 .parent()
425 .unwrap()
426 .to_path_buf();
427 if bootstrap_out.ends_with("deps") {
430 bootstrap_out.pop();
431 }
432 if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
433 panic!(
435 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
436 bootstrap_out.display()
437 )
438 }
439
440 if rust_info.is_from_tarball() && config.description.is_none() {
441 config.description = Some("built from a source tarball".to_owned());
442 }
443
444 let mut build = Build {
445 initial_lld,
446 initial_relative_libdir,
447 initial_rustc: config.initial_rustc.clone(),
448 initial_rustdoc: config
449 .initial_rustc
450 .with_file_name(exe("rustdoc", config.host_target)),
451 initial_cargo: config.initial_cargo.clone(),
452 initial_sysroot: config.initial_sysroot.clone(),
453 local_rebuild: config.local_rebuild,
454 fail_fast: config.cmd.fail_fast(),
455 doc_tests: config.cmd.doc_tests(),
456 verbosity: config.verbose,
457
458 host_target: config.host_target,
459 hosts: config.hosts.clone(),
460 targets: config.targets.clone(),
461
462 config,
463 version: version.to_string(),
464 src,
465 out,
466 bootstrap_out,
467
468 cargo_info,
469 rust_analyzer_info,
470 clippy_info,
471 miri_info,
472 rustfmt_info,
473 enzyme_info,
474 in_tree_llvm_info,
475 in_tree_gcc_info,
476 cc: HashMap::new(),
477 cxx: HashMap::new(),
478 ar: HashMap::new(),
479 ranlib: HashMap::new(),
480 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
481 crates: HashMap::new(),
482 crate_paths: HashMap::new(),
483 is_sudo,
484 prerelease_version: Cell::new(None),
485
486 #[cfg(feature = "build-metrics")]
487 metrics: crate::utils::metrics::BuildMetrics::init(),
488 };
489
490 let local_version_verbose = command(&build.initial_rustc)
493 .run_in_dry_run()
494 .args(["--version", "--verbose"])
495 .run_capture_stdout(&build)
496 .stdout();
497 let local_release = local_version_verbose
498 .lines()
499 .filter_map(|x| x.strip_prefix("release:"))
500 .next()
501 .unwrap()
502 .trim();
503 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
504 build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
505 build.local_rebuild = true;
506 }
507
508 build.verbose(|| println!("finding compilers"));
509 utils::cc_detect::fill_compilers(&mut build);
510 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
516 build.verbose(|| println!("running sanity check"));
517 crate::core::sanity::check(&mut build);
518
519 let rust_submodules = ["library/backtrace"];
522 for s in rust_submodules {
523 build.require_submodule(
524 s,
525 Some(
526 "The submodule is required for the standard library \
527 and the main Cargo workspace.",
528 ),
529 );
530 }
531 build.update_existing_submodules();
533
534 build.verbose(|| println!("learning about cargo"));
535 crate::core::metadata::build(&mut build);
536 }
537
538 let build_triple = build.out.join(build.host_target);
540 t!(fs::create_dir_all(&build_triple));
541 let host = build.out.join("host");
542 if host.is_symlink() {
543 #[cfg(windows)]
546 t!(fs::remove_dir(&host));
547 #[cfg(not(windows))]
548 t!(fs::remove_file(&host));
549 }
550 t!(
551 symlink_dir(&build.config, &build_triple, &host),
552 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
553 );
554
555 build
556 }
557
558 #[cfg_attr(
567 feature = "tracing",
568 instrument(
569 level = "trace",
570 name = "Build::require_submodule",
571 skip_all,
572 fields(submodule = submodule),
573 ),
574 )]
575 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
576 if self.rust_info().is_from_tarball() {
577 return;
578 }
579
580 if cfg!(test) && !self.config.submodules() {
583 return;
584 }
585 self.config.update_submodule(submodule);
586 let absolute_path = self.config.src.join(submodule);
587 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
588 let maybe_enable = if !self.config.submodules()
589 && self.config.rust_info.is_managed_git_subrepository()
590 {
591 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
592 } else {
593 ""
594 };
595 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
596 eprintln!(
597 "submodule {submodule} does not appear to be checked out, \
598 but it is required for this step{maybe_enable}{err_hint}"
599 );
600 exit!(1);
601 }
602 }
603
604 fn update_existing_submodules(&self) {
607 if !self.config.submodules() {
610 return;
611 }
612 let output = helpers::git(Some(&self.src))
613 .args(["config", "--file"])
614 .arg(".gitmodules")
615 .args(["--get-regexp", "path"])
616 .run_capture(self)
617 .stdout();
618 std::thread::scope(|s| {
619 for line in output.lines() {
622 let submodule = line.split_once(' ').unwrap().1;
623 let config = self.config.clone();
624 s.spawn(move || {
625 Self::update_existing_submodule(&config, submodule);
626 });
627 }
628 });
629 }
630
631 pub fn update_existing_submodule(config: &Config, submodule: &str) {
633 if !config.submodules() {
635 return;
636 }
637
638 if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
639 config.update_submodule(submodule);
640 }
641 }
642
643 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
645 pub fn build(&mut self) {
646 trace!("setting up job management");
647 unsafe {
648 crate::utils::job::setup(self);
649 }
650
651 {
653 #[cfg(feature = "tracing")]
654 let _hardcoded_span =
655 span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
656 .entered();
657
658 match &self.config.cmd {
659 Subcommand::Format { check, all } => {
660 return core::build_steps::format::format(
661 &builder::Builder::new(self),
662 *check,
663 *all,
664 &self.config.paths,
665 );
666 }
667 Subcommand::Perf(args) => {
668 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
669 }
670 _cmd => {
671 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
672 }
673 }
674
675 debug!("handling subcommand normally");
676 }
677
678 if !self.config.dry_run() {
679 #[cfg(feature = "tracing")]
680 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
681
682 {
685 #[cfg(feature = "tracing")]
686 let _sanity_check_span =
687 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
688 self.config.set_dry_run(DryRun::SelfCheck);
689 let builder = builder::Builder::new(self);
690 builder.execute_cli();
691 }
692
693 {
695 #[cfg(feature = "tracing")]
696 let _actual_run_span =
697 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
698 self.config.set_dry_run(DryRun::Disabled);
699 let builder = builder::Builder::new(self);
700 builder.execute_cli();
701 }
702 } else {
703 #[cfg(feature = "tracing")]
704 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
705
706 let builder = builder::Builder::new(self);
707 builder.execute_cli();
708 }
709
710 #[cfg(feature = "tracing")]
711 debug!("checking for postponed test failures from `test --no-fail-fast`");
712
713 self.config.exec_ctx().report_failures_and_exit();
715
716 #[cfg(feature = "build-metrics")]
717 self.metrics.persist(self);
718 }
719
720 fn rust_info(&self) -> &GitInfo {
721 &self.config.rust_info
722 }
723
724 fn std_features(&self, target: TargetSelection) -> String {
727 let mut features: BTreeSet<&str> =
728 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
729
730 match self.config.llvm_libunwind(target) {
731 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
732 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
733 LlvmLibunwind::No => false,
734 };
735
736 if self.config.backtrace {
737 features.insert("backtrace");
738 }
739
740 if self.config.profiler_enabled(target) {
741 features.insert("profiler");
742 }
743
744 if target.contains("zkvm") {
746 features.insert("compiler-builtins-mem");
747 }
748
749 features.into_iter().collect::<Vec<_>>().join(" ")
750 }
751
752 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
754 let possible_features_by_crates: HashSet<_> = crates
755 .iter()
756 .flat_map(|krate| &self.crates[krate].features)
757 .map(std::ops::Deref::deref)
758 .collect();
759 let check = |feature: &str| -> bool {
760 crates.is_empty() || possible_features_by_crates.contains(feature)
761 };
762 let mut features = vec![];
763 if self.config.jemalloc(target) && check("jemalloc") {
764 features.push("jemalloc");
765 }
766 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
767 features.push("llvm");
768 }
769 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
771 features.push("rustc_randomized_layouts");
772 }
773 if self.config.compile_time_deps && kind == Kind::Check {
774 features.push("check_only");
775 }
776
777 if !self.config.rust_debug_logging && check("max_level_info") {
783 features.push("max_level_info");
784 }
785
786 features.join(" ")
787 }
788
789 fn cargo_dir(&self) -> &'static str {
792 if self.config.rust_optimize.is_release() { "release" } else { "debug" }
793 }
794
795 fn tools_dir(&self, compiler: Compiler) -> PathBuf {
796 let out = self.out.join(compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
797 t!(fs::create_dir_all(&out));
798 out
799 }
800
801 fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
806 let suffix = match mode {
807 Mode::Std => "-std",
808 Mode::Rustc => "-rustc",
809 Mode::Codegen => "-codegen",
810 Mode::ToolBootstrap => {
811 return self.out.join(compiler.host).join("bootstrap-tools");
812 }
813 Mode::ToolStd | Mode::ToolRustc => "-tools",
814 };
815 self.out.join(compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
816 }
817
818 fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
822 self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
823 }
824
825 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
830 if self.config.llvm_from_ci && self.config.is_host_target(target) {
831 self.config.ci_llvm_root()
832 } else {
833 self.out.join(target).join("llvm")
834 }
835 }
836
837 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
838 self.out.join(&*target.triple).join("enzyme")
839 }
840
841 fn gcc_out(&self, target: TargetSelection) -> PathBuf {
842 self.out.join(&*target.triple).join("gcc")
843 }
844
845 fn lld_out(&self, target: TargetSelection) -> PathBuf {
846 self.out.join(target).join("lld")
847 }
848
849 fn doc_out(&self, target: TargetSelection) -> PathBuf {
851 self.out.join(target).join("doc")
852 }
853
854 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
856 self.out.join(target).join("json-doc")
857 }
858
859 fn test_out(&self, target: TargetSelection) -> PathBuf {
860 self.out.join(target).join("test")
861 }
862
863 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
865 self.out.join(target).join("compiler-doc")
866 }
867
868 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
870 self.out.join(target).join("md-doc")
871 }
872
873 fn vendored_crates_path(&self) -> Option<PathBuf> {
875 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
876 }
877
878 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
880 let target_config = self.config.target_config.get(&target);
881 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
882 s.to_path_buf()
883 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
884 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
885 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
886 if filecheck.exists() {
887 filecheck
888 } else {
889 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
892 let lib_filecheck =
893 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
894 if lib_filecheck.exists() {
895 lib_filecheck
896 } else {
897 filecheck
901 }
902 }
903 } else {
904 let base = self.llvm_out(target).join("build");
905 let base = if !self.ninja() && target.is_msvc() {
906 if self.config.llvm_optimize {
907 if self.config.llvm_release_debuginfo {
908 base.join("RelWithDebInfo")
909 } else {
910 base.join("Release")
911 }
912 } else {
913 base.join("Debug")
914 }
915 } else {
916 base
917 };
918 base.join("bin").join(exe("FileCheck", target))
919 }
920 }
921
922 fn native_dir(&self, target: TargetSelection) -> PathBuf {
924 self.out.join(target).join("native")
925 }
926
927 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
930 self.native_dir(target).join("rust-test-helpers")
931 }
932
933 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
935 if env::var_os("RUST_TEST_THREADS").is_none() {
936 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
937 }
938 }
939
940 fn rustc_snapshot_libdir(&self) -> PathBuf {
942 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
943 }
944
945 fn rustc_snapshot_sysroot(&self) -> &Path {
947 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
948 SYSROOT_CACHE.get_or_init(|| {
949 command(&self.initial_rustc)
950 .run_in_dry_run()
951 .args(["--print", "sysroot"])
952 .run_capture_stdout(self)
953 .stdout()
954 .trim()
955 .to_owned()
956 .into()
957 })
958 }
959
960 pub fn is_verbose_than(&self, level: usize) -> bool {
962 self.verbosity > level
963 }
964
965 fn verbose_than(&self, level: usize, f: impl Fn()) {
967 if self.is_verbose_than(level) {
968 f()
969 }
970 }
971
972 fn info(&self, msg: &str) {
973 match self.config.get_dry_run() {
974 DryRun::SelfCheck => (),
975 DryRun::Disabled | DryRun::UserSelected => {
976 println!("{msg}");
977 }
978 }
979 }
980
981 #[must_use = "Groups should not be dropped until the Step finishes running"]
982 #[track_caller]
983 fn msg_clippy(
984 &self,
985 what: impl Display,
986 target: impl Into<Option<TargetSelection>>,
987 ) -> Option<gha::Group> {
988 self.msg(Kind::Clippy, self.config.stage, what, self.config.host_target, target)
989 }
990
991 #[must_use = "Groups should not be dropped until the Step finishes running"]
992 #[track_caller]
993 fn msg_check(
994 &self,
995 what: impl Display,
996 target: impl Into<Option<TargetSelection>>,
997 custom_stage: Option<u32>,
998 ) -> Option<gha::Group> {
999 self.msg(
1000 Kind::Check,
1001 custom_stage.unwrap_or(self.config.stage),
1002 what,
1003 self.config.host_target,
1004 target,
1005 )
1006 }
1007
1008 #[must_use = "Groups should not be dropped until the Step finishes running"]
1009 #[track_caller]
1010 fn msg_doc(
1011 &self,
1012 compiler: Compiler,
1013 what: impl Display,
1014 target: impl Into<Option<TargetSelection>> + Copy,
1015 ) -> Option<gha::Group> {
1016 self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into())
1017 }
1018
1019 #[must_use = "Groups should not be dropped until the Step finishes running"]
1020 #[track_caller]
1021 fn msg_build(
1022 &self,
1023 compiler: Compiler,
1024 what: impl Display,
1025 target: impl Into<Option<TargetSelection>>,
1026 ) -> Option<gha::Group> {
1027 self.msg(Kind::Build, compiler.stage, what, compiler.host, target)
1028 }
1029
1030 #[must_use = "Groups should not be dropped until the Step finishes running"]
1034 #[track_caller]
1035 fn msg(
1036 &self,
1037 action: impl Into<Kind>,
1038 stage: u32,
1039 what: impl Display,
1040 host: impl Into<Option<TargetSelection>>,
1041 target: impl Into<Option<TargetSelection>>,
1042 ) -> Option<gha::Group> {
1043 let action = action.into().description();
1044 let msg = |fmt| format!("{action} stage{stage} {what}{fmt}");
1045 let msg = if let Some(target) = target.into() {
1046 let host = host.into().unwrap();
1047 if host == target {
1048 msg(format_args!(" ({target})"))
1049 } else {
1050 msg(format_args!(" ({host} -> {target})"))
1051 }
1052 } else {
1053 msg(format_args!(""))
1054 };
1055 self.group(&msg)
1056 }
1057
1058 #[must_use = "Groups should not be dropped until the Step finishes running"]
1062 #[track_caller]
1063 fn msg_unstaged(
1064 &self,
1065 action: impl Into<Kind>,
1066 what: impl Display,
1067 target: TargetSelection,
1068 ) -> Option<gha::Group> {
1069 let action = action.into().description();
1070 let msg = format!("{action} {what} for {target}");
1071 self.group(&msg)
1072 }
1073
1074 #[must_use = "Groups should not be dropped until the Step finishes running"]
1075 #[track_caller]
1076 fn msg_sysroot_tool(
1077 &self,
1078 action: impl Into<Kind>,
1079 stage: u32,
1080 what: impl Display,
1081 host: TargetSelection,
1082 target: TargetSelection,
1083 ) -> Option<gha::Group> {
1084 let action = action.into().description();
1085 let msg = |fmt| format!("{action} {what} {fmt}");
1086 let msg = if host == target {
1087 msg(format_args!("(stage{stage} -> stage{}, {target})", stage + 1))
1088 } else {
1089 msg(format_args!("(stage{stage}:{host} -> stage{}:{target})", stage + 1))
1090 };
1091 self.group(&msg)
1092 }
1093
1094 #[track_caller]
1095 fn group(&self, msg: &str) -> Option<gha::Group> {
1096 match self.config.get_dry_run() {
1097 DryRun::SelfCheck => None,
1098 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1099 }
1100 }
1101
1102 fn jobs(&self) -> u32 {
1105 self.config.jobs.unwrap_or_else(|| {
1106 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1107 })
1108 }
1109
1110 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1111 if !self.config.rust_remap_debuginfo {
1112 return None;
1113 }
1114
1115 match which {
1116 GitRepo::Rustc => {
1117 let sha = self.rust_sha().unwrap_or(&self.version);
1118
1119 match remap_scheme {
1120 RemapScheme::Compiler => {
1121 Some(format!("/rustc-dev/{sha}"))
1130 }
1131 RemapScheme::NonCompiler => {
1132 Some(format!("/rustc/{sha}"))
1134 }
1135 }
1136 }
1137 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1138 }
1139 }
1140
1141 fn cc(&self, target: TargetSelection) -> PathBuf {
1143 if self.config.dry_run() {
1144 return PathBuf::new();
1145 }
1146 self.cc[&target].path().into()
1147 }
1148
1149 fn cc_tool(&self, target: TargetSelection) -> Tool {
1151 self.cc[&target].clone()
1152 }
1153
1154 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1156 self.cxx[&target].clone()
1157 }
1158
1159 fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1162 if self.config.dry_run() {
1163 return Vec::new();
1164 }
1165 let base = match c {
1166 CLang::C => self.cc[&target].clone(),
1167 CLang::Cxx => self.cxx[&target].clone(),
1168 };
1169
1170 base.args()
1173 .iter()
1174 .map(|s| s.to_string_lossy().into_owned())
1175 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1176 .collect::<Vec<String>>()
1177 }
1178
1179 fn cc_unhandled_cflags(
1181 &self,
1182 target: TargetSelection,
1183 which: GitRepo,
1184 c: CLang,
1185 ) -> Vec<String> {
1186 let mut base = Vec::new();
1187
1188 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1192 base.push("-stdlib=libc++".into());
1193 }
1194
1195 if &*target.triple == "i686-pc-windows-gnu" {
1199 base.push("-fno-omit-frame-pointer".into());
1200 }
1201
1202 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1203 let map = format!("{}={}", self.src.display(), map_to);
1204 let cc = self.cc(target);
1205 if cc.ends_with("clang") || cc.ends_with("gcc") {
1206 base.push(format!("-fdebug-prefix-map={map}"));
1207 } else if cc.ends_with("clang-cl.exe") {
1208 base.push("-Xclang".into());
1209 base.push(format!("-fdebug-prefix-map={map}"));
1210 }
1211 }
1212 base
1213 }
1214
1215 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1217 if self.config.dry_run() {
1218 return None;
1219 }
1220 self.ar.get(&target).cloned()
1221 }
1222
1223 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1225 if self.config.dry_run() {
1226 return None;
1227 }
1228 self.ranlib.get(&target).cloned()
1229 }
1230
1231 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1233 if self.config.dry_run() {
1234 return Ok(PathBuf::new());
1235 }
1236 match self.cxx.get(&target) {
1237 Some(p) => Ok(p.path().into()),
1238 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1239 }
1240 }
1241
1242 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1244 if self.config.dry_run() {
1245 return Some(PathBuf::new());
1246 }
1247 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1248 {
1249 Some(linker)
1250 } else if target.contains("vxworks") {
1251 Some(self.cxx[&target].path().into())
1254 } else if !self.config.is_host_target(target)
1255 && helpers::use_host_linker(target)
1256 && !target.is_msvc()
1257 {
1258 Some(self.cc(target))
1259 } else if self.config.lld_mode.is_used()
1260 && self.is_lld_direct_linker(target)
1261 && self.host_target == target
1262 {
1263 match self.config.lld_mode {
1264 LldMode::SelfContained => Some(self.initial_lld.clone()),
1265 LldMode::External => Some("lld".into()),
1266 LldMode::Unused => None,
1267 }
1268 } else {
1269 None
1270 }
1271 }
1272
1273 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1276 target.is_msvc()
1277 }
1278
1279 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1281 if target.contains("pc-windows-msvc") {
1282 Some(true)
1283 } else {
1284 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1285 }
1286 }
1287
1288 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1290 self.config
1291 .target_config
1292 .get(&target)
1293 .and_then(|t| t.musl_root.as_ref())
1294 .or(self.config.musl_root.as_ref())
1295 .map(|p| &**p)
1296 }
1297
1298 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1300 let t = self.config.target_config.get(&target)?;
1301 if let libdir @ Some(_) = &t.musl_libdir {
1302 return libdir.clone();
1303 }
1304 self.musl_root(target).map(|root| root.join("lib"))
1305 }
1306
1307 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1314 let configured =
1315 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1316 if let Some(path) = configured {
1317 return Some(path.join("lib").join(target.to_string()));
1318 }
1319 let mut env_root = self.wasi_sdk_path.clone()?;
1320 env_root.push("share");
1321 env_root.push("wasi-sysroot");
1322 env_root.push("lib");
1323 env_root.push(target.to_string());
1324 Some(env_root)
1325 }
1326
1327 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1329 self.config.target_config.get(&target).map(|t| t.no_std)
1330 }
1331
1332 fn remote_tested(&self, target: TargetSelection) -> bool {
1335 self.qemu_rootfs(target).is_some()
1336 || target.contains("android")
1337 || env::var_os("TEST_DEVICE_ADDR").is_some()
1338 }
1339
1340 fn runner(&self, target: TargetSelection) -> Option<String> {
1346 let configured_runner =
1347 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1348 if let Some(runner) = configured_runner {
1349 return Some(runner.to_owned());
1350 }
1351
1352 if target.starts_with("wasm") && target.contains("wasi") {
1353 self.default_wasi_runner(target)
1354 } else {
1355 None
1356 }
1357 }
1358
1359 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1363 let mut finder = crate::core::sanity::Finder::new();
1364
1365 if let Some(path) = finder.maybe_have("wasmtime")
1369 && let Ok(mut path) = path.into_os_string().into_string()
1370 {
1371 path.push_str(" run -C cache=n --dir .");
1372 path.push_str(" --env RUSTC_BOOTSTRAP");
1379
1380 if target.contains("wasip2") {
1381 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1382 }
1383
1384 return Some(path);
1385 }
1386
1387 None
1388 }
1389
1390 fn tool_enabled(&self, tool: &str) -> bool {
1395 if !self.config.extended {
1396 return false;
1397 }
1398 match &self.config.tools {
1399 Some(set) => set.contains(tool),
1400 None => true,
1401 }
1402 }
1403
1404 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1410 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1411 }
1412
1413 fn python(&self) -> &Path {
1415 if self.config.host_target.ends_with("apple-darwin") {
1416 Path::new("/usr/bin/python3")
1420 } else {
1421 self.config
1422 .python
1423 .as_ref()
1424 .expect("python is required for running LLDB or rustdoc tests")
1425 }
1426 }
1427
1428 fn extended_error_dir(&self) -> PathBuf {
1430 self.out.join("tmp/extended-error-metadata")
1431 }
1432
1433 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1452 !self.config.full_bootstrap
1453 && !self.config.download_rustc()
1454 && stage >= 2
1455 && (self.hosts.contains(&target) || target == self.host_target)
1456 }
1457
1458 fn force_use_stage2(&self, stage: u32) -> bool {
1464 self.config.download_rustc() && stage >= 2
1465 }
1466
1467 fn release(&self, num: &str) -> String {
1473 match &self.config.channel[..] {
1474 "stable" => num.to_string(),
1475 "beta" => {
1476 if !self.config.omit_git_hash {
1477 format!("{}-beta.{}", num, self.beta_prerelease_version())
1478 } else {
1479 format!("{num}-beta")
1480 }
1481 }
1482 "nightly" => format!("{num}-nightly"),
1483 _ => format!("{num}-dev"),
1484 }
1485 }
1486
1487 fn beta_prerelease_version(&self) -> u32 {
1488 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1489 let version = fs::read_to_string(version_file).ok()?;
1490
1491 helpers::extract_beta_rev(&version)
1492 }
1493
1494 if let Some(s) = self.prerelease_version.get() {
1495 return s;
1496 }
1497
1498 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1502 helpers::git(Some(&self.src))
1506 .arg("rev-list")
1507 .arg("--count")
1508 .arg("--merges")
1509 .arg(format!(
1510 "refs/remotes/origin/{}..HEAD",
1511 self.config.stage0_metadata.config.nightly_branch
1512 ))
1513 .run_in_dry_run()
1514 .run_capture(self)
1515 .stdout()
1516 });
1517 let n = count.trim().parse().unwrap();
1518 self.prerelease_version.set(Some(n));
1519 n
1520 }
1521
1522 fn rust_release(&self) -> String {
1524 self.release(&self.version)
1525 }
1526
1527 fn package_vers(&self, num: &str) -> String {
1534 match &self.config.channel[..] {
1535 "stable" => num.to_string(),
1536 "beta" => "beta".to_string(),
1537 "nightly" => "nightly".to_string(),
1538 _ => format!("{num}-dev"),
1539 }
1540 }
1541
1542 fn rust_package_vers(&self) -> String {
1544 self.package_vers(&self.version)
1545 }
1546
1547 fn rust_version(&self) -> String {
1553 let mut version = self.rust_info().version(self, &self.version);
1554 if let Some(ref s) = self.config.description
1555 && !s.is_empty()
1556 {
1557 version.push_str(" (");
1558 version.push_str(s);
1559 version.push(')');
1560 }
1561 version
1562 }
1563
1564 fn rust_sha(&self) -> Option<&str> {
1566 self.rust_info().sha()
1567 }
1568
1569 fn release_num(&self, package: &str) -> String {
1571 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1572 let toml = t!(fs::read_to_string(toml_file_name));
1573 for line in toml.lines() {
1574 if let Some(stripped) =
1575 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1576 {
1577 return stripped.to_owned();
1578 }
1579 }
1580
1581 panic!("failed to find version in {package}'s Cargo.toml")
1582 }
1583
1584 fn unstable_features(&self) -> bool {
1587 !matches!(&self.config.channel[..], "stable" | "beta")
1588 }
1589
1590 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1594 let mut ret = Vec::new();
1595 let mut list = vec![root.to_owned()];
1596 let mut visited = HashSet::new();
1597 while let Some(krate) = list.pop() {
1598 let krate = self
1599 .crates
1600 .get(&krate)
1601 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1602 ret.push(krate);
1603 for dep in &krate.deps {
1604 if !self.crates.contains_key(dep) {
1605 continue;
1607 }
1608 if visited.insert(dep)
1614 && (dep != "profiler_builtins"
1615 || target
1616 .map(|t| self.config.profiler_enabled(t))
1617 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1618 && (dep != "rustc_codegen_llvm"
1619 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1620 {
1621 list.push(dep.clone());
1622 }
1623 }
1624 }
1625 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1627 }
1628
1629 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1630 if self.config.dry_run() {
1631 return Vec::new();
1632 }
1633
1634 if !stamp.path().exists() {
1635 eprintln!(
1636 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1637 stamp.path().display()
1638 );
1639 crate::exit!(1);
1640 }
1641
1642 let mut paths = Vec::new();
1643 let contents = t!(fs::read(stamp.path()), stamp.path());
1644 for part in contents.split(|b| *b == 0) {
1647 if part.is_empty() {
1648 continue;
1649 }
1650 let dependency_type = match part[0] as char {
1651 'h' => DependencyType::Host,
1652 's' => DependencyType::TargetSelfContained,
1653 't' => DependencyType::Target,
1654 _ => unreachable!(),
1655 };
1656 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1657 paths.push((path, dependency_type));
1658 }
1659 paths
1660 }
1661
1662 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1667 self.copy_link_internal(src, dst, true);
1668 }
1669
1670 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1675 self.copy_link_internal(src, dst, false);
1676
1677 if file_type.could_have_split_debuginfo()
1678 && let Some(dbg_file) = split_debuginfo(src)
1679 {
1680 self.copy_link_internal(
1681 &dbg_file,
1682 &dst.with_extension(dbg_file.extension().unwrap()),
1683 false,
1684 );
1685 }
1686 }
1687
1688 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1689 if self.config.dry_run() {
1690 return;
1691 }
1692 self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1693 if src == dst {
1694 return;
1695 }
1696 if let Err(e) = fs::remove_file(dst)
1697 && cfg!(windows)
1698 && e.kind() != io::ErrorKind::NotFound
1699 {
1700 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1703 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1704 }
1705 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1706 let mut src = src.to_path_buf();
1707 if metadata.file_type().is_symlink() {
1708 if dereference_symlinks {
1709 src = t!(fs::canonicalize(src));
1710 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1711 } else {
1712 let link = t!(fs::read_link(src));
1713 t!(self.symlink_file(link, dst));
1714 return;
1715 }
1716 }
1717 if let Ok(()) = fs::hard_link(&src, dst) {
1718 } else {
1721 if let Err(e) = fs::copy(&src, dst) {
1722 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1723 }
1724 t!(fs::set_permissions(dst, metadata.permissions()));
1725
1726 let file_times = fs::FileTimes::new()
1729 .set_accessed(t!(metadata.accessed()))
1730 .set_modified(t!(metadata.modified()));
1731 t!(set_file_times(dst, file_times));
1732 }
1733 }
1734
1735 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1739 if self.config.dry_run() {
1740 return;
1741 }
1742 for f in self.read_dir(src) {
1743 let path = f.path();
1744 let name = path.file_name().unwrap();
1745 let dst = dst.join(name);
1746 if t!(f.file_type()).is_dir() {
1747 t!(fs::create_dir_all(&dst));
1748 self.cp_link_r(&path, &dst);
1749 } else {
1750 self.copy_link(&path, &dst, FileType::Regular);
1751 }
1752 }
1753 }
1754
1755 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1761 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1763 }
1764
1765 fn cp_link_filtered_recurse(
1767 &self,
1768 src: &Path,
1769 dst: &Path,
1770 relative: &Path,
1771 filter: &dyn Fn(&Path) -> bool,
1772 ) {
1773 for f in self.read_dir(src) {
1774 let path = f.path();
1775 let name = path.file_name().unwrap();
1776 let dst = dst.join(name);
1777 let relative = relative.join(name);
1778 if filter(&relative) {
1780 if t!(f.file_type()).is_dir() {
1781 let _ = fs::remove_dir_all(&dst);
1782 self.create_dir(&dst);
1783 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1784 } else {
1785 let _ = fs::remove_file(&dst);
1786 self.copy_link(&path, &dst, FileType::Regular);
1787 }
1788 }
1789 }
1790 }
1791
1792 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1793 let file_name = src.file_name().unwrap();
1794 let dest = dest_folder.join(file_name);
1795 self.copy_link(src, &dest, FileType::Regular);
1796 }
1797
1798 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1799 if self.config.dry_run() {
1800 return;
1801 }
1802 let dst = dstdir.join(src.file_name().unwrap());
1803 self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1804 t!(fs::create_dir_all(dstdir));
1805 if !src.exists() {
1806 panic!("ERROR: File \"{}\" not found!", src.display());
1807 }
1808
1809 self.copy_link_internal(src, &dst, true);
1810 chmod(&dst, file_type.perms());
1811
1812 if file_type.could_have_split_debuginfo()
1814 && let Some(dbg_file) = split_debuginfo(src)
1815 {
1816 self.install(&dbg_file, dstdir, FileType::Regular);
1817 }
1818 }
1819
1820 fn read(&self, path: &Path) -> String {
1821 if self.config.dry_run() {
1822 return String::new();
1823 }
1824 t!(fs::read_to_string(path))
1825 }
1826
1827 fn create_dir(&self, dir: &Path) {
1828 if self.config.dry_run() {
1829 return;
1830 }
1831 t!(fs::create_dir_all(dir))
1832 }
1833
1834 fn remove_dir(&self, dir: &Path) {
1835 if self.config.dry_run() {
1836 return;
1837 }
1838 t!(fs::remove_dir_all(dir))
1839 }
1840
1841 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1842 let iter = match fs::read_dir(dir) {
1843 Ok(v) => v,
1844 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1845 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1846 };
1847 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1848 }
1849
1850 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1851 #[cfg(unix)]
1852 use std::os::unix::fs::symlink as symlink_file;
1853 #[cfg(windows)]
1854 use std::os::windows::fs::symlink_file;
1855 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1856 }
1857
1858 fn ninja(&self) -> bool {
1861 let mut cmd_finder = crate::core::sanity::Finder::new();
1862
1863 if self.config.ninja_in_file {
1864 if cmd_finder.maybe_have("ninja-build").is_none()
1867 && cmd_finder.maybe_have("ninja").is_none()
1868 {
1869 eprintln!(
1870 "
1871Couldn't find required command: ninja (or ninja-build)
1872
1873You should install ninja as described at
1874<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1875or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
1876Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1877to download LLVM rather than building it.
1878"
1879 );
1880 exit!(1);
1881 }
1882 }
1883
1884 if !self.config.ninja_in_file
1892 && self.config.host_target.is_msvc()
1893 && cmd_finder.maybe_have("ninja").is_some()
1894 {
1895 return true;
1896 }
1897
1898 self.config.ninja_in_file
1899 }
1900
1901 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1902 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1903 }
1904
1905 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1906 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1907 }
1908
1909 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1910 where
1911 C: Fn(ColorChoice) -> StandardStream,
1912 F: FnOnce(&mut dyn WriteColor) -> R,
1913 {
1914 let choice = match self.config.color {
1915 flags::Color::Always => ColorChoice::Always,
1916 flags::Color::Never => ColorChoice::Never,
1917 flags::Color::Auto if !is_tty => ColorChoice::Never,
1918 flags::Color::Auto => ColorChoice::Auto,
1919 };
1920 let mut stream = constructor(choice);
1921 let result = f(&mut stream);
1922 stream.reset().unwrap();
1923 result
1924 }
1925
1926 pub fn exec_ctx(&self) -> &ExecutionContext {
1927 &self.config.exec_ctx
1928 }
1929
1930 pub fn report_summary(&self, start_time: Instant) {
1931 self.config.exec_ctx.profiler().report_summary(start_time);
1932 }
1933}
1934
1935impl AsRef<ExecutionContext> for Build {
1936 fn as_ref(&self) -> &ExecutionContext {
1937 &self.config.exec_ctx
1938 }
1939}
1940
1941#[cfg(unix)]
1942fn chmod(path: &Path, perms: u32) {
1943 use std::os::unix::fs::*;
1944 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1945}
1946#[cfg(windows)]
1947fn chmod(_path: &Path, _perms: u32) {}
1948
1949impl Compiler {
1950 pub fn new(stage: u32, host: TargetSelection) -> Self {
1951 Self { stage, host, forced_compiler: false }
1952 }
1953
1954 pub fn forced_compiler(&mut self, forced_compiler: bool) {
1955 self.forced_compiler = forced_compiler;
1956 }
1957
1958 pub fn with_stage(mut self, stage: u32) -> Compiler {
1959 self.stage = stage;
1960 self
1961 }
1962
1963 pub fn is_snapshot(&self, build: &Build) -> bool {
1965 self.stage == 0 && self.host == build.host_target
1966 }
1967
1968 pub fn is_forced_compiler(&self) -> bool {
1970 self.forced_compiler
1971 }
1972}
1973
1974fn envify(s: &str) -> String {
1975 s.chars()
1976 .map(|c| match c {
1977 '-' => '_',
1978 c => c,
1979 })
1980 .flat_map(|c| c.to_uppercase())
1981 .collect()
1982}
1983
1984pub fn prepare_behaviour_dump_dir(build: &Build) {
1986 static INITIALIZED: OnceLock<bool> = OnceLock::new();
1987
1988 let dump_path = build.out.join("bootstrap-shims-dump");
1989
1990 let initialized = INITIALIZED.get().unwrap_or(&false);
1991 if !initialized {
1992 if dump_path.exists() {
1994 t!(fs::remove_dir_all(&dump_path));
1995 }
1996
1997 t!(fs::create_dir_all(&dump_path));
1998
1999 t!(INITIALIZED.set(true));
2000 }
2001}