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::{BootstrapOverrideLld, DryRun, LlvmLibunwind, TargetSelection, flags};
39use crate::utils::exec::{BootstrapCommand, command};
40use crate::utils::helpers::{self, dir_is_empty, exe, libdir, set_file_times, split_debuginfo};
41
42mod core;
43mod utils;
44
45pub use core::builder::PathSet;
46#[cfg(feature = "tracing")]
47pub use core::builder::STEP_SPAN_TARGET;
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, symlink_dir};
57#[cfg(feature = "tracing")]
58pub use utils::tracing::setup_tracing;
59
60use crate::core::build_steps::vendor::VENDOR_DIR;
61
62const LLVM_TOOLS: &[&str] = &[
63 "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", ];
78
79const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
81
82#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
86 (Some(Mode::Rustc), "bootstrap", None),
87 (Some(Mode::Codegen), "bootstrap", None),
88 (Some(Mode::ToolRustcPrivate), "bootstrap", None),
89 (Some(Mode::ToolStd), "bootstrap", None),
90 (Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
91 (Some(Mode::ToolStd), "rust_analyzer", None),
92 ];
96
97#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
103pub struct Compiler {
104 stage: u32,
105 host: TargetSelection,
106 forced_compiler: bool,
110}
111
112impl std::hash::Hash for Compiler {
113 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
114 self.stage.hash(state);
115 self.host.hash(state);
116 }
117}
118
119impl PartialEq for Compiler {
120 fn eq(&self, other: &Self) -> bool {
121 self.stage == other.stage && self.host == other.host
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
127pub enum CodegenBackendKind {
128 #[default]
129 Llvm,
130 Cranelift,
131 Gcc,
132 Custom(String),
133}
134
135impl CodegenBackendKind {
136 pub fn name(&self) -> &str {
139 match self {
140 CodegenBackendKind::Llvm => "llvm",
141 CodegenBackendKind::Cranelift => "cranelift",
142 CodegenBackendKind::Gcc => "gcc",
143 CodegenBackendKind::Custom(name) => name,
144 }
145 }
146
147 pub fn crate_name(&self) -> String {
149 format!("rustc_codegen_{}", self.name())
150 }
151
152 pub fn is_llvm(&self) -> bool {
153 matches!(self, Self::Llvm)
154 }
155
156 pub fn is_cranelift(&self) -> bool {
157 matches!(self, Self::Cranelift)
158 }
159
160 pub fn is_gcc(&self) -> bool {
161 matches!(self, Self::Gcc)
162 }
163}
164
165impl std::str::FromStr for CodegenBackendKind {
166 type Err = &'static str;
167
168 fn from_str(s: &str) -> Result<Self, Self::Err> {
169 match s.to_lowercase().as_str() {
170 "" => Err("Invalid empty backend name"),
171 "gcc" => Ok(Self::Gcc),
172 "llvm" => Ok(Self::Llvm),
173 "cranelift" => Ok(Self::Cranelift),
174 _ => Ok(Self::Custom(s.to_string())),
175 }
176 }
177}
178
179#[derive(PartialEq, Eq, Copy, Clone, Debug)]
180pub enum DocTests {
181 Yes,
183 No,
185 Only,
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 doc_tests: DocTests,
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 is_tool(&self) -> bool {
344 match self {
345 Mode::ToolBootstrap | Mode::ToolRustcPrivate | Mode::ToolStd | Mode::ToolTarget => true,
346 Mode::Std | Mode::Codegen | Mode::Rustc => false,
347 }
348 }
349
350 pub fn must_support_dlopen(&self) -> bool {
351 match self {
352 Mode::Std | Mode::Codegen => true,
353 Mode::ToolBootstrap
354 | Mode::ToolRustcPrivate
355 | Mode::ToolStd
356 | Mode::ToolTarget
357 | Mode::Rustc => false,
358 }
359 }
360}
361
362pub enum RemapScheme {
366 Compiler,
368 NonCompiler,
370}
371
372#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
373pub enum CLang {
374 C,
375 Cxx,
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub enum FileType {
380 Executable,
382 NativeLibrary,
384 Script,
386 Regular,
388}
389
390impl FileType {
391 pub fn perms(self) -> u32 {
393 match self {
394 FileType::Executable | FileType::Script => 0o755,
395 FileType::Regular | FileType::NativeLibrary => 0o644,
396 }
397 }
398
399 pub fn could_have_split_debuginfo(self) -> bool {
400 match self {
401 FileType::Executable | FileType::NativeLibrary => true,
402 FileType::Script | FileType::Regular => false,
403 }
404 }
405}
406
407macro_rules! forward {
408 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
409 impl Build {
410 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
411 self.config.$fn( $($param),* )
412 } )+
413 }
414 }
415}
416
417forward! {
418 do_if_verbose(f: impl Fn()),
419 is_verbose() -> bool,
420 create(path: &Path, s: &str),
421 remove(f: &Path),
422 tempdir() -> PathBuf,
423 llvm_link_shared() -> bool,
424 download_rustc() -> bool,
425}
426
427struct TargetAndStage {
430 target: TargetSelection,
431 stage: u32,
432}
433
434impl From<(TargetSelection, u32)> for TargetAndStage {
435 fn from((target, stage): (TargetSelection, u32)) -> Self {
436 Self { target, stage }
437 }
438}
439
440impl From<Compiler> for TargetAndStage {
441 fn from(compiler: Compiler) -> Self {
442 Self { target: compiler.host, stage: compiler.stage }
443 }
444}
445
446impl Build {
447 pub fn new(mut config: Config) -> Build {
452 let src = config.src.clone();
453 let out = config.out.clone();
454
455 #[cfg(unix)]
456 let is_sudo = match env::var_os("SUDO_USER") {
459 Some(_sudo_user) => {
460 let uid = unsafe { libc::getuid() };
465 uid == 0
466 }
467 None => false,
468 };
469 #[cfg(not(unix))]
470 let is_sudo = false;
471
472 let rust_info = config.rust_info.clone();
473 let cargo_info = config.cargo_info.clone();
474 let rust_analyzer_info = config.rust_analyzer_info.clone();
475 let clippy_info = config.clippy_info.clone();
476 let miri_info = config.miri_info.clone();
477 let rustfmt_info = config.rustfmt_info.clone();
478 let enzyme_info = config.enzyme_info.clone();
479 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
480 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
481
482 let initial_target_libdir = command(&config.initial_rustc)
483 .run_in_dry_run()
484 .args(["--print", "target-libdir"])
485 .run_capture_stdout(&config)
486 .stdout()
487 .trim()
488 .to_owned();
489
490 let initial_target_dir = Path::new(&initial_target_libdir)
491 .parent()
492 .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent"));
493
494 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
495
496 let initial_relative_libdir = if cfg!(test) {
497 PathBuf::default()
499 } else {
500 let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
501 panic!("Not enough ancestors for {}", initial_target_dir.display())
502 });
503
504 ancestor
505 .strip_prefix(&config.initial_sysroot)
506 .unwrap_or_else(|_| {
507 panic!(
508 "Couldn’t resolve the initial relative libdir from {}",
509 initial_target_dir.display()
510 )
511 })
512 .to_path_buf()
513 };
514
515 let version = std::fs::read_to_string(src.join("src").join("version"))
516 .expect("failed to read src/version");
517 let version = version.trim();
518
519 let mut bootstrap_out = std::env::current_exe()
520 .expect("could not determine path to running process")
521 .parent()
522 .unwrap()
523 .to_path_buf();
524 if bootstrap_out.ends_with("deps") {
527 bootstrap_out.pop();
528 }
529 if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
530 panic!(
532 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
533 bootstrap_out.display()
534 )
535 }
536
537 if rust_info.is_from_tarball() && config.description.is_none() {
538 config.description = Some("built from a source tarball".to_owned());
539 }
540
541 let mut build = Build {
542 initial_lld,
543 initial_relative_libdir,
544 initial_rustc: config.initial_rustc.clone(),
545 initial_rustdoc: config
546 .initial_rustc
547 .with_file_name(exe("rustdoc", config.host_target)),
548 initial_cargo: config.initial_cargo.clone(),
549 initial_sysroot: config.initial_sysroot.clone(),
550 local_rebuild: config.local_rebuild,
551 fail_fast: config.cmd.fail_fast(),
552 doc_tests: config.cmd.doc_tests(),
553 verbosity: config.exec_ctx.verbosity as usize,
554
555 host_target: config.host_target,
556 hosts: config.hosts.clone(),
557 targets: config.targets.clone(),
558
559 config,
560 version: version.to_string(),
561 src,
562 out,
563 bootstrap_out,
564
565 cargo_info,
566 rust_analyzer_info,
567 clippy_info,
568 miri_info,
569 rustfmt_info,
570 enzyme_info,
571 in_tree_llvm_info,
572 in_tree_gcc_info,
573 cc: HashMap::new(),
574 cxx: HashMap::new(),
575 ar: HashMap::new(),
576 ranlib: HashMap::new(),
577 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
578 crates: HashMap::new(),
579 crate_paths: HashMap::new(),
580 is_sudo,
581 prerelease_version: Cell::new(None),
582
583 #[cfg(feature = "build-metrics")]
584 metrics: crate::utils::metrics::BuildMetrics::init(),
585
586 #[cfg(feature = "tracing")]
587 step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()),
588 };
589
590 let local_version_verbose = command(&build.initial_rustc)
593 .run_in_dry_run()
594 .args(["--version", "--verbose"])
595 .run_capture_stdout(&build)
596 .stdout();
597 let local_release = local_version_verbose
598 .lines()
599 .filter_map(|x| x.strip_prefix("release:"))
600 .next()
601 .unwrap()
602 .trim();
603 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
604 build.do_if_verbose(|| println!("auto-detected local-rebuild {local_release}"));
605 build.local_rebuild = true;
606 }
607
608 build.do_if_verbose(|| println!("finding compilers"));
609 utils::cc_detect::fill_compilers(&mut build);
610 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
616 build.do_if_verbose(|| println!("running sanity check"));
617 crate::core::sanity::check(&mut build);
618
619 let rust_submodules = ["library/backtrace"];
622 for s in rust_submodules {
623 build.require_submodule(
624 s,
625 Some(
626 "The submodule is required for the standard library \
627 and the main Cargo workspace.",
628 ),
629 );
630 }
631 build.update_existing_submodules();
633
634 build.do_if_verbose(|| println!("learning about cargo"));
635 crate::core::metadata::build(&mut build);
636 }
637
638 let build_triple = build.out.join(build.host_target);
640 t!(fs::create_dir_all(&build_triple));
641 let host = build.out.join("host");
642 if host.is_symlink() {
643 #[cfg(windows)]
646 t!(fs::remove_dir(&host));
647 #[cfg(not(windows))]
648 t!(fs::remove_file(&host));
649 }
650 t!(
651 symlink_dir(&build.config, &build_triple, &host),
652 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
653 );
654
655 build
656 }
657
658 #[cfg_attr(
667 feature = "tracing",
668 instrument(
669 level = "trace",
670 name = "Build::require_submodule",
671 skip_all,
672 fields(submodule = submodule),
673 ),
674 )]
675 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
676 if self.rust_info().is_from_tarball() {
677 return;
678 }
679
680 if cfg!(test) && !self.config.submodules() {
683 return;
684 }
685 self.config.update_submodule(submodule);
686 let absolute_path = self.config.src.join(submodule);
687 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
688 let maybe_enable = if !self.config.submodules()
689 && self.config.rust_info.is_managed_git_subrepository()
690 {
691 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
692 } else {
693 ""
694 };
695 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
696 eprintln!(
697 "submodule {submodule} does not appear to be checked out, \
698 but it is required for this step{maybe_enable}{err_hint}"
699 );
700 exit!(1);
701 }
702 }
703
704 fn update_existing_submodules(&self) {
707 if !self.config.submodules() {
710 return;
711 }
712 let output = helpers::git(Some(&self.src))
713 .args(["config", "--file"])
714 .arg(".gitmodules")
715 .args(["--get-regexp", "path"])
716 .run_capture(self)
717 .stdout();
718 std::thread::scope(|s| {
719 for line in output.lines() {
722 let submodule = line.split_once(' ').unwrap().1;
723 let config = self.config.clone();
724 s.spawn(move || {
725 Self::update_existing_submodule(&config, submodule);
726 });
727 }
728 });
729 }
730
731 pub fn update_existing_submodule(config: &Config, submodule: &str) {
733 if !config.submodules() {
735 return;
736 }
737
738 if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
739 config.update_submodule(submodule);
740 }
741 }
742
743 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
745 pub fn build(&mut self) {
746 trace!("setting up job management");
747 unsafe {
748 crate::utils::job::setup(self);
749 }
750
751 {
753 #[cfg(feature = "tracing")]
754 let _hardcoded_span =
755 span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
756 .entered();
757
758 match &self.config.cmd {
759 Subcommand::Format { check, all } => {
760 return core::build_steps::format::format(
761 &builder::Builder::new(self),
762 *check,
763 *all,
764 &self.config.paths,
765 );
766 }
767 Subcommand::Perf(args) => {
768 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
769 }
770 _cmd => {
771 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
772 }
773 }
774
775 debug!("handling subcommand normally");
776 }
777
778 if !self.config.dry_run() {
779 #[cfg(feature = "tracing")]
780 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
781
782 {
785 #[cfg(feature = "tracing")]
786 let _sanity_check_span =
787 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
788 self.config.set_dry_run(DryRun::SelfCheck);
789 let builder = builder::Builder::new(self);
790 builder.execute_cli();
791 }
792
793 {
795 #[cfg(feature = "tracing")]
796 let _actual_run_span =
797 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
798 self.config.set_dry_run(DryRun::Disabled);
799 let builder = builder::Builder::new(self);
800 builder.execute_cli();
801 }
802 } else {
803 #[cfg(feature = "tracing")]
804 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
805
806 let builder = builder::Builder::new(self);
807 builder.execute_cli();
808 }
809
810 #[cfg(feature = "tracing")]
811 debug!("checking for postponed test failures from `test --no-fail-fast`");
812
813 self.config.exec_ctx().report_failures_and_exit();
815
816 #[cfg(feature = "build-metrics")]
817 self.metrics.persist(self);
818 }
819
820 fn rust_info(&self) -> &GitInfo {
821 &self.config.rust_info
822 }
823
824 fn std_features(&self, target: TargetSelection) -> String {
827 let mut features: BTreeSet<&str> =
828 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
829
830 match self.config.llvm_libunwind(target) {
831 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
832 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
833 LlvmLibunwind::No => false,
834 };
835
836 if self.config.backtrace {
837 features.insert("backtrace");
838 }
839
840 if self.config.profiler_enabled(target) {
841 features.insert("profiler");
842 }
843
844 if target.contains("zkvm") {
846 features.insert("compiler-builtins-mem");
847 }
848
849 if self.config.llvm_enzyme {
850 features.insert("llvm_enzyme");
851 }
852
853 features.into_iter().collect::<Vec<_>>().join(" ")
854 }
855
856 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
858 let possible_features_by_crates: HashSet<_> = crates
859 .iter()
860 .flat_map(|krate| &self.crates[krate].features)
861 .map(std::ops::Deref::deref)
862 .collect();
863 let check = |feature: &str| -> bool {
864 crates.is_empty() || possible_features_by_crates.contains(feature)
865 };
866 let mut features = vec![];
867 if self.config.jemalloc(target) && check("jemalloc") {
868 features.push("jemalloc");
869 }
870 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
871 features.push("llvm");
872 }
873 if self.config.llvm_enzyme {
874 features.push("llvm_enzyme");
875 }
876 if self.config.llvm_offload {
877 features.push("llvm_offload");
878 }
879 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
881 features.push("rustc_randomized_layouts");
882 }
883 if self.config.compile_time_deps && kind == Kind::Check {
884 features.push("check_only");
885 }
886
887 if !self.config.rust_debug_logging && check("max_level_info") {
893 features.push("max_level_info");
894 }
895
896 features.join(" ")
897 }
898
899 fn cargo_dir(&self, mode: Mode) -> &'static str {
902 match (mode, self.config.rust_optimize.is_release()) {
903 (Mode::Std, _) => "dist",
904 (_, true) => "release",
905 (_, false) => "debug",
906 }
907 }
908
909 fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
910 let out = self
911 .out
912 .join(build_compiler.host)
913 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
914 t!(fs::create_dir_all(&out));
915 out
916 }
917
918 fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
923 use std::fmt::Write;
924
925 fn bootstrap_tool() -> (Option<u32>, &'static str) {
926 (None, "bootstrap-tools")
927 }
928 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
929 (Some(build_compiler.stage + 1), "tools")
930 }
931
932 let (stage, suffix) = match mode {
933 Mode::Std => (Some(build_compiler.stage), "std"),
935 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
937 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
938 Mode::ToolBootstrap => bootstrap_tool(),
939 Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
940 Mode::ToolTarget => {
941 if build_compiler.stage == 0 {
944 bootstrap_tool()
945 } else {
946 staged_tool(build_compiler)
947 }
948 }
949 };
950 let path = self.out.join(build_compiler.host);
951 let mut dir_name = String::new();
952 if let Some(stage) = stage {
953 write!(dir_name, "stage{stage}-").unwrap();
954 }
955 dir_name.push_str(suffix);
956 path.join(dir_name)
957 }
958
959 fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
963 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
964 }
965
966 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
971 if self.config.llvm_from_ci && self.config.is_host_target(target) {
972 self.config.ci_llvm_root()
973 } else {
974 self.out.join(target).join("llvm")
975 }
976 }
977
978 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
979 self.out.join(&*target.triple).join("enzyme")
980 }
981
982 fn offload_out(&self, target: TargetSelection) -> PathBuf {
983 self.out.join(&*target.triple).join("offload")
984 }
985
986 fn lld_out(&self, target: TargetSelection) -> PathBuf {
987 self.out.join(target).join("lld")
988 }
989
990 fn doc_out(&self, target: TargetSelection) -> PathBuf {
992 self.out.join(target).join("doc")
993 }
994
995 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
997 self.out.join(target).join("json-doc")
998 }
999
1000 fn test_out(&self, target: TargetSelection) -> PathBuf {
1001 self.out.join(target).join("test")
1002 }
1003
1004 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
1006 self.out.join(target).join("compiler-doc")
1007 }
1008
1009 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
1011 self.out.join(target).join("md-doc")
1012 }
1013
1014 fn vendored_crates_path(&self) -> Option<PathBuf> {
1016 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1017 }
1018
1019 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
1021 let target_config = self.config.target_config.get(&target);
1022 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
1023 s.to_path_buf()
1024 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
1025 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
1026 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
1027 if filecheck.exists() {
1028 filecheck
1029 } else {
1030 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
1033 let lib_filecheck =
1034 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
1035 if lib_filecheck.exists() {
1036 lib_filecheck
1037 } else {
1038 filecheck
1042 }
1043 }
1044 } else {
1045 let base = self.llvm_out(target).join("build");
1046 let base = if !self.ninja() && target.is_msvc() {
1047 if self.config.llvm_optimize {
1048 if self.config.llvm_release_debuginfo {
1049 base.join("RelWithDebInfo")
1050 } else {
1051 base.join("Release")
1052 }
1053 } else {
1054 base.join("Debug")
1055 }
1056 } else {
1057 base
1058 };
1059 base.join("bin").join(exe("FileCheck", target))
1060 }
1061 }
1062
1063 fn native_dir(&self, target: TargetSelection) -> PathBuf {
1065 self.out.join(target).join("native")
1066 }
1067
1068 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1071 self.native_dir(target).join("rust-test-helpers")
1072 }
1073
1074 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1076 if env::var_os("RUST_TEST_THREADS").is_none() {
1077 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1078 }
1079 }
1080
1081 fn rustc_snapshot_libdir(&self) -> PathBuf {
1083 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1084 }
1085
1086 fn rustc_snapshot_sysroot(&self) -> &Path {
1088 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1089 SYSROOT_CACHE.get_or_init(|| {
1090 command(&self.initial_rustc)
1091 .run_in_dry_run()
1092 .args(["--print", "sysroot"])
1093 .run_capture_stdout(self)
1094 .stdout()
1095 .trim()
1096 .to_owned()
1097 .into()
1098 })
1099 }
1100
1101 fn info(&self, msg: &str) {
1102 match self.config.get_dry_run() {
1103 DryRun::SelfCheck => (),
1104 DryRun::Disabled | DryRun::UserSelected => {
1105 println!("{msg}");
1106 }
1107 }
1108 }
1109
1110 #[must_use = "Groups should not be dropped until the Step finishes running"]
1122 #[track_caller]
1123 fn msg(
1124 &self,
1125 action: impl Into<Kind>,
1126 what: impl Display,
1127 mode: impl Into<Option<Mode>>,
1128 target_and_stage: impl Into<TargetAndStage>,
1129 target: impl Into<Option<TargetSelection>>,
1130 ) -> Option<gha::Group> {
1131 let target_and_stage = target_and_stage.into();
1132 let action = action.into();
1133 assert!(
1134 action != Kind::Test,
1135 "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1136 );
1137
1138 let actual_stage = match mode.into() {
1139 Some(Mode::Std) => target_and_stage.stage,
1141 Some(
1143 Mode::Rustc
1144 | Mode::Codegen
1145 | Mode::ToolBootstrap
1146 | Mode::ToolTarget
1147 | Mode::ToolStd
1148 | Mode::ToolRustcPrivate,
1149 )
1150 | None => target_and_stage.stage + 1,
1151 };
1152
1153 let action = action.description();
1154 let what = what.to_string();
1155 let msg = |fmt| {
1156 let space = if !what.is_empty() { " " } else { "" };
1157 format!("{action} stage{actual_stage} {what}{space}{fmt}")
1158 };
1159 let msg = if let Some(target) = target.into() {
1160 let build_stage = target_and_stage.stage;
1161 let host = target_and_stage.target;
1162 if host == target {
1163 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1164 } else {
1165 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1166 }
1167 } else {
1168 msg(format_args!(""))
1169 };
1170 self.group(&msg)
1171 }
1172
1173 #[must_use = "Groups should not be dropped until the Step finishes running"]
1179 #[track_caller]
1180 fn msg_test(
1181 &self,
1182 what: impl Display,
1183 target: TargetSelection,
1184 stage: u32,
1185 ) -> Option<gha::Group> {
1186 let action = Kind::Test.description();
1187 let msg = format!("{action} stage{stage} {what} ({target})");
1188 self.group(&msg)
1189 }
1190
1191 #[must_use = "Groups should not be dropped until the Step finishes running"]
1195 #[track_caller]
1196 fn msg_unstaged(
1197 &self,
1198 action: impl Into<Kind>,
1199 what: impl Display,
1200 target: TargetSelection,
1201 ) -> Option<gha::Group> {
1202 let action = action.into().description();
1203 let msg = format!("{action} {what} for {target}");
1204 self.group(&msg)
1205 }
1206
1207 #[track_caller]
1208 fn group(&self, msg: &str) -> Option<gha::Group> {
1209 match self.config.get_dry_run() {
1210 DryRun::SelfCheck => None,
1211 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1212 }
1213 }
1214
1215 fn jobs(&self) -> u32 {
1218 self.config.jobs.unwrap_or_else(|| {
1219 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1220 })
1221 }
1222
1223 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1224 if !self.config.rust_remap_debuginfo {
1225 return None;
1226 }
1227
1228 match which {
1229 GitRepo::Rustc => {
1230 let sha = self.rust_sha().unwrap_or(&self.version);
1231
1232 match remap_scheme {
1233 RemapScheme::Compiler => {
1234 Some(format!("/rustc-dev/{sha}"))
1243 }
1244 RemapScheme::NonCompiler => {
1245 Some(format!("/rustc/{sha}"))
1247 }
1248 }
1249 }
1250 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1251 }
1252 }
1253
1254 fn cc(&self, target: TargetSelection) -> PathBuf {
1256 if self.config.dry_run() {
1257 return PathBuf::new();
1258 }
1259 self.cc[&target].path().into()
1260 }
1261
1262 fn cc_tool(&self, target: TargetSelection) -> Tool {
1264 self.cc[&target].clone()
1265 }
1266
1267 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1269 self.cxx[&target].clone()
1270 }
1271
1272 fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1275 if self.config.dry_run() {
1276 return Vec::new();
1277 }
1278 let base = match c {
1279 CLang::C => self.cc[&target].clone(),
1280 CLang::Cxx => self.cxx[&target].clone(),
1281 };
1282
1283 base.args()
1286 .iter()
1287 .map(|s| s.to_string_lossy().into_owned())
1288 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1289 .collect::<Vec<String>>()
1290 }
1291
1292 fn cc_unhandled_cflags(
1294 &self,
1295 target: TargetSelection,
1296 which: GitRepo,
1297 c: CLang,
1298 ) -> Vec<String> {
1299 let mut base = Vec::new();
1300
1301 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1305 base.push("-stdlib=libc++".into());
1306 }
1307
1308 if &*target.triple == "i686-pc-windows-gnu" {
1312 base.push("-fno-omit-frame-pointer".into());
1313 }
1314
1315 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1316 let map = format!("{}={}", self.src.display(), map_to);
1317 let cc = self.cc(target);
1318 if cc.ends_with("clang") || cc.ends_with("gcc") {
1319 base.push(format!("-fdebug-prefix-map={map}"));
1320 } else if cc.ends_with("clang-cl.exe") {
1321 base.push("-Xclang".into());
1322 base.push(format!("-fdebug-prefix-map={map}"));
1323 }
1324 }
1325 base
1326 }
1327
1328 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1330 if self.config.dry_run() {
1331 return None;
1332 }
1333 self.ar.get(&target).cloned()
1334 }
1335
1336 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1338 if self.config.dry_run() {
1339 return None;
1340 }
1341 self.ranlib.get(&target).cloned()
1342 }
1343
1344 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1346 if self.config.dry_run() {
1347 return Ok(PathBuf::new());
1348 }
1349 match self.cxx.get(&target) {
1350 Some(p) => Ok(p.path().into()),
1351 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1352 }
1353 }
1354
1355 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1357 if self.config.dry_run() {
1358 return Some(PathBuf::new());
1359 }
1360 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1361 {
1362 Some(linker)
1363 } else if target.contains("vxworks") {
1364 Some(self.cxx[&target].path().into())
1367 } else if !self.config.is_host_target(target)
1368 && helpers::use_host_linker(target)
1369 && !target.is_msvc()
1370 {
1371 Some(self.cc(target))
1372 } else if self.config.bootstrap_override_lld.is_used()
1373 && self.is_lld_direct_linker(target)
1374 && self.host_target == target
1375 {
1376 match self.config.bootstrap_override_lld {
1377 BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1378 BootstrapOverrideLld::External => Some("lld".into()),
1379 BootstrapOverrideLld::None => None,
1380 }
1381 } else {
1382 None
1383 }
1384 }
1385
1386 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1389 target.is_msvc()
1390 }
1391
1392 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1394 if target.contains("pc-windows-msvc") {
1395 Some(true)
1396 } else {
1397 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1398 }
1399 }
1400
1401 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1406 let configured_root = self
1407 .config
1408 .target_config
1409 .get(&target)
1410 .and_then(|t| t.musl_root.as_ref())
1411 .or(self.config.musl_root.as_ref())
1412 .map(|p| &**p);
1413
1414 if self.config.is_host_target(target) && configured_root.is_none() {
1415 Some(Path::new("/usr"))
1416 } else {
1417 configured_root
1418 }
1419 }
1420
1421 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1423 self.config
1424 .target_config
1425 .get(&target)
1426 .and_then(|t| t.musl_libdir.clone())
1427 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1428 }
1429
1430 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1437 let configured =
1438 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1439 if let Some(path) = configured {
1440 return Some(path.join("lib").join(target.to_string()));
1441 }
1442 let mut env_root = self.wasi_sdk_path.clone()?;
1443 env_root.push("share");
1444 env_root.push("wasi-sysroot");
1445 env_root.push("lib");
1446 env_root.push(target.to_string());
1447 Some(env_root)
1448 }
1449
1450 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1452 self.config.target_config.get(&target).map(|t| t.no_std)
1453 }
1454
1455 fn remote_tested(&self, target: TargetSelection) -> bool {
1458 self.qemu_rootfs(target).is_some()
1459 || target.contains("android")
1460 || env::var_os("TEST_DEVICE_ADDR").is_some()
1461 }
1462
1463 fn runner(&self, target: TargetSelection) -> Option<String> {
1469 let configured_runner =
1470 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1471 if let Some(runner) = configured_runner {
1472 return Some(runner.to_owned());
1473 }
1474
1475 if target.starts_with("wasm") && target.contains("wasi") {
1476 self.default_wasi_runner(target)
1477 } else {
1478 None
1479 }
1480 }
1481
1482 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1486 let mut finder = crate::core::sanity::Finder::new();
1487
1488 if let Some(path) = finder.maybe_have("wasmtime")
1492 && let Ok(mut path) = path.into_os_string().into_string()
1493 {
1494 path.push_str(" run -C cache=n --dir .");
1495 path.push_str(" --env RUSTC_BOOTSTRAP");
1502
1503 if target.contains("wasip2") {
1504 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1505 }
1506
1507 return Some(path);
1508 }
1509
1510 None
1511 }
1512
1513 fn tool_enabled(&self, tool: &str) -> bool {
1518 if !self.config.extended {
1519 return false;
1520 }
1521 match &self.config.tools {
1522 Some(set) => set.contains(tool),
1523 None => true,
1524 }
1525 }
1526
1527 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1533 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1534 }
1535
1536 fn extended_error_dir(&self) -> PathBuf {
1538 self.out.join("tmp/extended-error-metadata")
1539 }
1540
1541 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1560 !self.config.full_bootstrap
1561 && !self.config.download_rustc()
1562 && stage >= 2
1563 && (self.hosts.contains(&target) || target == self.host_target)
1564 }
1565
1566 fn force_use_stage2(&self, stage: u32) -> bool {
1572 self.config.download_rustc() && stage >= 2
1573 }
1574
1575 fn release(&self, num: &str) -> String {
1581 match &self.config.channel[..] {
1582 "stable" => num.to_string(),
1583 "beta" => {
1584 if !self.config.omit_git_hash {
1585 format!("{}-beta.{}", num, self.beta_prerelease_version())
1586 } else {
1587 format!("{num}-beta")
1588 }
1589 }
1590 "nightly" => format!("{num}-nightly"),
1591 _ => format!("{num}-dev"),
1592 }
1593 }
1594
1595 fn beta_prerelease_version(&self) -> u32 {
1596 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1597 let version = fs::read_to_string(version_file).ok()?;
1598
1599 helpers::extract_beta_rev(&version)
1600 }
1601
1602 if let Some(s) = self.prerelease_version.get() {
1603 return s;
1604 }
1605
1606 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1610 helpers::git(Some(&self.src))
1614 .arg("rev-list")
1615 .arg("--count")
1616 .arg("--merges")
1617 .arg(format!(
1618 "refs/remotes/origin/{}..HEAD",
1619 self.config.stage0_metadata.config.nightly_branch
1620 ))
1621 .run_in_dry_run()
1622 .run_capture(self)
1623 .stdout()
1624 });
1625 let n = count.trim().parse().unwrap();
1626 self.prerelease_version.set(Some(n));
1627 n
1628 }
1629
1630 fn rust_release(&self) -> String {
1632 self.release(&self.version)
1633 }
1634
1635 fn rust_package_vers(&self) -> String {
1641 match &self.config.channel[..] {
1642 "stable" => self.version.to_string(),
1643 "beta" => "beta".to_string(),
1644 "nightly" => "nightly".to_string(),
1645 _ => format!("{}-dev", self.version),
1646 }
1647 }
1648
1649 fn rust_version(&self) -> String {
1655 let mut version = self.rust_info().version(self, &self.version);
1656 if let Some(ref s) = self.config.description
1657 && !s.is_empty()
1658 {
1659 version.push_str(" (");
1660 version.push_str(s);
1661 version.push(')');
1662 }
1663 version
1664 }
1665
1666 fn rust_sha(&self) -> Option<&str> {
1668 self.rust_info().sha()
1669 }
1670
1671 fn release_num(&self, package: &str) -> String {
1673 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1674 let toml = t!(fs::read_to_string(toml_file_name));
1675 for line in toml.lines() {
1676 if let Some(stripped) =
1677 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1678 {
1679 return stripped.to_owned();
1680 }
1681 }
1682
1683 panic!("failed to find version in {package}'s Cargo.toml")
1684 }
1685
1686 fn unstable_features(&self) -> bool {
1689 !matches!(&self.config.channel[..], "stable" | "beta")
1690 }
1691
1692 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1696 let mut ret = Vec::new();
1697 let mut list = vec![root.to_owned()];
1698 let mut visited = HashSet::new();
1699 while let Some(krate) = list.pop() {
1700 let krate = self
1701 .crates
1702 .get(&krate)
1703 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1704 ret.push(krate);
1705 for dep in &krate.deps {
1706 if !self.crates.contains_key(dep) {
1707 continue;
1709 }
1710 if visited.insert(dep)
1716 && (dep != "profiler_builtins"
1717 || target
1718 .map(|t| self.config.profiler_enabled(t))
1719 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1720 && (dep != "rustc_codegen_llvm"
1721 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1722 {
1723 list.push(dep.clone());
1724 }
1725 }
1726 }
1727 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1729 }
1730
1731 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1732 if self.config.dry_run() {
1733 return Vec::new();
1734 }
1735
1736 if !stamp.path().exists() {
1737 eprintln!(
1738 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1739 stamp.path().display()
1740 );
1741 crate::exit!(1);
1742 }
1743
1744 let mut paths = Vec::new();
1745 let contents = t!(fs::read(stamp.path()), stamp.path());
1746 for part in contents.split(|b| *b == 0) {
1749 if part.is_empty() {
1750 continue;
1751 }
1752 let dependency_type = match part[0] as char {
1753 'h' => DependencyType::Host,
1754 's' => DependencyType::TargetSelfContained,
1755 't' => DependencyType::Target,
1756 _ => unreachable!(),
1757 };
1758 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1759 paths.push((path, dependency_type));
1760 }
1761 paths
1762 }
1763
1764 #[track_caller]
1769 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1770 self.copy_link_internal(src, dst, true);
1771 }
1772
1773 #[track_caller]
1778 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1779 self.copy_link_internal(src, dst, false);
1780
1781 if file_type.could_have_split_debuginfo()
1782 && let Some(dbg_file) = split_debuginfo(src)
1783 {
1784 self.copy_link_internal(
1785 &dbg_file,
1786 &dst.with_extension(dbg_file.extension().unwrap()),
1787 false,
1788 );
1789 }
1790 }
1791
1792 #[track_caller]
1793 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1794 if self.config.dry_run() {
1795 return;
1796 }
1797 if src == dst {
1798 return;
1799 }
1800
1801 #[cfg(feature = "tracing")]
1802 let _span = trace_io!("file-copy-link", ?src, ?dst);
1803
1804 if let Err(e) = fs::remove_file(dst)
1805 && cfg!(windows)
1806 && e.kind() != io::ErrorKind::NotFound
1807 {
1808 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1811 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1812 }
1813 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1814 let mut src = src.to_path_buf();
1815 if metadata.file_type().is_symlink() {
1816 if dereference_symlinks {
1817 src = t!(fs::canonicalize(src));
1818 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1819 } else {
1820 let link = t!(fs::read_link(src));
1821 t!(self.symlink_file(link, dst));
1822 return;
1823 }
1824 }
1825 if let Ok(()) = fs::hard_link(&src, dst) {
1826 } else {
1829 if let Err(e) = fs::copy(&src, dst) {
1830 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1831 }
1832 t!(fs::set_permissions(dst, metadata.permissions()));
1833
1834 let file_times = fs::FileTimes::new()
1837 .set_accessed(t!(metadata.accessed()))
1838 .set_modified(t!(metadata.modified()));
1839 t!(set_file_times(dst, file_times));
1840 }
1841 }
1842
1843 #[track_caller]
1847 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1848 if self.config.dry_run() {
1849 return;
1850 }
1851 for f in self.read_dir(src) {
1852 let path = f.path();
1853 let name = path.file_name().unwrap();
1854 let dst = dst.join(name);
1855 if t!(f.file_type()).is_dir() {
1856 t!(fs::create_dir_all(&dst));
1857 self.cp_link_r(&path, &dst);
1858 } else {
1859 self.copy_link(&path, &dst, FileType::Regular);
1860 }
1861 }
1862 }
1863
1864 #[track_caller]
1870 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1871 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1873 }
1874
1875 #[track_caller]
1877 fn cp_link_filtered_recurse(
1878 &self,
1879 src: &Path,
1880 dst: &Path,
1881 relative: &Path,
1882 filter: &dyn Fn(&Path) -> bool,
1883 ) {
1884 for f in self.read_dir(src) {
1885 let path = f.path();
1886 let name = path.file_name().unwrap();
1887 let dst = dst.join(name);
1888 let relative = relative.join(name);
1889 if filter(&relative) {
1891 if t!(f.file_type()).is_dir() {
1892 let _ = fs::remove_dir_all(&dst);
1893 self.create_dir(&dst);
1894 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1895 } else {
1896 self.copy_link(&path, &dst, FileType::Regular);
1897 }
1898 }
1899 }
1900 }
1901
1902 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1903 let file_name = src.file_name().unwrap();
1904 let dest = dest_folder.join(file_name);
1905 self.copy_link(src, &dest, FileType::Regular);
1906 }
1907
1908 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1909 if self.config.dry_run() {
1910 return;
1911 }
1912 let dst = dstdir.join(src.file_name().unwrap());
1913
1914 #[cfg(feature = "tracing")]
1915 let _span = trace_io!("install", ?src, ?dst);
1916
1917 t!(fs::create_dir_all(dstdir));
1918 if !src.exists() {
1919 panic!("ERROR: File \"{}\" not found!", src.display());
1920 }
1921
1922 self.copy_link_internal(src, &dst, true);
1923 chmod(&dst, file_type.perms());
1924
1925 if file_type.could_have_split_debuginfo()
1927 && let Some(dbg_file) = split_debuginfo(src)
1928 {
1929 self.install(&dbg_file, dstdir, FileType::Regular);
1930 }
1931 }
1932
1933 fn read(&self, path: &Path) -> String {
1934 if self.config.dry_run() {
1935 return String::new();
1936 }
1937 t!(fs::read_to_string(path))
1938 }
1939
1940 #[track_caller]
1941 fn create_dir(&self, dir: &Path) {
1942 if self.config.dry_run() {
1943 return;
1944 }
1945
1946 #[cfg(feature = "tracing")]
1947 let _span = trace_io!("dir-create", ?dir);
1948
1949 t!(fs::create_dir_all(dir))
1950 }
1951
1952 fn remove_dir(&self, dir: &Path) {
1953 if self.config.dry_run() {
1954 return;
1955 }
1956
1957 #[cfg(feature = "tracing")]
1958 let _span = trace_io!("dir-remove", ?dir);
1959
1960 t!(fs::remove_dir_all(dir))
1961 }
1962
1963 fn clear_dir(&self, dir: &Path) {
1966 if self.config.dry_run() {
1967 return;
1968 }
1969
1970 #[cfg(feature = "tracing")]
1971 let _span = trace_io!("dir-clear", ?dir);
1972
1973 let _ = std::fs::remove_dir_all(dir);
1974 self.create_dir(dir);
1975 }
1976
1977 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1978 let iter = match fs::read_dir(dir) {
1979 Ok(v) => v,
1980 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1981 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1982 };
1983 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1984 }
1985
1986 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1987 #[cfg(unix)]
1988 use std::os::unix::fs::symlink as symlink_file;
1989 #[cfg(windows)]
1990 use std::os::windows::fs::symlink_file;
1991 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1992 }
1993
1994 fn ninja(&self) -> bool {
1997 let mut cmd_finder = crate::core::sanity::Finder::new();
1998
1999 if self.config.ninja_in_file {
2000 if cmd_finder.maybe_have("ninja-build").is_none()
2003 && cmd_finder.maybe_have("ninja").is_none()
2004 {
2005 eprintln!(
2006 "
2007Couldn't find required command: ninja (or ninja-build)
2008
2009You should install ninja as described at
2010<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
2011or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
2012Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
2013to download LLVM rather than building it.
2014"
2015 );
2016 exit!(1);
2017 }
2018 }
2019
2020 if !self.config.ninja_in_file
2028 && self.config.host_target.is_msvc()
2029 && cmd_finder.maybe_have("ninja").is_some()
2030 {
2031 return true;
2032 }
2033
2034 self.config.ninja_in_file
2035 }
2036
2037 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2038 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
2039 }
2040
2041 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2042 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
2043 }
2044
2045 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2046 where
2047 C: Fn(ColorChoice) -> StandardStream,
2048 F: FnOnce(&mut dyn WriteColor) -> R,
2049 {
2050 let choice = match self.config.color {
2051 flags::Color::Always => ColorChoice::Always,
2052 flags::Color::Never => ColorChoice::Never,
2053 flags::Color::Auto if !is_tty => ColorChoice::Never,
2054 flags::Color::Auto => ColorChoice::Auto,
2055 };
2056 let mut stream = constructor(choice);
2057 let result = f(&mut stream);
2058 stream.reset().unwrap();
2059 result
2060 }
2061
2062 pub fn exec_ctx(&self) -> &ExecutionContext {
2063 &self.config.exec_ctx
2064 }
2065
2066 pub fn report_summary(&self, path: &Path, start_time: Instant) {
2067 self.config.exec_ctx.profiler().report_summary(path, start_time);
2068 }
2069
2070 #[cfg(feature = "tracing")]
2071 pub fn report_step_graph(self, directory: &Path) {
2072 self.step_graph.into_inner().store_to_dot_files(directory);
2073 }
2074}
2075
2076impl AsRef<ExecutionContext> for Build {
2077 fn as_ref(&self) -> &ExecutionContext {
2078 &self.config.exec_ctx
2079 }
2080}
2081
2082#[cfg(unix)]
2083fn chmod(path: &Path, perms: u32) {
2084 use std::os::unix::fs::*;
2085 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2086}
2087#[cfg(windows)]
2088fn chmod(_path: &Path, _perms: u32) {}
2089
2090impl Compiler {
2091 pub fn new(stage: u32, host: TargetSelection) -> Self {
2092 Self { stage, host, forced_compiler: false }
2093 }
2094
2095 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2096 self.forced_compiler = forced_compiler;
2097 }
2098
2099 pub fn is_snapshot(&self, build: &Build) -> bool {
2101 self.stage == 0 && self.host == build.host_target
2102 }
2103
2104 pub fn is_forced_compiler(&self) -> bool {
2106 self.forced_compiler
2107 }
2108}
2109
2110fn envify(s: &str) -> String {
2111 s.chars()
2112 .map(|c| match c {
2113 '-' => '_',
2114 c => c,
2115 })
2116 .flat_map(|c| c.to_uppercase())
2117 .collect()
2118}
2119
2120pub fn prepare_behaviour_dump_dir(build: &Build) {
2122 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2123
2124 let dump_path = build.out.join("bootstrap-shims-dump");
2125
2126 let initialized = INITIALIZED.get().unwrap_or(&false);
2127 if !initialized {
2128 if dump_path.exists() {
2130 t!(fs::remove_dir_all(&dump_path));
2131 }
2132
2133 t!(fs::create_dir_all(&dump_path));
2134
2135 t!(INITIALIZED.set(true));
2136 }
2137}