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 cc::Tool;
30use termcolor::{ColorChoice, StandardStream, WriteColor};
31use utils::build_stamp::BuildStamp;
32use utils::channel::GitInfo;
33use utils::exec::ExecutionContext;
34
35use crate::core::builder;
36use crate::core::builder::Kind;
37use crate::core::config::{BootstrapOverrideLld, DryRun, LlvmLibunwind, TargetSelection, flags};
38use crate::utils::exec::{BootstrapCommand, command};
39use crate::utils::helpers::{self, dir_is_empty, exe, libdir, set_file_times, split_debuginfo};
40
41mod core;
42mod utils;
43
44#[cfg(feature = "tracing")]
45pub use core::builder::STEP_SPAN_TARGET;
46pub use core::builder::{PathSet, StepStack};
47pub use core::config::flags::{Flags, Subcommand};
48pub use core::config::{ChangeId, Config};
49
50#[cfg(feature = "tracing")]
51use tracing::{instrument, span};
52pub use utils::change_tracker::{
53 CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
54};
55pub use utils::helpers::{PanicTracker, symlink_dir};
56#[cfg(feature = "tracing")]
57pub use utils::tracing::setup_tracing;
58
59use crate::core::build_steps::vendor::VENDOR_DIR;
60
61const LLVM_TOOLS: &[&str] = &[
62 "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", ];
77
78const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
80
81#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
85 (Some(Mode::Rustc), "bootstrap", None),
86 (Some(Mode::Codegen), "bootstrap", None),
87 (Some(Mode::ToolRustcPrivate), "bootstrap", None),
88 (Some(Mode::ToolStd), "bootstrap", None),
89 (Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
90 (Some(Mode::ToolStd), "rust_analyzer", None),
91 ];
95
96#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
102pub struct Compiler {
103 stage: u32,
104 host: TargetSelection,
105 forced_compiler: bool,
109}
110
111impl std::hash::Hash for Compiler {
112 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
113 self.stage.hash(state);
114 self.host.hash(state);
115 }
116}
117
118impl PartialEq for Compiler {
119 fn eq(&self, other: &Self) -> bool {
120 self.stage == other.stage && self.host == other.host
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
126pub enum CodegenBackendKind {
127 #[default]
128 Llvm,
129 Cranelift,
130 Gcc,
131 Custom(String),
132}
133
134impl CodegenBackendKind {
135 pub fn name(&self) -> &str {
138 match self {
139 CodegenBackendKind::Llvm => "llvm",
140 CodegenBackendKind::Cranelift => "cranelift",
141 CodegenBackendKind::Gcc => "gcc",
142 CodegenBackendKind::Custom(name) => name,
143 }
144 }
145
146 pub fn crate_name(&self) -> String {
148 format!("rustc_codegen_{}", self.name())
149 }
150
151 pub fn is_llvm(&self) -> bool {
152 matches!(self, Self::Llvm)
153 }
154
155 pub fn is_cranelift(&self) -> bool {
156 matches!(self, Self::Cranelift)
157 }
158
159 pub fn is_gcc(&self) -> bool {
160 matches!(self, Self::Gcc)
161 }
162}
163
164impl std::str::FromStr for CodegenBackendKind {
165 type Err = &'static str;
166
167 fn from_str(s: &str) -> Result<Self, Self::Err> {
168 match s.to_lowercase().as_str() {
169 "" => Err("Invalid empty backend name"),
170 "gcc" => Ok(Self::Gcc),
171 "llvm" => Ok(Self::Llvm),
172 "cranelift" => Ok(Self::Cranelift),
173 _ => Ok(Self::Custom(s.to_string())),
174 }
175 }
176}
177
178#[derive(PartialEq, Eq, Copy, Clone, Debug)]
179pub enum TestTarget {
180 Default,
182 AllTargets,
184 DocOnly,
186 Tests,
188}
189
190impl TestTarget {
191 fn runs_doctests(&self) -> bool {
192 matches!(self, TestTarget::DocOnly | TestTarget::Default)
193 }
194}
195
196pub enum GitRepo {
197 Rustc,
198 Llvm,
199}
200
201pub struct Build {
212 config: Config,
214
215 version: String,
217
218 src: PathBuf,
220 out: PathBuf,
221 bootstrap_out: PathBuf,
222 cargo_info: GitInfo,
223 rust_analyzer_info: GitInfo,
224 clippy_info: GitInfo,
225 miri_info: GitInfo,
226 rustfmt_info: GitInfo,
227 enzyme_info: GitInfo,
228 in_tree_llvm_info: GitInfo,
229 in_tree_gcc_info: GitInfo,
230 local_rebuild: bool,
231 fail_fast: bool,
232 test_target: TestTarget,
233 verbosity: usize,
234
235 host_target: TargetSelection,
237 hosts: Vec<TargetSelection>,
239 targets: Vec<TargetSelection>,
241
242 initial_rustc: PathBuf,
243 initial_rustdoc: PathBuf,
244 initial_cargo: PathBuf,
245 initial_lld: PathBuf,
246 initial_relative_libdir: PathBuf,
247 initial_sysroot: PathBuf,
248
249 cc: HashMap<TargetSelection, cc::Tool>,
252 cxx: HashMap<TargetSelection, cc::Tool>,
253 ar: HashMap<TargetSelection, PathBuf>,
254 ranlib: HashMap<TargetSelection, PathBuf>,
255 wasi_sdk_path: Option<PathBuf>,
256
257 crates: HashMap<String, Crate>,
260 crate_paths: HashMap<PathBuf, String>,
261 is_sudo: bool,
262 prerelease_version: Cell<Option<u32>>,
263
264 #[cfg(feature = "build-metrics")]
265 metrics: crate::utils::metrics::BuildMetrics,
266
267 #[cfg(feature = "tracing")]
268 step_graph: std::cell::RefCell<crate::utils::step_graph::StepGraph>,
269}
270
271#[derive(Debug, Clone)]
272struct Crate {
273 name: String,
274 deps: HashSet<String>,
275 path: PathBuf,
276 features: Vec<String>,
277}
278
279impl Crate {
280 fn local_path(&self, build: &Build) -> PathBuf {
281 self.path.strip_prefix(&build.config.src).unwrap().into()
282 }
283}
284
285#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
287pub enum DependencyType {
288 Host,
290 Target,
292 TargetSelfContained,
294}
295
296#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
301pub enum Mode {
302 Std,
304
305 Rustc,
307
308 Codegen,
310
311 ToolBootstrap,
323
324 ToolTarget,
335
336 ToolStd,
340
341 ToolRustcPrivate,
347}
348
349impl Mode {
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.initial_rustdoc.clone(),
546 initial_cargo: config.initial_cargo.clone(),
547 initial_sysroot: config.initial_sysroot.clone(),
548 local_rebuild: config.local_rebuild,
549 fail_fast: config.cmd.fail_fast(),
550 test_target: config.cmd.test_target(),
551 verbosity: config.exec_ctx.verbosity as usize,
552
553 host_target: config.host_target,
554 hosts: config.hosts.clone(),
555 targets: config.targets.clone(),
556
557 config,
558 version: version.to_string(),
559 src,
560 out,
561 bootstrap_out,
562
563 cargo_info,
564 rust_analyzer_info,
565 clippy_info,
566 miri_info,
567 rustfmt_info,
568 enzyme_info,
569 in_tree_llvm_info,
570 in_tree_gcc_info,
571 cc: HashMap::new(),
572 cxx: HashMap::new(),
573 ar: HashMap::new(),
574 ranlib: HashMap::new(),
575 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
576 crates: HashMap::new(),
577 crate_paths: HashMap::new(),
578 is_sudo,
579 prerelease_version: Cell::new(None),
580
581 #[cfg(feature = "build-metrics")]
582 metrics: crate::utils::metrics::BuildMetrics::init(),
583
584 #[cfg(feature = "tracing")]
585 step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()),
586 };
587
588 let local_version_verbose = command(&build.initial_rustc)
591 .run_in_dry_run()
592 .args(["--version", "--verbose"])
593 .run_capture_stdout(&build)
594 .stdout();
595 let local_release = local_version_verbose
596 .lines()
597 .filter_map(|x| x.strip_prefix("release:"))
598 .next()
599 .unwrap()
600 .trim();
601 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
602 build.do_if_verbose(|| println!("auto-detected local-rebuild {local_release}"));
603 build.local_rebuild = true;
604 }
605
606 build.do_if_verbose(|| println!("finding compilers"));
607 utils::cc_detect::fill_compilers(&mut build);
608 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
614 build.do_if_verbose(|| println!("running sanity check"));
615 crate::core::sanity::check(&mut build);
616
617 let rust_submodules = ["library/backtrace"];
620 for s in rust_submodules {
621 build.require_submodule(
622 s,
623 Some(
624 "The submodule is required for the standard library \
625 and the main Cargo workspace.",
626 ),
627 );
628 }
629 build.update_existing_submodules();
631
632 build.do_if_verbose(|| println!("learning about cargo"));
633 crate::core::metadata::build(&mut build);
634 }
635
636 let build_triple = build.out.join(build.host_target);
638 t!(fs::create_dir_all(&build_triple));
639 let host = build.out.join("host");
640 if host.is_symlink() {
641 #[cfg(windows)]
644 t!(fs::remove_dir(&host));
645 #[cfg(not(windows))]
646 t!(fs::remove_file(&host));
647 }
648 t!(
649 symlink_dir(&build.config, &build_triple, &host),
650 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
651 );
652
653 build
654 }
655
656 #[cfg_attr(
665 feature = "tracing",
666 instrument(
667 level = "trace",
668 name = "Build::require_submodule",
669 skip_all,
670 fields(submodule = submodule),
671 ),
672 )]
673 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
674 if self.rust_info().is_from_tarball() {
675 return;
676 }
677
678 if self.config.dry_run() {
679 return;
680 }
681
682 if cfg!(test) && !self.config.submodules() {
685 return;
686 }
687 self.config.update_submodule(submodule);
688 let absolute_path = self.config.src.join(submodule);
689 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
690 let maybe_enable = if !self.config.submodules()
691 && self.config.rust_info.is_managed_git_subrepository()
692 {
693 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
694 } else {
695 ""
696 };
697 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
698 eprintln!(
699 "submodule {submodule} does not appear to be checked out, \
700 but it is required for this step{maybe_enable}{err_hint}"
701 );
702 exit!(1);
703 }
704 }
705
706 fn update_existing_submodules(&self) {
709 if !self.config.submodules() {
712 return;
713 }
714 let output = helpers::git(Some(&self.src))
715 .args(["config", "--file"])
716 .arg(".gitmodules")
717 .args(["--get-regexp", "path"])
718 .run_capture(self)
719 .stdout();
720 std::thread::scope(|s| {
721 for line in output.lines() {
724 let submodule = line.split_once(' ').unwrap().1;
725 let config = self.config.clone();
726 s.spawn(move || {
727 Self::update_existing_submodule(&config, submodule);
728 });
729 }
730 });
731 }
732
733 pub fn update_existing_submodule(config: &Config, submodule: &str) {
735 if !config.submodules() {
737 return;
738 }
739
740 if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
741 config.update_submodule(submodule);
742 }
743 }
744
745 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
747 pub fn build(&mut self) {
748 trace!("setting up job management");
749 unsafe {
750 crate::utils::job::setup(self);
751 }
752
753 {
755 #[cfg(feature = "tracing")]
756 let _hardcoded_span =
757 span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
758 .entered();
759
760 match &self.config.cmd {
761 Subcommand::Format { check, all } => {
762 return core::build_steps::format::format(
763 &builder::Builder::new(self),
764 *check,
765 *all,
766 &self.config.paths,
767 );
768 }
769 Subcommand::Perf(args) => {
770 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
771 }
772 _cmd => {
773 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
774 }
775 }
776
777 debug!("handling subcommand normally");
778 }
779
780 if !self.config.dry_run() {
781 #[cfg(feature = "tracing")]
782 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
783
784 {
787 #[cfg(feature = "tracing")]
788 let _sanity_check_span =
789 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
790 self.config.set_dry_run(DryRun::SelfCheck);
791 let builder = builder::Builder::new(self);
792 builder.execute_cli();
793 }
794
795 {
797 #[cfg(feature = "tracing")]
798 let _actual_run_span =
799 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
800 self.config.set_dry_run(DryRun::Disabled);
801 let builder = builder::Builder::new(self);
802 builder.execute_cli();
803 }
804 } else {
805 #[cfg(feature = "tracing")]
806 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
807
808 let builder = builder::Builder::new(self);
809 builder.execute_cli();
810 }
811
812 #[cfg(feature = "tracing")]
813 debug!("checking for postponed test failures from `test --no-fail-fast`");
814
815 self.config.exec_ctx().report_failures_and_exit();
817
818 #[cfg(feature = "build-metrics")]
819 self.metrics.persist(self);
820 }
821
822 fn rust_info(&self) -> &GitInfo {
823 &self.config.rust_info
824 }
825
826 fn std_features(&self, target: TargetSelection) -> String {
829 let mut features: BTreeSet<&str> =
830 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
831
832 match self.config.llvm_libunwind(target) {
833 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
834 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
835 LlvmLibunwind::No => false,
836 };
837
838 if self.config.backtrace {
839 features.insert("backtrace");
840 }
841
842 if self.config.profiler_enabled(target) {
843 features.insert("profiler");
844 }
845
846 if target.contains("zkvm") {
848 features.insert("compiler-builtins-mem");
849 }
850
851 if self.config.llvm_enzyme {
852 features.insert("llvm_enzyme");
853 }
854
855 features.into_iter().collect::<Vec<_>>().join(" ")
856 }
857
858 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
860 let possible_features_by_crates: HashSet<_> = crates
861 .iter()
862 .flat_map(|krate| &self.crates[krate].features)
863 .map(std::ops::Deref::deref)
864 .collect();
865 let check = |feature: &str| -> bool {
866 crates.is_empty() || possible_features_by_crates.contains(feature)
867 };
868 let mut features = vec![];
869 if self.config.jemalloc(target) && check("jemalloc") {
870 features.push("jemalloc");
871 }
872 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
873 features.push("llvm");
874 }
875 if self.config.llvm_enzyme {
876 features.push("llvm_enzyme");
877 }
878 if self.config.llvm_offload {
879 features.push("llvm_offload");
880 }
881 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
883 features.push("rustc_randomized_layouts");
884 }
885 if self.config.compile_time_deps && kind == Kind::Check {
886 features.push("check_only");
887 }
888
889 if crates.iter().any(|c| c == "rustc_transmute") {
890 features.push("rustc");
893 }
894
895 if !self.config.rust_debug_logging && check("max_level_info") {
901 features.push("max_level_info");
902 }
903
904 features.join(" ")
905 }
906
907 fn cargo_dir(&self, mode: Mode) -> &'static str {
910 match (mode, self.config.rust_optimize.is_release()) {
911 (Mode::Std, _) => "dist",
912 (_, true) => "release",
913 (_, false) => "debug",
914 }
915 }
916
917 fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
918 let out = self
919 .out
920 .join(build_compiler.host)
921 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
922 t!(fs::create_dir_all(&out));
923 out
924 }
925
926 fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
931 use std::fmt::Write;
932
933 fn bootstrap_tool() -> (Option<u32>, &'static str) {
934 (None, "bootstrap-tools")
935 }
936 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
937 (Some(build_compiler.stage + 1), "tools")
938 }
939
940 let (stage, suffix) = match mode {
941 Mode::Std => (Some(build_compiler.stage), "std"),
943 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
945 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
946 Mode::ToolBootstrap => bootstrap_tool(),
947 Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
948 Mode::ToolTarget => {
949 if build_compiler.stage == 0 {
952 bootstrap_tool()
953 } else {
954 staged_tool(build_compiler)
955 }
956 }
957 };
958 let path = self.out.join(build_compiler.host);
959 let mut dir_name = String::new();
960 if let Some(stage) = stage {
961 write!(dir_name, "stage{stage}-").unwrap();
962 }
963 dir_name.push_str(suffix);
964 path.join(dir_name)
965 }
966
967 fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
971 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
972 }
973
974 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
979 if self.config.llvm_from_ci && self.config.is_host_target(target) {
980 self.config.ci_llvm_root()
981 } else {
982 self.out.join(target).join("llvm")
983 }
984 }
985
986 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
987 self.out.join(&*target.triple).join("enzyme")
988 }
989
990 fn offload_out(&self, target: TargetSelection) -> PathBuf {
991 self.out.join(&*target.triple).join("offload")
992 }
993
994 fn lld_out(&self, target: TargetSelection) -> PathBuf {
995 self.out.join(target).join("lld")
996 }
997
998 fn doc_out(&self, target: TargetSelection) -> PathBuf {
1000 self.out.join(target).join("doc")
1001 }
1002
1003 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
1005 self.out.join(target).join("json-doc")
1006 }
1007
1008 fn test_out(&self, target: TargetSelection) -> PathBuf {
1009 self.out.join(target).join("test")
1010 }
1011
1012 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
1014 self.out.join(target).join("compiler-doc")
1015 }
1016
1017 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
1019 self.out.join(target).join("md-doc")
1020 }
1021
1022 fn vendored_crates_path(&self) -> Option<PathBuf> {
1024 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1025 }
1026
1027 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
1029 let target_config = self.config.target_config.get(&target);
1030 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
1031 s.to_path_buf()
1032 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
1033 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
1034 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
1035 if filecheck.exists() {
1036 filecheck
1037 } else {
1038 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
1041 let lib_filecheck =
1042 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
1043 if lib_filecheck.exists() {
1044 lib_filecheck
1045 } else {
1046 filecheck
1050 }
1051 }
1052 } else {
1053 let base = self.llvm_out(target).join("build");
1054 let base = if !self.ninja() && target.is_msvc() {
1055 if self.config.llvm_optimize {
1056 if self.config.llvm_release_debuginfo {
1057 base.join("RelWithDebInfo")
1058 } else {
1059 base.join("Release")
1060 }
1061 } else {
1062 base.join("Debug")
1063 }
1064 } else {
1065 base
1066 };
1067 base.join("bin").join(exe("FileCheck", target))
1068 }
1069 }
1070
1071 fn native_dir(&self, target: TargetSelection) -> PathBuf {
1073 self.out.join(target).join("native")
1074 }
1075
1076 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1079 self.native_dir(target).join("rust-test-helpers")
1080 }
1081
1082 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1084 if env::var_os("RUST_TEST_THREADS").is_none() {
1085 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1086 }
1087 }
1088
1089 fn rustc_snapshot_libdir(&self) -> PathBuf {
1091 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1092 }
1093
1094 fn rustc_snapshot_sysroot(&self) -> &Path {
1096 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1097 SYSROOT_CACHE.get_or_init(|| {
1098 command(&self.initial_rustc)
1099 .run_in_dry_run()
1100 .args(["--print", "sysroot"])
1101 .run_capture_stdout(self)
1102 .stdout()
1103 .trim()
1104 .to_owned()
1105 .into()
1106 })
1107 }
1108
1109 fn info(&self, msg: &str) {
1110 match self.config.get_dry_run() {
1111 DryRun::SelfCheck => (),
1112 DryRun::Disabled | DryRun::UserSelected => {
1113 println!("{msg}");
1114 }
1115 }
1116 }
1117
1118 #[must_use = "Groups should not be dropped until the Step finishes running"]
1130 #[track_caller]
1131 fn msg(
1132 &self,
1133 action: impl Into<Kind>,
1134 what: impl Display,
1135 mode: impl Into<Option<Mode>>,
1136 target_and_stage: impl Into<TargetAndStage>,
1137 target: impl Into<Option<TargetSelection>>,
1138 ) -> Option<gha::Group> {
1139 let target_and_stage = target_and_stage.into();
1140 let action = action.into();
1141 assert!(
1142 action != Kind::Test,
1143 "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1144 );
1145
1146 let actual_stage = match mode.into() {
1147 Some(Mode::Std) => target_and_stage.stage,
1149 Some(
1151 Mode::Rustc
1152 | Mode::Codegen
1153 | Mode::ToolBootstrap
1154 | Mode::ToolTarget
1155 | Mode::ToolStd
1156 | Mode::ToolRustcPrivate,
1157 )
1158 | None => target_and_stage.stage + 1,
1159 };
1160
1161 let action = action.description();
1162 let what = what.to_string();
1163 let msg = |fmt| {
1164 let space = if !what.is_empty() { " " } else { "" };
1165 format!("{action} stage{actual_stage} {what}{space}{fmt}")
1166 };
1167 let msg = if let Some(target) = target.into() {
1168 let build_stage = target_and_stage.stage;
1169 let host = target_and_stage.target;
1170 if host == target {
1171 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1172 } else {
1173 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1174 }
1175 } else {
1176 msg(format_args!(""))
1177 };
1178 self.group(&msg)
1179 }
1180
1181 #[must_use = "Groups should not be dropped until the Step finishes running"]
1187 #[track_caller]
1188 fn msg_test(
1189 &self,
1190 what: impl Display,
1191 target: TargetSelection,
1192 stage: u32,
1193 ) -> Option<gha::Group> {
1194 let action = Kind::Test.description();
1195 let msg = format!("{action} stage{stage} {what} ({target})");
1196 self.group(&msg)
1197 }
1198
1199 #[must_use = "Groups should not be dropped until the Step finishes running"]
1203 #[track_caller]
1204 fn msg_unstaged(
1205 &self,
1206 action: impl Into<Kind>,
1207 what: impl Display,
1208 target: TargetSelection,
1209 ) -> Option<gha::Group> {
1210 let action = action.into().description();
1211 let msg = format!("{action} {what} for {target}");
1212 self.group(&msg)
1213 }
1214
1215 #[track_caller]
1216 fn group(&self, msg: &str) -> Option<gha::Group> {
1217 match self.config.get_dry_run() {
1218 DryRun::SelfCheck => None,
1219 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1220 }
1221 }
1222
1223 fn jobs(&self) -> u32 {
1226 self.config.jobs.unwrap_or_else(|| {
1227 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1228 })
1229 }
1230
1231 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1232 if !self.config.rust_remap_debuginfo {
1233 return None;
1234 }
1235
1236 match which {
1237 GitRepo::Rustc => {
1238 let sha = self.rust_sha().unwrap_or(&self.version);
1239
1240 match remap_scheme {
1241 RemapScheme::Compiler => {
1242 Some(format!("/rustc-dev/{sha}"))
1251 }
1252 RemapScheme::NonCompiler => {
1253 Some(format!("/rustc/{sha}"))
1255 }
1256 }
1257 }
1258 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1259 }
1260 }
1261
1262 fn cc(&self, target: TargetSelection) -> PathBuf {
1264 if self.config.dry_run() {
1265 return PathBuf::new();
1266 }
1267 self.cc[&target].path().into()
1268 }
1269
1270 fn cc_tool(&self, target: TargetSelection) -> Tool {
1272 self.cc[&target].clone()
1273 }
1274
1275 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1277 self.cxx[&target].clone()
1278 }
1279
1280 fn cc_handled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1283 if self.config.dry_run() {
1284 return Vec::new();
1285 }
1286 let base = match c {
1287 CLang::C => self.cc[&target].clone(),
1288 CLang::Cxx => self.cxx[&target].clone(),
1289 };
1290
1291 base.args()
1294 .iter()
1295 .map(|s| s.to_string_lossy().into_owned())
1296 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1297 .collect::<Vec<String>>()
1298 }
1299
1300 fn cc_unhandled_cflags(
1302 &self,
1303 target: TargetSelection,
1304 which: GitRepo,
1305 c: CLang,
1306 ) -> Vec<String> {
1307 let mut base = Vec::new();
1308
1309 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1313 base.push("-stdlib=libc++".into());
1314 }
1315
1316 if &*target.triple == "i686-pc-windows-gnu" {
1320 base.push("-fno-omit-frame-pointer".into());
1321 }
1322
1323 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1324 let map = format!("{}={}", self.src.display(), map_to);
1325 let cc = self.cc(target);
1326 if cc.ends_with("clang") || cc.ends_with("gcc") {
1327 base.push(format!("-fdebug-prefix-map={map}"));
1328 } else if cc.ends_with("clang-cl.exe") {
1329 base.push("-Xclang".into());
1330 base.push(format!("-fdebug-prefix-map={map}"));
1331 }
1332 }
1333 base
1334 }
1335
1336 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1338 if self.config.dry_run() {
1339 return None;
1340 }
1341 self.ar.get(&target).cloned()
1342 }
1343
1344 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1346 if self.config.dry_run() {
1347 return None;
1348 }
1349 self.ranlib.get(&target).cloned()
1350 }
1351
1352 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1354 if self.config.dry_run() {
1355 return Ok(PathBuf::new());
1356 }
1357 match self.cxx.get(&target) {
1358 Some(p) => Ok(p.path().into()),
1359 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1360 }
1361 }
1362
1363 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1365 if self.config.dry_run() {
1366 return Some(PathBuf::new());
1367 }
1368 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1369 {
1370 Some(linker)
1371 } else if target.contains("vxworks") {
1372 Some(self.cxx[&target].path().into())
1375 } else if !self.config.is_host_target(target)
1376 && helpers::use_host_linker(target)
1377 && !target.is_msvc()
1378 {
1379 Some(self.cc(target))
1380 } else if self.config.bootstrap_override_lld.is_used()
1381 && self.is_lld_direct_linker(target)
1382 && self.host_target == target
1383 {
1384 match self.config.bootstrap_override_lld {
1385 BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1386 BootstrapOverrideLld::External => Some("lld".into()),
1387 BootstrapOverrideLld::None => None,
1388 }
1389 } else {
1390 None
1391 }
1392 }
1393
1394 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1397 target.is_msvc()
1398 }
1399
1400 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1402 if target.contains("pc-windows-msvc") {
1403 Some(true)
1404 } else {
1405 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1406 }
1407 }
1408
1409 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1414 let configured_root = self
1415 .config
1416 .target_config
1417 .get(&target)
1418 .and_then(|t| t.musl_root.as_ref())
1419 .or(self.config.musl_root.as_ref())
1420 .map(|p| &**p);
1421
1422 if self.config.is_host_target(target) && configured_root.is_none() {
1423 Some(Path::new("/usr"))
1424 } else {
1425 configured_root
1426 }
1427 }
1428
1429 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1431 self.config
1432 .target_config
1433 .get(&target)
1434 .and_then(|t| t.musl_libdir.clone())
1435 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1436 }
1437
1438 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1445 let configured =
1446 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1447 if let Some(path) = configured {
1448 return Some(path.join("lib").join(target.to_string()));
1449 }
1450 let mut env_root = self.wasi_sdk_path.clone()?;
1451 env_root.push("share");
1452 env_root.push("wasi-sysroot");
1453 env_root.push("lib");
1454 env_root.push(target.to_string());
1455 Some(env_root)
1456 }
1457
1458 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1460 self.config.target_config.get(&target).map(|t| t.no_std)
1461 }
1462
1463 fn remote_tested(&self, target: TargetSelection) -> bool {
1466 self.qemu_rootfs(target).is_some()
1467 || target.contains("android")
1468 || env::var_os("TEST_DEVICE_ADDR").is_some()
1469 }
1470
1471 fn runner(&self, target: TargetSelection) -> Option<String> {
1477 let configured_runner =
1478 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1479 if let Some(runner) = configured_runner {
1480 return Some(runner.to_owned());
1481 }
1482
1483 if target.starts_with("wasm") && target.contains("wasi") {
1484 self.default_wasi_runner(target)
1485 } else {
1486 None
1487 }
1488 }
1489
1490 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1494 let mut finder = crate::core::sanity::Finder::new();
1495
1496 if let Some(path) = finder.maybe_have("wasmtime")
1500 && let Ok(mut path) = path.into_os_string().into_string()
1501 {
1502 path.push_str(" run -Wexceptions -C cache=n --dir .");
1503 path.push_str(" --env RUSTC_BOOTSTRAP");
1510
1511 if target.contains("wasip2") {
1512 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1513 }
1514
1515 return Some(path);
1516 }
1517
1518 None
1519 }
1520
1521 fn tool_enabled(&self, tool: &str) -> bool {
1526 if !self.config.extended {
1527 return false;
1528 }
1529 match &self.config.tools {
1530 Some(set) => set.contains(tool),
1531 None => true,
1532 }
1533 }
1534
1535 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1541 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1542 }
1543
1544 fn extended_error_dir(&self) -> PathBuf {
1546 self.out.join("tmp/extended-error-metadata")
1547 }
1548
1549 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1568 !self.config.full_bootstrap
1569 && !self.config.download_rustc()
1570 && stage >= 2
1571 && (self.hosts.contains(&target) || target == self.host_target)
1572 }
1573
1574 fn force_use_stage2(&self, stage: u32) -> bool {
1580 self.config.download_rustc() && stage >= 2
1581 }
1582
1583 fn release(&self, num: &str) -> String {
1589 match &self.config.channel[..] {
1590 "stable" => num.to_string(),
1591 "beta" => {
1592 if !self.config.omit_git_hash {
1593 format!("{}-beta.{}", num, self.beta_prerelease_version())
1594 } else {
1595 format!("{num}-beta")
1596 }
1597 }
1598 "nightly" => format!("{num}-nightly"),
1599 _ => format!("{num}-dev"),
1600 }
1601 }
1602
1603 fn beta_prerelease_version(&self) -> u32 {
1604 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1605 let version = fs::read_to_string(version_file).ok()?;
1606
1607 helpers::extract_beta_rev(&version)
1608 }
1609
1610 if let Some(s) = self.prerelease_version.get() {
1611 return s;
1612 }
1613
1614 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1618 helpers::git(Some(&self.src))
1622 .arg("rev-list")
1623 .arg("--count")
1624 .arg("--merges")
1625 .arg(format!(
1626 "refs/remotes/origin/{}..HEAD",
1627 self.config.stage0_metadata.config.nightly_branch
1628 ))
1629 .run_in_dry_run()
1630 .run_capture(self)
1631 .stdout()
1632 });
1633 let n = count.trim().parse().unwrap();
1634 self.prerelease_version.set(Some(n));
1635 n
1636 }
1637
1638 fn rust_release(&self) -> String {
1640 self.release(&self.version)
1641 }
1642
1643 fn rust_package_vers(&self) -> String {
1649 match &self.config.channel[..] {
1650 "stable" => self.version.to_string(),
1651 "beta" => "beta".to_string(),
1652 "nightly" => "nightly".to_string(),
1653 _ => format!("{}-dev", self.version),
1654 }
1655 }
1656
1657 fn rust_version(&self) -> String {
1663 let mut version = self.rust_info().version(self, &self.version);
1664 if let Some(ref s) = self.config.description
1665 && !s.is_empty()
1666 {
1667 version.push_str(" (");
1668 version.push_str(s);
1669 version.push(')');
1670 }
1671 version
1672 }
1673
1674 fn rust_sha(&self) -> Option<&str> {
1676 self.rust_info().sha()
1677 }
1678
1679 fn release_num(&self, package: &str) -> String {
1681 if self.config.dry_run() {
1682 return "0.0.0 (dry-run)".into();
1683 }
1684 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1685 let toml = t!(fs::read_to_string(toml_file_name));
1686 for line in toml.lines() {
1687 if let Some(stripped) =
1688 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1689 {
1690 return stripped.to_owned();
1691 }
1692 }
1693
1694 panic!("failed to find version in {package}'s Cargo.toml")
1695 }
1696
1697 fn unstable_features(&self) -> bool {
1700 !matches!(&self.config.channel[..], "stable" | "beta")
1701 }
1702
1703 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1707 let mut ret = Vec::new();
1708 let mut list = vec![root.to_owned()];
1709 let mut visited = HashSet::new();
1710 while let Some(krate) = list.pop() {
1711 let krate = self
1712 .crates
1713 .get(&krate)
1714 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1715 ret.push(krate);
1716 for dep in &krate.deps {
1717 if !self.crates.contains_key(dep) {
1718 continue;
1720 }
1721 if visited.insert(dep)
1727 && (dep != "profiler_builtins"
1728 || target
1729 .map(|t| self.config.profiler_enabled(t))
1730 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1731 && (dep != "rustc_codegen_llvm"
1732 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1733 {
1734 list.push(dep.clone());
1735 }
1736 }
1737 }
1738 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1740 }
1741
1742 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1743 if self.config.dry_run() {
1744 return Vec::new();
1745 }
1746
1747 if !stamp.path().exists() {
1748 eprintln!(
1749 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1750 stamp.path().display()
1751 );
1752 crate::exit!(1);
1753 }
1754
1755 let mut paths = Vec::new();
1756 let contents = t!(fs::read(stamp.path()), stamp.path());
1757 for part in contents.split(|b| *b == 0) {
1760 if part.is_empty() {
1761 continue;
1762 }
1763 let dependency_type = match part[0] as char {
1764 'h' => DependencyType::Host,
1765 's' => DependencyType::TargetSelfContained,
1766 't' => DependencyType::Target,
1767 _ => unreachable!(),
1768 };
1769 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1770 paths.push((path, dependency_type));
1771 }
1772 paths
1773 }
1774
1775 #[track_caller]
1780 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1781 self.copy_link_internal(src, dst, true);
1782 }
1783
1784 #[track_caller]
1789 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1790 self.copy_link_internal(src, dst, false);
1791
1792 if file_type.could_have_split_debuginfo()
1793 && let Some(dbg_file) = split_debuginfo(src)
1794 {
1795 self.copy_link_internal(
1796 &dbg_file,
1797 &dst.with_extension(dbg_file.extension().unwrap()),
1798 false,
1799 );
1800 }
1801 }
1802
1803 #[track_caller]
1804 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1805 if self.config.dry_run() {
1806 return;
1807 }
1808 if src == dst {
1809 return;
1810 }
1811
1812 #[cfg(feature = "tracing")]
1813 let _span = trace_io!("file-copy-link", ?src, ?dst);
1814
1815 if let Err(e) = fs::remove_file(dst)
1816 && cfg!(windows)
1817 && e.kind() != io::ErrorKind::NotFound
1818 {
1819 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1822 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1823 }
1824 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1825 let mut src = src.to_path_buf();
1826 if metadata.file_type().is_symlink() {
1827 if dereference_symlinks {
1828 src = t!(fs::canonicalize(src));
1829 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1830 } else {
1831 let link = t!(fs::read_link(src));
1832 t!(self.symlink_file(link, dst));
1833 return;
1834 }
1835 }
1836 if let Ok(()) = fs::hard_link(&src, dst) {
1837 } else {
1840 if let Err(e) = fs::copy(&src, dst) {
1841 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1842 }
1843 t!(fs::set_permissions(dst, metadata.permissions()));
1844
1845 let file_times = fs::FileTimes::new()
1848 .set_accessed(t!(metadata.accessed()))
1849 .set_modified(t!(metadata.modified()));
1850 t!(set_file_times(dst, file_times));
1851 }
1852 }
1853
1854 #[track_caller]
1858 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1859 if self.config.dry_run() {
1860 return;
1861 }
1862 for f in self.read_dir(src) {
1863 let path = f.path();
1864 let name = path.file_name().unwrap();
1865 let dst = dst.join(name);
1866 if t!(f.file_type()).is_dir() {
1867 t!(fs::create_dir_all(&dst));
1868 self.cp_link_r(&path, &dst);
1869 } else {
1870 self.copy_link(&path, &dst, FileType::Regular);
1871 }
1872 }
1873 }
1874
1875 #[track_caller]
1881 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1882 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1884 }
1885
1886 #[track_caller]
1888 fn cp_link_filtered_recurse(
1889 &self,
1890 src: &Path,
1891 dst: &Path,
1892 relative: &Path,
1893 filter: &dyn Fn(&Path) -> bool,
1894 ) {
1895 for f in self.read_dir(src) {
1896 let path = f.path();
1897 let name = path.file_name().unwrap();
1898 let dst = dst.join(name);
1899 let relative = relative.join(name);
1900 if filter(&relative) {
1902 if t!(f.file_type()).is_dir() {
1903 let _ = fs::remove_dir_all(&dst);
1904 self.create_dir(&dst);
1905 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1906 } else {
1907 self.copy_link(&path, &dst, FileType::Regular);
1908 }
1909 }
1910 }
1911 }
1912
1913 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1914 let file_name = src.file_name().unwrap();
1915 let dest = dest_folder.join(file_name);
1916 self.copy_link(src, &dest, FileType::Regular);
1917 }
1918
1919 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1920 if self.config.dry_run() {
1921 return;
1922 }
1923 let dst = dstdir.join(src.file_name().unwrap());
1924
1925 #[cfg(feature = "tracing")]
1926 let _span = trace_io!("install", ?src, ?dst);
1927
1928 t!(fs::create_dir_all(dstdir));
1929 if !src.exists() {
1930 panic!("ERROR: File \"{}\" not found!", src.display());
1931 }
1932
1933 self.copy_link_internal(src, &dst, true);
1934 chmod(&dst, file_type.perms());
1935
1936 if file_type.could_have_split_debuginfo()
1938 && let Some(dbg_file) = split_debuginfo(src)
1939 {
1940 self.install(&dbg_file, dstdir, FileType::Regular);
1941 }
1942 }
1943
1944 fn read(&self, path: &Path) -> String {
1945 if self.config.dry_run() {
1946 return String::new();
1947 }
1948 t!(fs::read_to_string(path))
1949 }
1950
1951 #[track_caller]
1952 fn create_dir(&self, dir: &Path) {
1953 if self.config.dry_run() {
1954 return;
1955 }
1956
1957 #[cfg(feature = "tracing")]
1958 let _span = trace_io!("dir-create", ?dir);
1959
1960 t!(fs::create_dir_all(dir))
1961 }
1962
1963 fn remove_dir(&self, dir: &Path) {
1964 if self.config.dry_run() {
1965 return;
1966 }
1967
1968 #[cfg(feature = "tracing")]
1969 let _span = trace_io!("dir-remove", ?dir);
1970
1971 t!(fs::remove_dir_all(dir))
1972 }
1973
1974 fn clear_dir(&self, dir: &Path) {
1977 if self.config.dry_run() {
1978 return;
1979 }
1980
1981 #[cfg(feature = "tracing")]
1982 let _span = trace_io!("dir-clear", ?dir);
1983
1984 let _ = std::fs::remove_dir_all(dir);
1985 self.create_dir(dir);
1986 }
1987
1988 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1989 let iter = match fs::read_dir(dir) {
1990 Ok(v) => v,
1991 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1992 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1993 };
1994 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1995 }
1996
1997 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1998 #[cfg(unix)]
1999 use std::os::unix::fs::symlink as symlink_file;
2000 #[cfg(windows)]
2001 use std::os::windows::fs::symlink_file;
2002 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
2003 }
2004
2005 fn ninja(&self) -> bool {
2008 let mut cmd_finder = crate::core::sanity::Finder::new();
2009
2010 if self.config.ninja_in_file {
2011 if cmd_finder.maybe_have("ninja-build").is_none()
2014 && cmd_finder.maybe_have("ninja").is_none()
2015 {
2016 eprintln!(
2017 "
2018Couldn't find required command: ninja (or ninja-build)
2019
2020You should install ninja as described at
2021<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
2022or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
2023Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
2024to download LLVM rather than building it.
2025"
2026 );
2027 exit!(1);
2028 }
2029 }
2030
2031 if !self.config.ninja_in_file
2039 && self.config.host_target.is_msvc()
2040 && cmd_finder.maybe_have("ninja").is_some()
2041 {
2042 return true;
2043 }
2044
2045 self.config.ninja_in_file
2046 }
2047
2048 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2049 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
2050 }
2051
2052 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2053 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
2054 }
2055
2056 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2057 where
2058 C: Fn(ColorChoice) -> StandardStream,
2059 F: FnOnce(&mut dyn WriteColor) -> R,
2060 {
2061 let choice = match self.config.color {
2062 flags::Color::Always => ColorChoice::Always,
2063 flags::Color::Never => ColorChoice::Never,
2064 flags::Color::Auto if !is_tty => ColorChoice::Never,
2065 flags::Color::Auto => ColorChoice::Auto,
2066 };
2067 let mut stream = constructor(choice);
2068 let result = f(&mut stream);
2069 stream.reset().unwrap();
2070 result
2071 }
2072
2073 pub fn exec_ctx(&self) -> &ExecutionContext {
2074 &self.config.exec_ctx
2075 }
2076
2077 pub fn report_summary(&self, path: &Path, start_time: Instant) {
2078 self.config.exec_ctx.profiler().report_summary(path, start_time);
2079 }
2080
2081 #[cfg(feature = "tracing")]
2082 pub fn report_step_graph(self, directory: &Path) {
2083 self.step_graph.into_inner().store_to_dot_files(directory);
2084 }
2085}
2086
2087impl AsRef<ExecutionContext> for Build {
2088 fn as_ref(&self) -> &ExecutionContext {
2089 &self.config.exec_ctx
2090 }
2091}
2092
2093#[cfg(unix)]
2094fn chmod(path: &Path, perms: u32) {
2095 use std::os::unix::fs::*;
2096 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2097}
2098#[cfg(windows)]
2099fn chmod(_path: &Path, _perms: u32) {}
2100
2101impl Compiler {
2102 pub fn new(stage: u32, host: TargetSelection) -> Self {
2103 Self { stage, host, forced_compiler: false }
2104 }
2105
2106 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2107 self.forced_compiler = forced_compiler;
2108 }
2109
2110 pub fn is_snapshot(&self, build: &Build) -> bool {
2112 self.stage == 0 && self.host == build.host_target
2113 }
2114
2115 pub fn is_forced_compiler(&self) -> bool {
2117 self.forced_compiler
2118 }
2119}
2120
2121fn envify(s: &str) -> String {
2122 s.chars()
2125 .map(|c| match c {
2126 '-' | '.' => '_',
2127 c => c,
2128 })
2129 .flat_map(|c| c.to_uppercase())
2130 .collect()
2131}
2132
2133pub fn prepare_behaviour_dump_dir(build: &Build) {
2135 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2136
2137 let dump_path = build.out.join("bootstrap-shims-dump");
2138
2139 let initialized = INITIALIZED.get().unwrap_or(&false);
2140 if !initialized {
2141 if dump_path.exists() {
2143 t!(fs::remove_dir_all(&dump_path));
2144 }
2145
2146 t!(fs::create_dir_all(&dump_path));
2147
2148 t!(INITIALIZED.set(true));
2149 }
2150}
2151
2152#[macro_export]
2153macro_rules! exit {
2154 ($code:expr) => {
2155 $crate::utils::helpers::detail_exit($code, cfg!(test));
2156 };
2157}