1#![allow(clippy::assertions_on_constants, reason = "false positive for `assert!(cfg!(..))`")]
21#![allow(clippy::map_clone, reason = "false positive for `|x: &&Foo| Foo::clone(x)`")]
22use std::cell::Cell;
25use std::collections::{BTreeSet, HashMap, HashSet};
26use std::fmt::Display;
27use std::path::{Path, PathBuf};
28use std::sync::OnceLock;
29use std::time::{Instant, SystemTime};
30use std::{env, fs, io, str};
31
32use build_helper::ci::gha;
33use cc::Tool;
34use termcolor::{ColorChoice, StandardStream, WriteColor};
35#[cfg(feature = "tracing")]
36use tracing::{instrument, span};
37
38use crate::core::build_steps::format::InternalRustfmt;
39use crate::core::build_steps::vendor::VENDOR_DIR;
40use crate::core::builder::{self, Kind};
41use crate::core::config::flags::{self, Subcommand};
42use crate::core::config::{BootstrapOverrideLld, Config, DryRun, LlvmLibunwind, TargetSelection};
43use crate::utils::build_stamp::BuildStamp;
44use crate::utils::channel::GitInfo;
45use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
46use crate::utils::helpers::{
47 self, dir_is_empty, exe, libdir, set_file_times, split_debuginfo, symlink_dir, t,
48};
49
50pub mod cli_main;
51mod core;
52mod utils;
53
54const LLVM_TOOLS: &[&str] = &[
55 "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", ];
70
71const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
73
74#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
78 (Some(Mode::Rustc), "bootstrap", None),
79 (Some(Mode::Codegen), "bootstrap", None),
80 (Some(Mode::ToolRustcPrivate), "bootstrap", None),
81 (Some(Mode::ToolStd), "bootstrap", None),
82 (Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
83 (Some(Mode::ToolStd), "rust_analyzer", None),
84 ];
88
89#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
95pub struct Compiler {
96 stage: u32,
97 host: TargetSelection,
98 forced_compiler: bool,
102}
103
104impl std::hash::Hash for Compiler {
105 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
106 self.stage.hash(state);
107 self.host.hash(state);
108 }
109}
110
111impl PartialEq for Compiler {
112 fn eq(&self, other: &Self) -> bool {
113 self.stage == other.stage && self.host == other.host
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
119pub enum CodegenBackendKind {
120 #[default]
121 Llvm,
122 Cranelift,
123 Gcc,
124 Custom(String),
125}
126
127impl CodegenBackendKind {
128 pub fn name(&self) -> &str {
131 match self {
132 CodegenBackendKind::Llvm => "llvm",
133 CodegenBackendKind::Cranelift => "cranelift",
134 CodegenBackendKind::Gcc => "gcc",
135 CodegenBackendKind::Custom(name) => name,
136 }
137 }
138
139 pub fn crate_name(&self) -> String {
141 format!("rustc_codegen_{}", self.name())
142 }
143
144 pub fn is_llvm(&self) -> bool {
145 matches!(self, Self::Llvm)
146 }
147
148 pub fn is_cranelift(&self) -> bool {
149 matches!(self, Self::Cranelift)
150 }
151
152 pub fn is_gcc(&self) -> bool {
153 matches!(self, Self::Gcc)
154 }
155}
156
157impl std::str::FromStr for CodegenBackendKind {
158 type Err = &'static str;
159
160 fn from_str(s: &str) -> Result<Self, Self::Err> {
161 match s.to_lowercase().as_str() {
162 "" => Err("Invalid empty backend name"),
163 "gcc" => Ok(Self::Gcc),
164 "llvm" => Ok(Self::Llvm),
165 "cranelift" => Ok(Self::Cranelift),
166 _ => Ok(Self::Custom(s.to_string())),
167 }
168 }
169}
170
171#[derive(PartialEq, Eq, Copy, Clone, Debug)]
172pub enum TestTarget {
173 Default,
175 AllTargets,
177 DocOnly,
179 Tests,
181}
182
183impl TestTarget {
184 fn runs_doctests(&self) -> bool {
185 matches!(self, TestTarget::DocOnly | TestTarget::Default)
186 }
187}
188
189pub enum GitRepo {
190 Rustc,
191 Llvm,
192}
193
194pub struct Build {
205 config: Config,
207
208 version: String,
210
211 src: PathBuf,
213 out: PathBuf,
214 bootstrap_out: PathBuf,
215 cargo_info: GitInfo,
216 rust_analyzer_info: GitInfo,
217 clippy_info: GitInfo,
218 miri_info: GitInfo,
219 rustfmt_info: GitInfo,
220 enzyme_info: GitInfo,
221 in_tree_llvm_info: GitInfo,
222 in_tree_gcc_info: GitInfo,
223 local_rebuild: bool,
224 fail_fast: bool,
225 test_target: TestTarget,
226 verbosity: usize,
227
228 host_target: TargetSelection,
230 hosts: Vec<TargetSelection>,
232 targets: Vec<TargetSelection>,
234
235 initial_rustc: PathBuf,
236 initial_rustdoc: PathBuf,
237 initial_cargo: PathBuf,
238 initial_lld: PathBuf,
239 initial_relative_libdir: PathBuf,
240 initial_sysroot: PathBuf,
241
242 cc: HashMap<TargetSelection, cc::Tool>,
245 cxx: HashMap<TargetSelection, cc::Tool>,
246 ar: HashMap<TargetSelection, PathBuf>,
247 ranlib: HashMap<TargetSelection, PathBuf>,
248 wasi_sdk_path: Option<PathBuf>,
249
250 crates: HashMap<String, Crate>,
253 crate_paths: HashMap<PathBuf, String>,
254 is_sudo: bool,
255 prerelease_version: Cell<Option<u32>>,
256
257 #[cfg(feature = "build-metrics")]
258 metrics: crate::utils::metrics::BuildMetrics,
259
260 #[cfg(feature = "tracing")]
261 step_graph: std::cell::RefCell<crate::utils::step_graph::StepGraph>,
262}
263
264#[derive(Debug, Clone)]
265struct Crate {
266 name: String,
267 deps: HashSet<String>,
268 path: PathBuf,
269 features: Vec<String>,
270}
271
272impl Crate {
273 fn local_path(&self, build: &Build) -> PathBuf {
274 self.path.strip_prefix(&build.config.src).unwrap().into()
275 }
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
280pub enum DependencyType {
281 Host,
283 Target,
285 TargetSelfContained,
287}
288
289#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
294pub enum Mode {
295 Std,
297
298 Rustc,
300
301 Codegen,
303
304 ToolBootstrap,
316
317 ToolTarget,
328
329 ToolStd,
333
334 ToolRustcPrivate,
340}
341
342impl Mode {
343 pub fn must_support_dlopen(&self) -> bool {
344 match self {
345 Mode::Std | Mode::Codegen => true,
346 Mode::ToolBootstrap
347 | Mode::ToolRustcPrivate
348 | Mode::ToolStd
349 | Mode::ToolTarget
350 | Mode::Rustc => false,
351 }
352 }
353}
354
355pub enum RemapScheme {
359 Compiler,
361 NonCompiler,
363}
364
365#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
366pub enum CLang {
367 C,
368 Cxx,
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
372pub enum FileType {
373 Executable,
375 NativeLibrary,
377 Script,
379 Regular,
381}
382
383impl FileType {
384 pub fn perms(self) -> u32 {
386 match self {
387 FileType::Executable | FileType::Script => 0o755,
388 FileType::Regular | FileType::NativeLibrary => 0o644,
389 }
390 }
391
392 pub fn could_have_split_debuginfo(self) -> bool {
393 match self {
394 FileType::Executable | FileType::NativeLibrary => true,
395 FileType::Script | FileType::Regular => false,
396 }
397 }
398}
399
400macro_rules! forward {
401 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
402 impl Build {
403 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
404 self.config.$fn( $($param),* )
405 } )+
406 }
407 }
408}
409
410forward! {
411 do_if_verbose(f: impl Fn()),
412 is_verbose() -> bool,
413 create(path: &Path, s: &str),
414 remove(f: &Path),
415 tempdir() -> PathBuf,
416 llvm_link_shared() -> bool,
417 download_rustc() -> bool,
418}
419
420struct TargetAndStage {
423 target: TargetSelection,
424 stage: u32,
425}
426
427impl From<(TargetSelection, u32)> for TargetAndStage {
428 fn from((target, stage): (TargetSelection, u32)) -> Self {
429 Self { target, stage }
430 }
431}
432
433impl From<Compiler> for TargetAndStage {
434 fn from(compiler: Compiler) -> Self {
435 Self { target: compiler.host, stage: compiler.stage }
436 }
437}
438
439impl Build {
440 pub fn new(mut config: Config) -> Build {
445 let src = config.src.clone();
446 let out = config.out.clone();
447
448 #[cfg(unix)]
449 let is_sudo = match env::var_os("SUDO_USER") {
452 Some(_sudo_user) => {
453 let uid = unsafe { libc::getuid() };
458 uid == 0
459 }
460 None => false,
461 };
462 #[cfg(not(unix))]
463 let is_sudo = false;
464
465 let rust_info = config.rust_info.clone();
466 let cargo_info = config.cargo_info.clone();
467 let rust_analyzer_info = config.rust_analyzer_info.clone();
468 let clippy_info = config.clippy_info.clone();
469 let miri_info = config.miri_info.clone();
470 let rustfmt_info = config.rustfmt_info.clone();
471 let enzyme_info = config.enzyme_info.clone();
472 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
473 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
474
475 let initial_target_libdir = command(&config.initial_rustc)
476 .run_in_dry_run()
477 .args(["--print", "target-libdir"])
478 .run_capture_stdout(&config)
479 .stdout()
480 .trim()
481 .to_owned();
482
483 let initial_target_dir = Path::new(&initial_target_libdir)
484 .parent()
485 .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent"));
486
487 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
488
489 let initial_relative_libdir = if cfg!(test) {
490 PathBuf::default()
492 } else {
493 let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
494 panic!("Not enough ancestors for {}", initial_target_dir.display())
495 });
496
497 ancestor
498 .strip_prefix(&config.initial_sysroot)
499 .unwrap_or_else(|_| {
500 panic!(
501 "Couldn’t resolve the initial relative libdir from {}",
502 initial_target_dir.display()
503 )
504 })
505 .to_path_buf()
506 };
507
508 let version = std::fs::read_to_string(src.join("src").join("version"))
509 .expect("failed to read src/version");
510 let version = version.trim();
511
512 let mut bootstrap_out = std::env::current_exe()
513 .expect("could not determine path to running process")
514 .parent()
515 .unwrap()
516 .to_path_buf();
517 if bootstrap_out.ends_with("deps") {
520 bootstrap_out.pop();
521 }
522 if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
523 panic!(
525 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
526 bootstrap_out.display()
527 )
528 }
529
530 if rust_info.is_from_tarball() && config.description.is_none() {
531 config.description = Some("built from a source tarball".to_owned());
532 }
533
534 let mut build = Build {
535 initial_lld,
536 initial_relative_libdir,
537 initial_rustc: config.initial_rustc.clone(),
538 initial_rustdoc: config.initial_rustdoc.clone(),
539 initial_cargo: config.initial_cargo.clone(),
540 initial_sysroot: config.initial_sysroot.clone(),
541 local_rebuild: config.local_rebuild,
542 fail_fast: config.cmd.fail_fast(),
543 test_target: config.cmd.test_target(),
544 verbosity: config.exec_ctx.verbosity as usize,
545
546 host_target: config.host_target,
547 hosts: config.hosts.clone(),
548 targets: config.targets.clone(),
549
550 config,
551 version: version.to_string(),
552 src,
553 out,
554 bootstrap_out,
555
556 cargo_info,
557 rust_analyzer_info,
558 clippy_info,
559 miri_info,
560 rustfmt_info,
561 enzyme_info,
562 in_tree_llvm_info,
563 in_tree_gcc_info,
564 cc: HashMap::new(),
565 cxx: HashMap::new(),
566 ar: HashMap::new(),
567 ranlib: HashMap::new(),
568 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
569 crates: HashMap::new(),
570 crate_paths: HashMap::new(),
571 is_sudo,
572 prerelease_version: Cell::new(None),
573
574 #[cfg(feature = "build-metrics")]
575 metrics: crate::utils::metrics::BuildMetrics::init(),
576
577 #[cfg(feature = "tracing")]
578 step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()),
579 };
580
581 let local_version_verbose = command(&build.initial_rustc)
584 .run_in_dry_run()
585 .args(["--version", "--verbose"])
586 .run_capture_stdout(&build)
587 .stdout();
588 let local_release = local_version_verbose
589 .lines()
590 .filter_map(|x| x.strip_prefix("release:"))
591 .next()
592 .unwrap()
593 .trim();
594 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
595 build.do_if_verbose(|| println!("auto-detected local-rebuild {local_release}"));
596 build.local_rebuild = true;
597 }
598
599 build.do_if_verbose(|| println!("finding compilers"));
600 utils::cc_detect::fill_compilers(&mut build);
601 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
607 build.do_if_verbose(|| println!("running sanity check"));
608 crate::core::sanity::check(&mut build);
609
610 let rust_submodules = ["library/backtrace"];
613 for s in rust_submodules {
614 build.require_submodule(
615 s,
616 Some(
617 "The submodule is required for the standard library \
618 and the main Cargo workspace.",
619 ),
620 );
621 }
622 build.update_existing_submodules();
624
625 build.do_if_verbose(|| println!("learning about cargo"));
626 crate::core::metadata::build(&mut build);
627 }
628
629 let build_triple = build.out.join(build.host_target);
631 t!(fs::create_dir_all(&build_triple));
632 let host = build.out.join("host");
633 if host.is_symlink() {
634 #[cfg(windows)]
637 t!(fs::remove_dir(&host));
638 #[cfg(not(windows))]
639 t!(fs::remove_file(&host));
640 }
641 t!(
642 symlink_dir(&build.config, &build_triple, &host),
643 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
644 );
645
646 build
647 }
648
649 #[cfg_attr(
658 feature = "tracing",
659 instrument(
660 level = "trace",
661 name = "Build::require_submodule",
662 skip_all,
663 fields(submodule = submodule),
664 ),
665 )]
666 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
667 if self.rust_info().is_from_tarball() {
668 return;
669 }
670
671 if self.config.dry_run() {
672 return;
673 }
674
675 if cfg!(test) && !self.config.submodules() {
678 return;
679 }
680 self.config.update_submodule(submodule);
681 let absolute_path = self.config.src.join(submodule);
682 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
683 let maybe_enable = if !self.config.submodules()
684 && self.config.rust_info.is_managed_git_subrepository()
685 {
686 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
687 } else {
688 ""
689 };
690 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
691 eprintln!(
692 "submodule {submodule} does not appear to be checked out, \
693 but it is required for this step{maybe_enable}{err_hint}"
694 );
695 helpers::exit_process(1);
696 }
697 }
698
699 fn update_existing_submodules(&self) {
702 if !self.config.submodules() {
705 return;
706 }
707 let output = helpers::git(Some(&self.src))
708 .args(["config", "--file"])
709 .arg(".gitmodules")
710 .args(["--get-regexp", "path"])
711 .run_capture(self)
712 .stdout();
713 std::thread::scope(|s| {
714 for line in output.lines() {
717 let submodule = line.split_once(' ').unwrap().1;
718 let config = self.config.clone();
719 s.spawn(move || {
720 Self::update_existing_submodule(&config, submodule);
721 });
722 }
723 });
724 }
725
726 pub fn update_existing_submodule(config: &Config, submodule: &str) {
728 if !config.submodules() {
730 return;
731 }
732
733 if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
734 config.update_submodule(submodule);
735 }
736 }
737
738 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
740 pub fn build(&mut self) {
741 trace!("setting up job management");
742 unsafe {
743 crate::utils::job::setup(self);
744 }
745
746 {
748 #[cfg(feature = "tracing")]
749 let _hardcoded_span =
750 span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
751 .entered();
752
753 match &self.config.cmd {
754 Subcommand::Format { check, all } => {
755 let builder = builder::Builder::new(self);
756 let rustfmt_path = builder.ensure(InternalRustfmt).unwrap_or_else(|| {
757 eprintln!("fmt error: `x fmt` is not supported on this channel");
758 helpers::exit_process(1);
759 });
760 return core::build_steps::format::format(
761 &builder,
762 rustfmt_path,
763 *check,
764 *all,
765 &self.config.paths,
766 );
767 }
768 Subcommand::Perf(args) => {
769 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
770 }
771 _cmd => {
772 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
773 }
774 }
775
776 debug!("handling subcommand normally");
777 }
778
779 if !self.config.dry_run() {
780 #[cfg(feature = "tracing")]
781 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
782
783 {
786 #[cfg(feature = "tracing")]
787 let _sanity_check_span =
788 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
789 self.config.set_dry_run(DryRun::SelfCheck);
790 let builder = builder::Builder::new(self);
791 builder.execute_cli();
792 }
793
794 {
796 #[cfg(feature = "tracing")]
797 let _actual_run_span =
798 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
799 self.config.set_dry_run(DryRun::Disabled);
800 let builder = builder::Builder::new(self);
801 builder.execute_cli();
802 }
803 } else {
804 #[cfg(feature = "tracing")]
805 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
806
807 let builder = builder::Builder::new(self);
808 builder.execute_cli();
809 }
810
811 #[cfg(feature = "tracing")]
812 debug!("checking for postponed test failures from `test --no-fail-fast`");
813
814 self.config.exec_ctx().report_failures_and_exit();
816
817 #[cfg(feature = "build-metrics")]
818 self.metrics.persist(self);
819 }
820
821 fn rust_info(&self) -> &GitInfo {
822 &self.config.rust_info
823 }
824
825 fn std_features(&self, target: TargetSelection) -> String {
828 let mut features: BTreeSet<&str> =
829 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
830
831 match self.config.llvm_libunwind(target) {
832 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
833 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
834 LlvmLibunwind::No => false,
835 };
836
837 if self.config.backtrace {
838 features.insert("backtrace");
839 }
840
841 if self.config.profiler_enabled(target) {
842 features.insert("profiler");
843 }
844
845 if target.contains("zkvm") {
847 features.insert("compiler-builtins-mem");
848 }
849
850 features.into_iter().collect::<Vec<_>>().join(" ")
851 }
852
853 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
855 let possible_features_by_crates: HashSet<_> = crates
856 .iter()
857 .flat_map(|krate| &self.crates[krate].features)
858 .map(std::ops::Deref::deref)
859 .collect();
860 let check = |feature: &str| -> bool {
861 crates.is_empty() || possible_features_by_crates.contains(feature)
862 };
863 let mut features = vec![];
864
865 if let Some(allocator_feature_name) = self.config.allocator(target).feature_name()
866 && check(allocator_feature_name)
867 {
868 features.push(allocator_feature_name);
869 }
870 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
871 features.push("llvm");
872 }
873 if self.config.llvm_offload {
874 features.push("llvm_offload");
875 }
876 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
878 features.push("rustc_randomized_layouts");
879 }
880 if self.config.compile_time_deps && kind == Kind::Check {
881 features.push("check_only");
882 }
883
884 if crates.iter().any(|c| c == "rustc_transmute") {
885 features.push("rustc");
888 }
889
890 if !self.config.rust_debug_logging && check("max_level_info") {
896 features.push("max_level_info");
897 }
898
899 features.join(" ")
900 }
901
902 fn cargo_dir(&self, mode: Mode) -> &'static str {
905 match (mode, self.config.rust_optimize.is_release()) {
906 (Mode::Std, _) => "dist",
907 (_, true) => "release",
908 (_, false) => "debug",
909 }
910 }
911
912 fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
913 let out = self
914 .out
915 .join(build_compiler.host)
916 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
917 t!(fs::create_dir_all(&out));
918 out
919 }
920
921 fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
926 use std::fmt::Write;
927
928 fn bootstrap_tool() -> (Option<u32>, &'static str) {
929 (None, "bootstrap-tools")
930 }
931 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
932 (Some(build_compiler.stage + 1), "tools")
933 }
934
935 let (stage, suffix) = match mode {
936 Mode::Std => (Some(build_compiler.stage), "std"),
938 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
940 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
941 Mode::ToolBootstrap => bootstrap_tool(),
942 Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
943 Mode::ToolTarget => {
944 if build_compiler.stage == 0 {
947 bootstrap_tool()
948 } else {
949 staged_tool(build_compiler)
950 }
951 }
952 };
953 let path = self.out.join(build_compiler.host);
954 let mut dir_name = String::new();
955 if let Some(stage) = stage {
956 write!(dir_name, "stage{stage}-").unwrap();
957 }
958 dir_name.push_str(suffix);
959 path.join(dir_name)
960 }
961
962 fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
966 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
967 }
968
969 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
974 if self.config.llvm_from_ci && self.config.is_host_target(target) {
975 self.config.ci_llvm_root()
976 } else {
977 self.out.join(target).join("llvm")
978 }
979 }
980
981 fn doc_out(&self, target: TargetSelection) -> PathBuf {
983 self.out.join(target).join("doc")
984 }
985
986 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
988 self.out.join(target).join("json-doc")
989 }
990
991 fn test_out(&self, target: TargetSelection) -> PathBuf {
992 self.out.join(target).join("test")
993 }
994
995 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
997 self.out.join(target).join("compiler-doc")
998 }
999
1000 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
1002 self.out.join(target).join("md-doc")
1003 }
1004
1005 fn vendored_crates_path(&self) -> Option<PathBuf> {
1007 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1008 }
1009
1010 fn native_dir(&self, target: TargetSelection) -> PathBuf {
1012 self.out.join(target).join("native")
1013 }
1014
1015 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1018 self.native_dir(target).join("rust-test-helpers")
1019 }
1020
1021 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1023 if env::var_os("RUST_TEST_THREADS").is_none() {
1024 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1025 }
1026 }
1027
1028 fn rustc_snapshot_libdir(&self) -> PathBuf {
1030 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1031 }
1032
1033 fn rustc_snapshot_sysroot(&self) -> &Path {
1035 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1036 SYSROOT_CACHE.get_or_init(|| {
1037 command(&self.initial_rustc)
1038 .run_in_dry_run()
1039 .args(["--print", "sysroot"])
1040 .run_capture_stdout(self)
1041 .stdout()
1042 .trim()
1043 .to_owned()
1044 .into()
1045 })
1046 }
1047
1048 fn info(&self, msg: &str) {
1049 match self.config.get_dry_run() {
1050 DryRun::SelfCheck => (),
1051 DryRun::Disabled | DryRun::UserSelected => {
1052 println!("{msg}");
1053 }
1054 }
1055 }
1056
1057 #[must_use = "Groups should not be dropped until the Step finishes running"]
1069 #[track_caller]
1070 fn msg(
1071 &self,
1072 action: impl Into<Kind>,
1073 what: impl Display,
1074 mode: impl Into<Option<Mode>>,
1075 target_and_stage: impl Into<TargetAndStage>,
1076 target: impl Into<Option<TargetSelection>>,
1077 ) -> Option<gha::Group> {
1078 let target_and_stage = target_and_stage.into();
1079 let action = action.into();
1080 assert!(
1081 action != Kind::Test,
1082 "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1083 );
1084
1085 let actual_stage = match mode.into() {
1086 Some(Mode::Std) => target_and_stage.stage,
1088 Some(
1090 Mode::Rustc
1091 | Mode::Codegen
1092 | Mode::ToolBootstrap
1093 | Mode::ToolTarget
1094 | Mode::ToolStd
1095 | Mode::ToolRustcPrivate,
1096 )
1097 | None => target_and_stage.stage + 1,
1098 };
1099
1100 let action = action.description();
1101 let what = what.to_string();
1102 let msg = |fmt| {
1103 let space = if !what.is_empty() { " " } else { "" };
1104 format!("{action} stage{actual_stage} {what}{space}{fmt}")
1105 };
1106 let msg = if let Some(target) = target.into() {
1107 let build_stage = target_and_stage.stage;
1108 let host = target_and_stage.target;
1109 if host == target {
1110 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1111 } else {
1112 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1113 }
1114 } else {
1115 msg(format_args!(""))
1116 };
1117 self.group(&msg)
1118 }
1119
1120 #[must_use = "Groups should not be dropped until the Step finishes running"]
1126 #[track_caller]
1127 fn msg_test(
1128 &self,
1129 what: impl Display,
1130 target: TargetSelection,
1131 stage: u32,
1132 ) -> Option<gha::Group> {
1133 let action = Kind::Test.description();
1134 let msg = format!("{action} stage{stage} {what} ({target})");
1135 self.group(&msg)
1136 }
1137
1138 #[must_use = "Groups should not be dropped until the Step finishes running"]
1142 #[track_caller]
1143 fn msg_unstaged(
1144 &self,
1145 action: impl Into<Kind>,
1146 what: impl Display,
1147 target: TargetSelection,
1148 ) -> Option<gha::Group> {
1149 let action = action.into().description();
1150 let msg = format!("{action} {what} for {target}");
1151 self.group(&msg)
1152 }
1153
1154 #[track_caller]
1155 fn group(&self, msg: &str) -> Option<gha::Group> {
1156 match self.config.get_dry_run() {
1157 DryRun::SelfCheck => None,
1158 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1159 }
1160 }
1161
1162 fn jobs(&self) -> u32 {
1165 self.config.jobs.unwrap_or_else(|| {
1166 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1167 })
1168 }
1169
1170 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1171 if !self.config.rust_remap_debuginfo {
1172 return None;
1173 }
1174
1175 match which {
1176 GitRepo::Rustc => {
1177 let sha = self.rust_sha().unwrap_or(&self.version);
1178
1179 match remap_scheme {
1180 RemapScheme::Compiler => {
1181 Some(format!("/rustc-dev/{sha}"))
1190 }
1191 RemapScheme::NonCompiler => {
1192 Some(format!("/rustc/{sha}"))
1194 }
1195 }
1196 }
1197 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1198 }
1199 }
1200
1201 fn cc(&self, target: TargetSelection) -> PathBuf {
1203 if self.config.dry_run() {
1204 return PathBuf::new();
1205 }
1206 self.cc[&target].path().into()
1207 }
1208
1209 fn cc_tool(&self, target: TargetSelection) -> Tool {
1211 self.cc[&target].clone()
1212 }
1213
1214 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1216 self.cxx[&target].clone()
1217 }
1218
1219 fn cc_handled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1222 if self.config.dry_run() {
1223 return Vec::new();
1224 }
1225 let base = match c {
1226 CLang::C => self.cc[&target].clone(),
1227 CLang::Cxx => self.cxx[&target].clone(),
1228 };
1229
1230 base.args()
1233 .iter()
1234 .map(|s| s.to_string_lossy().into_owned())
1235 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1236 .collect::<Vec<String>>()
1237 }
1238
1239 fn cc_unhandled_cflags(
1241 &self,
1242 target: TargetSelection,
1243 which: GitRepo,
1244 c: CLang,
1245 ) -> Vec<String> {
1246 let mut base = Vec::new();
1247
1248 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1252 base.push("-stdlib=libc++".into());
1253 }
1254
1255 if &*target.triple == "i686-pc-windows-gnu" {
1259 base.push("-fno-omit-frame-pointer".into());
1260 }
1261
1262 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1263 let map = format!("{}={}", self.src.display(), map_to);
1264 let cc = self.cc_tool(target);
1265 if cc.is_like_clang() || cc.is_like_gnu() {
1266 base.push(format!("-fdebug-prefix-map={map}"));
1267 } else if cc.is_like_clang_cl() {
1268 base.push("-Xclang".into());
1269 base.push(format!("-fdebug-prefix-map={map}"));
1270 }
1271 }
1272 base
1273 }
1274
1275 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1277 if self.config.dry_run() {
1278 return None;
1279 }
1280 self.ar.get(&target).cloned()
1281 }
1282
1283 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1285 if self.config.dry_run() {
1286 return None;
1287 }
1288 self.ranlib.get(&target).cloned()
1289 }
1290
1291 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1293 if self.config.dry_run() {
1294 return Ok(PathBuf::new());
1295 }
1296 match self.cxx.get(&target) {
1297 Some(p) => Ok(p.path().into()),
1298 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1299 }
1300 }
1301
1302 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1304 if self.config.dry_run() {
1305 return Some(PathBuf::new());
1306 }
1307 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1308 {
1309 Some(linker)
1310 } else if target.contains("vxworks") {
1311 Some(self.cxx[&target].path().into())
1314 } else if !self.config.is_host_target(target)
1315 && helpers::use_host_linker(target)
1316 && !target.is_msvc()
1317 {
1318 Some(self.cc(target))
1319 } else if self.config.bootstrap_override_lld.is_used()
1320 && self.is_lld_direct_linker(target)
1321 && self.host_target == target
1322 {
1323 match self.config.bootstrap_override_lld {
1324 BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1325 BootstrapOverrideLld::External => Some("lld".into()),
1326 BootstrapOverrideLld::None => None,
1327 }
1328 } else {
1329 None
1330 }
1331 }
1332
1333 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1336 target.is_msvc()
1337 }
1338
1339 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1341 if target.contains("pc-windows-msvc") {
1342 Some(true)
1343 } else {
1344 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1345 }
1346 }
1347
1348 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1353 let configured_root = self
1354 .config
1355 .target_config
1356 .get(&target)
1357 .and_then(|t| t.musl_root.as_ref())
1358 .or(self.config.musl_root.as_ref())
1359 .map(|p| &**p);
1360
1361 if self.config.is_host_target(target) && configured_root.is_none() {
1362 Some(Path::new("/usr"))
1363 } else {
1364 configured_root
1365 }
1366 }
1367
1368 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1370 self.config
1371 .target_config
1372 .get(&target)
1373 .and_then(|t| t.musl_libdir.clone())
1374 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1375 }
1376
1377 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1384 let configured =
1385 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1386 if let Some(path) = configured {
1387 return Some(path.join("lib").join(target.to_string()));
1388 }
1389 let mut env_root = self.wasi_sdk_path.clone()?;
1390 env_root.push("share");
1391 env_root.push("wasi-sysroot");
1392 env_root.push("lib");
1393 env_root.push(target.to_string());
1394 Some(env_root)
1395 }
1396
1397 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1399 self.config.target_config.get(&target).map(|t| t.no_std)
1400 }
1401
1402 fn remote_tested(&self, target: TargetSelection) -> bool {
1405 self.qemu_rootfs(target).is_some()
1406 || target.contains("android")
1407 || env::var_os("TEST_DEVICE_ADDR").is_some()
1408 }
1409
1410 fn runner(&self, target: TargetSelection) -> Option<String> {
1416 let configured_runner =
1417 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1418 if let Some(runner) = configured_runner {
1419 return Some(runner.to_owned());
1420 }
1421
1422 if target.starts_with("wasm") && target.contains("wasi") {
1423 self.default_wasi_runner(target)
1424 } else {
1425 None
1426 }
1427 }
1428
1429 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1433 let mut finder = crate::core::sanity::Finder::new();
1434
1435 if let Some(path) = finder.maybe_have("wasmtime")
1439 && let Ok(mut path) = path.into_os_string().into_string()
1440 {
1441 path.push_str(" run -Wexceptions -C cache=n --dir .");
1442 path.push_str(" --env RUSTC_BOOTSTRAP");
1449
1450 if target.contains("wasip2") {
1451 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1452 }
1453
1454 return Some(path);
1455 }
1456
1457 None
1458 }
1459
1460 fn tool_enabled(&self, tool: &str) -> bool {
1465 if !self.config.extended {
1466 return false;
1467 }
1468 match &self.config.tools {
1469 Some(set) => set.contains(tool),
1470 None => true,
1471 }
1472 }
1473
1474 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1480 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1481 }
1482
1483 fn extended_error_dir(&self) -> PathBuf {
1485 self.out.join("tmp/extended-error-metadata")
1486 }
1487
1488 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1507 !self.config.full_bootstrap
1508 && !self.config.download_rustc()
1509 && stage >= 2
1510 && (self.hosts.contains(&target) || target == self.host_target)
1511 }
1512
1513 fn force_use_stage2(&self, stage: u32) -> bool {
1519 self.config.download_rustc() && stage >= 2
1520 }
1521
1522 fn release(&self, num: &str) -> String {
1528 match &self.config.channel[..] {
1529 "stable" => num.to_string(),
1530 "beta" => {
1531 if !self.config.omit_git_hash {
1532 format!("{}-beta.{}", num, self.beta_prerelease_version())
1533 } else {
1534 format!("{num}-beta")
1535 }
1536 }
1537 "nightly" => format!("{num}-nightly"),
1538 _ => format!("{num}-dev"),
1539 }
1540 }
1541
1542 fn beta_prerelease_version(&self) -> u32 {
1543 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1544 let version = fs::read_to_string(version_file).ok()?;
1545
1546 helpers::extract_beta_rev(&version)
1547 }
1548
1549 if let Some(s) = self.prerelease_version.get() {
1550 return s;
1551 }
1552
1553 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1557 helpers::git(Some(&self.src))
1561 .arg("rev-list")
1562 .arg("--count")
1563 .arg("--merges")
1564 .arg(format!(
1565 "refs/remotes/origin/{}..HEAD",
1566 self.config.stage0_metadata.config.nightly_branch
1567 ))
1568 .run_in_dry_run()
1569 .run_capture(self)
1570 .stdout()
1571 });
1572 let n = count.trim().parse().unwrap();
1573 self.prerelease_version.set(Some(n));
1574 n
1575 }
1576
1577 fn rust_release(&self) -> String {
1579 self.release(&self.version)
1580 }
1581
1582 fn rust_package_vers(&self) -> String {
1588 match &self.config.channel[..] {
1589 "stable" => self.version.to_string(),
1590 "beta" => "beta".to_string(),
1591 "nightly" => "nightly".to_string(),
1592 _ => format!("{}-dev", self.version),
1593 }
1594 }
1595
1596 fn rust_version(&self) -> String {
1602 let mut version = self.rust_info().version(self, &self.version);
1603 if let Some(ref s) = self.config.description
1604 && !s.is_empty()
1605 {
1606 version.push_str(" (");
1607 version.push_str(s);
1608 version.push(')');
1609 }
1610 version
1611 }
1612
1613 fn rust_sha(&self) -> Option<&str> {
1615 self.rust_info().sha()
1616 }
1617
1618 fn release_num(&self, package: &str) -> String {
1620 if self.config.dry_run() {
1621 return "0.0.0 (dry-run)".into();
1622 }
1623 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1624 let toml = t!(fs::read_to_string(toml_file_name));
1625 for line in toml.lines() {
1626 if let Some(stripped) =
1627 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1628 {
1629 return stripped.to_owned();
1630 }
1631 }
1632
1633 panic!("failed to find version in {package}'s Cargo.toml")
1634 }
1635
1636 fn unstable_features(&self) -> bool {
1639 !matches!(&self.config.channel[..], "stable" | "beta")
1640 }
1641
1642 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1646 let mut ret = Vec::new();
1647 let mut list = vec![root.to_owned()];
1648 let mut visited = HashSet::new();
1649 while let Some(krate) = list.pop() {
1650 let krate = self
1651 .crates
1652 .get(&krate)
1653 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1654 ret.push(krate);
1655 for dep in &krate.deps {
1656 if !self.crates.contains_key(dep) {
1657 continue;
1659 }
1660 if visited.insert(dep)
1666 && (dep != "profiler_builtins"
1667 || target
1668 .map(|t| self.config.profiler_enabled(t))
1669 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1670 && (dep != "rustc_codegen_llvm"
1671 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1672 {
1673 list.push(dep.clone());
1674 }
1675 }
1676 }
1677
1678 ret.sort_unstable_by(|a, b| Ord::cmp(&a.name, &b.name));
1680 ret
1681 }
1682
1683 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1684 if self.config.dry_run() {
1685 return Vec::new();
1686 }
1687
1688 if !stamp.path().exists() {
1689 eprintln!(
1690 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1691 stamp.path().display()
1692 );
1693 helpers::exit_process(1);
1694 }
1695
1696 let mut paths = Vec::new();
1697 let contents = t!(fs::read(stamp.path()), stamp.path());
1698 for part in contents.split(|b| *b == 0) {
1701 if part.is_empty() {
1702 continue;
1703 }
1704 let dependency_type = match part[0] as char {
1705 'h' => DependencyType::Host,
1706 's' => DependencyType::TargetSelfContained,
1707 't' => DependencyType::Target,
1708 _ => unreachable!(),
1709 };
1710 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1711 paths.push((path, dependency_type));
1712 }
1713 paths
1714 }
1715
1716 #[track_caller]
1721 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1722 self.copy_link_internal(src, dst, true);
1723 }
1724
1725 #[track_caller]
1730 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1731 self.copy_link_internal(src, dst, false);
1732
1733 if file_type.could_have_split_debuginfo()
1734 && let Some(dbg_file) = split_debuginfo(src)
1735 {
1736 self.copy_link_internal(
1737 &dbg_file,
1738 &dst.with_extension(dbg_file.extension().unwrap()),
1739 false,
1740 );
1741 }
1742 }
1743
1744 #[track_caller]
1745 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1746 if self.config.dry_run() {
1747 return;
1748 }
1749 if src == dst {
1750 return;
1751 }
1752
1753 #[cfg(feature = "tracing")]
1754 let _span = trace_io!("file-copy-link", ?src, ?dst);
1755
1756 if let Err(e) = fs::remove_file(dst)
1757 && cfg!(windows)
1758 && e.kind() != io::ErrorKind::NotFound
1759 {
1760 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1763 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1764 }
1765 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1766 let mut src = src.to_path_buf();
1767 if metadata.file_type().is_symlink() {
1768 if dereference_symlinks {
1769 src = t!(fs::canonicalize(src));
1770 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1771 } else {
1772 let link = t!(fs::read_link(src));
1773 t!(self.symlink_file(link, dst));
1774 return;
1775 }
1776 }
1777 if let Ok(()) = fs::hard_link(&src, dst) {
1778 } else {
1781 if let Err(e) = fs::copy(&src, dst) {
1782 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1783 }
1784 t!(fs::set_permissions(dst, metadata.permissions()));
1785
1786 let file_times = fs::FileTimes::new()
1789 .set_accessed(t!(metadata.accessed()))
1790 .set_modified(t!(metadata.modified()));
1791 t!(set_file_times(dst, file_times));
1792 }
1793 }
1794
1795 #[track_caller]
1799 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1800 if self.config.dry_run() {
1801 return;
1802 }
1803 for f in self.read_dir(src) {
1804 let path = f.path();
1805 let name = path.file_name().unwrap();
1806 let dst = dst.join(name);
1807 if t!(f.file_type()).is_dir() {
1808 t!(fs::create_dir_all(&dst));
1809 self.cp_link_r(&path, &dst);
1810 } else {
1811 self.copy_link(&path, &dst, FileType::Regular);
1812 }
1813 }
1814 }
1815
1816 #[track_caller]
1822 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 #[track_caller]
1829 fn cp_link_filtered_recurse(
1830 &self,
1831 src: &Path,
1832 dst: &Path,
1833 relative: &Path,
1834 filter: &dyn Fn(&Path) -> bool,
1835 ) {
1836 for f in self.read_dir(src) {
1837 let path = f.path();
1838 let name = path.file_name().unwrap();
1839 let dst = dst.join(name);
1840 let relative = relative.join(name);
1841 if filter(&relative) {
1843 if t!(f.file_type()).is_dir() {
1844 let _ = fs::remove_dir_all(&dst);
1845 self.create_dir(&dst);
1846 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1847 } else {
1848 self.copy_link(&path, &dst, FileType::Regular);
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, FileType::Regular);
1858 }
1859
1860 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1861 if self.config.dry_run() {
1862 return;
1863 }
1864 let dst = dstdir.join(src.file_name().unwrap());
1865
1866 #[cfg(feature = "tracing")]
1867 let _span = trace_io!("install", ?src, ?dst);
1868
1869 t!(fs::create_dir_all(dstdir));
1870 if !src.exists() {
1871 panic!("ERROR: File \"{}\" not found!", src.display());
1872 }
1873
1874 self.copy_link_internal(src, &dst, true);
1875 chmod(&dst, file_type.perms());
1876
1877 if file_type.could_have_split_debuginfo()
1879 && let Some(dbg_file) = split_debuginfo(src)
1880 {
1881 self.install(&dbg_file, dstdir, FileType::Regular);
1882 }
1883 }
1884
1885 fn read(&self, path: &Path) -> String {
1886 if self.config.dry_run() {
1887 return String::new();
1888 }
1889 t!(fs::read_to_string(path))
1890 }
1891
1892 #[track_caller]
1893 fn create_dir(&self, dir: &Path) {
1894 if self.config.dry_run() {
1895 return;
1896 }
1897
1898 #[cfg(feature = "tracing")]
1899 let _span = trace_io!("dir-create", ?dir);
1900
1901 t!(fs::create_dir_all(dir))
1902 }
1903
1904 fn remove_dir(&self, dir: &Path) {
1905 if self.config.dry_run() {
1906 return;
1907 }
1908
1909 #[cfg(feature = "tracing")]
1910 let _span = trace_io!("dir-remove", ?dir);
1911
1912 t!(fs::remove_dir_all(dir))
1913 }
1914
1915 fn clear_dir(&self, dir: &Path) {
1918 if self.config.dry_run() {
1919 return;
1920 }
1921
1922 #[cfg(feature = "tracing")]
1923 let _span = trace_io!("dir-clear", ?dir);
1924
1925 let _ = std::fs::remove_dir_all(dir);
1926 self.create_dir(dir);
1927 }
1928
1929 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1930 let iter = match fs::read_dir(dir) {
1931 Ok(v) => v,
1932 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1933 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1934 };
1935 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1936 }
1937
1938 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1939 #[cfg(unix)]
1940 use std::os::unix::fs::symlink as symlink_file;
1941 #[cfg(windows)]
1942 use std::os::windows::fs::symlink_file;
1943 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1944 }
1945
1946 fn ninja(&self) -> bool {
1949 let mut cmd_finder = crate::core::sanity::Finder::new();
1950
1951 if self.config.ninja_in_file {
1952 if cmd_finder.maybe_have("ninja-build").is_none()
1955 && cmd_finder.maybe_have("ninja").is_none()
1956 {
1957 eprintln!(
1958 "
1959Couldn't find required command: ninja (or ninja-build)
1960
1961You should install ninja as described at
1962<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1963or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
1964Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1965to download LLVM rather than building it.
1966"
1967 );
1968 helpers::exit_process(1);
1969 }
1970 }
1971
1972 if !self.config.ninja_in_file
1980 && self.config.host_target.is_msvc()
1981 && cmd_finder.maybe_have("ninja").is_some()
1982 {
1983 return true;
1984 }
1985
1986 self.config.ninja_in_file
1987 }
1988
1989 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1990 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1991 }
1992
1993 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1994 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1995 }
1996
1997 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
1998 where
1999 C: Fn(ColorChoice) -> StandardStream,
2000 F: FnOnce(&mut dyn WriteColor) -> R,
2001 {
2002 let choice = match self.config.color {
2003 flags::Color::Always => ColorChoice::Always,
2004 flags::Color::Never => ColorChoice::Never,
2005 flags::Color::Auto if !is_tty => ColorChoice::Never,
2006 flags::Color::Auto => ColorChoice::Auto,
2007 };
2008 let mut stream = constructor(choice);
2009 let result = f(&mut stream);
2010 stream.reset().unwrap();
2011 result
2012 }
2013
2014 pub fn exec_ctx(&self) -> &ExecutionContext {
2015 &self.config.exec_ctx
2016 }
2017
2018 pub fn report_summary(&self, path: &Path, start_time: Instant) {
2019 self.config.exec_ctx.profiler().report_summary(path, start_time);
2020 }
2021
2022 #[cfg(feature = "tracing")]
2023 pub fn report_step_graph(self, directory: &Path) {
2024 self.step_graph.into_inner().store_to_dot_files(directory);
2025 }
2026}
2027
2028impl AsRef<ExecutionContext> for Build {
2029 fn as_ref(&self) -> &ExecutionContext {
2030 &self.config.exec_ctx
2031 }
2032}
2033
2034#[cfg(unix)]
2035fn chmod(path: &Path, perms: u32) {
2036 use std::os::unix::fs::*;
2037 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2038}
2039#[cfg(windows)]
2040fn chmod(_path: &Path, _perms: u32) {}
2041
2042impl Compiler {
2043 pub fn new(stage: u32, host: TargetSelection) -> Self {
2044 Self { stage, host, forced_compiler: false }
2045 }
2046
2047 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2048 self.forced_compiler = forced_compiler;
2049 }
2050
2051 pub fn is_snapshot(&self, build: &Build) -> bool {
2053 self.stage == 0 && self.host == build.host_target
2054 }
2055
2056 pub fn is_forced_compiler(&self) -> bool {
2058 self.forced_compiler
2059 }
2060}
2061
2062fn envify(s: &str) -> String {
2063 s.chars()
2066 .map(|c| match c {
2067 '-' | '.' => '_',
2068 c => c,
2069 })
2070 .flat_map(|c| c.to_uppercase())
2071 .collect()
2072}
2073
2074pub fn prepare_behaviour_dump_dir(build: &Build) {
2076 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2077
2078 let dump_path = build.out.join("bootstrap-shims-dump");
2079
2080 let initialized = INITIALIZED.get().unwrap_or(&false);
2081 if !initialized {
2082 if dump_path.exists() {
2084 t!(fs::remove_dir_all(&dump_path));
2085 }
2086
2087 t!(fs::create_dir_all(&dump_path));
2088
2089 t!(INITIALIZED.set(true));
2090 }
2091}