1#![allow(clippy::assertions_on_constants, reason = "false positive for `assert!(cfg!(..))`")]
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 let Some(allocator) = self.config.override_allocator(target)
870 && check(allocator.feature_name())
871 {
872 features.push(allocator.feature_name());
873 }
874 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
875 features.push("llvm");
876 }
877 if self.config.llvm_enzyme {
878 features.push("llvm_enzyme");
879 }
880 if self.config.llvm_offload {
881 features.push("llvm_offload");
882 }
883 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
885 features.push("rustc_randomized_layouts");
886 }
887 if self.config.compile_time_deps && kind == Kind::Check {
888 features.push("check_only");
889 }
890
891 if crates.iter().any(|c| c == "rustc_transmute") {
892 features.push("rustc");
895 }
896
897 if !self.config.rust_debug_logging && check("max_level_info") {
903 features.push("max_level_info");
904 }
905
906 features.join(" ")
907 }
908
909 fn cargo_dir(&self, mode: Mode) -> &'static str {
912 match (mode, self.config.rust_optimize.is_release()) {
913 (Mode::Std, _) => "dist",
914 (_, true) => "release",
915 (_, false) => "debug",
916 }
917 }
918
919 fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
920 let out = self
921 .out
922 .join(build_compiler.host)
923 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
924 t!(fs::create_dir_all(&out));
925 out
926 }
927
928 fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
933 use std::fmt::Write;
934
935 fn bootstrap_tool() -> (Option<u32>, &'static str) {
936 (None, "bootstrap-tools")
937 }
938 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
939 (Some(build_compiler.stage + 1), "tools")
940 }
941
942 let (stage, suffix) = match mode {
943 Mode::Std => (Some(build_compiler.stage), "std"),
945 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
947 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
948 Mode::ToolBootstrap => bootstrap_tool(),
949 Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
950 Mode::ToolTarget => {
951 if build_compiler.stage == 0 {
954 bootstrap_tool()
955 } else {
956 staged_tool(build_compiler)
957 }
958 }
959 };
960 let path = self.out.join(build_compiler.host);
961 let mut dir_name = String::new();
962 if let Some(stage) = stage {
963 write!(dir_name, "stage{stage}-").unwrap();
964 }
965 dir_name.push_str(suffix);
966 path.join(dir_name)
967 }
968
969 fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
973 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
974 }
975
976 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
981 if self.config.llvm_from_ci && self.config.is_host_target(target) {
982 self.config.ci_llvm_root()
983 } else {
984 self.out.join(target).join("llvm")
985 }
986 }
987
988 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
989 self.out.join(&*target.triple).join("enzyme")
990 }
991
992 fn offload_out(&self, target: TargetSelection) -> PathBuf {
993 self.out.join(&*target.triple).join("offload")
994 }
995
996 fn lld_out(&self, target: TargetSelection) -> PathBuf {
997 self.out.join(target).join("lld")
998 }
999
1000 fn doc_out(&self, target: TargetSelection) -> PathBuf {
1002 self.out.join(target).join("doc")
1003 }
1004
1005 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
1007 self.out.join(target).join("json-doc")
1008 }
1009
1010 fn test_out(&self, target: TargetSelection) -> PathBuf {
1011 self.out.join(target).join("test")
1012 }
1013
1014 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
1016 self.out.join(target).join("compiler-doc")
1017 }
1018
1019 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
1021 self.out.join(target).join("md-doc")
1022 }
1023
1024 fn vendored_crates_path(&self) -> Option<PathBuf> {
1026 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1027 }
1028
1029 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
1031 let target_config = self.config.target_config.get(&target);
1032 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
1033 s.to_path_buf()
1034 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
1035 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
1036 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
1037 if filecheck.exists() {
1038 filecheck
1039 } else {
1040 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
1043 let lib_filecheck =
1044 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
1045 if lib_filecheck.exists() {
1046 lib_filecheck
1047 } else {
1048 filecheck
1052 }
1053 }
1054 } else {
1055 let base = self.llvm_out(target).join("build");
1056 let base = if !self.ninja() && target.is_msvc() {
1057 if self.config.llvm_optimize {
1058 if self.config.llvm_release_debuginfo {
1059 base.join("RelWithDebInfo")
1060 } else {
1061 base.join("Release")
1062 }
1063 } else {
1064 base.join("Debug")
1065 }
1066 } else {
1067 base
1068 };
1069 base.join("bin").join(exe("FileCheck", target))
1070 }
1071 }
1072
1073 fn native_dir(&self, target: TargetSelection) -> PathBuf {
1075 self.out.join(target).join("native")
1076 }
1077
1078 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1081 self.native_dir(target).join("rust-test-helpers")
1082 }
1083
1084 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1086 if env::var_os("RUST_TEST_THREADS").is_none() {
1087 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1088 }
1089 }
1090
1091 fn rustc_snapshot_libdir(&self) -> PathBuf {
1093 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1094 }
1095
1096 fn rustc_snapshot_sysroot(&self) -> &Path {
1098 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1099 SYSROOT_CACHE.get_or_init(|| {
1100 command(&self.initial_rustc)
1101 .run_in_dry_run()
1102 .args(["--print", "sysroot"])
1103 .run_capture_stdout(self)
1104 .stdout()
1105 .trim()
1106 .to_owned()
1107 .into()
1108 })
1109 }
1110
1111 fn info(&self, msg: &str) {
1112 match self.config.get_dry_run() {
1113 DryRun::SelfCheck => (),
1114 DryRun::Disabled | DryRun::UserSelected => {
1115 println!("{msg}");
1116 }
1117 }
1118 }
1119
1120 #[must_use = "Groups should not be dropped until the Step finishes running"]
1132 #[track_caller]
1133 fn msg(
1134 &self,
1135 action: impl Into<Kind>,
1136 what: impl Display,
1137 mode: impl Into<Option<Mode>>,
1138 target_and_stage: impl Into<TargetAndStage>,
1139 target: impl Into<Option<TargetSelection>>,
1140 ) -> Option<gha::Group> {
1141 let target_and_stage = target_and_stage.into();
1142 let action = action.into();
1143 assert!(
1144 action != Kind::Test,
1145 "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1146 );
1147
1148 let actual_stage = match mode.into() {
1149 Some(Mode::Std) => target_and_stage.stage,
1151 Some(
1153 Mode::Rustc
1154 | Mode::Codegen
1155 | Mode::ToolBootstrap
1156 | Mode::ToolTarget
1157 | Mode::ToolStd
1158 | Mode::ToolRustcPrivate,
1159 )
1160 | None => target_and_stage.stage + 1,
1161 };
1162
1163 let action = action.description();
1164 let what = what.to_string();
1165 let msg = |fmt| {
1166 let space = if !what.is_empty() { " " } else { "" };
1167 format!("{action} stage{actual_stage} {what}{space}{fmt}")
1168 };
1169 let msg = if let Some(target) = target.into() {
1170 let build_stage = target_and_stage.stage;
1171 let host = target_and_stage.target;
1172 if host == target {
1173 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1174 } else {
1175 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1176 }
1177 } else {
1178 msg(format_args!(""))
1179 };
1180 self.group(&msg)
1181 }
1182
1183 #[must_use = "Groups should not be dropped until the Step finishes running"]
1189 #[track_caller]
1190 fn msg_test(
1191 &self,
1192 what: impl Display,
1193 target: TargetSelection,
1194 stage: u32,
1195 ) -> Option<gha::Group> {
1196 let action = Kind::Test.description();
1197 let msg = format!("{action} stage{stage} {what} ({target})");
1198 self.group(&msg)
1199 }
1200
1201 #[must_use = "Groups should not be dropped until the Step finishes running"]
1205 #[track_caller]
1206 fn msg_unstaged(
1207 &self,
1208 action: impl Into<Kind>,
1209 what: impl Display,
1210 target: TargetSelection,
1211 ) -> Option<gha::Group> {
1212 let action = action.into().description();
1213 let msg = format!("{action} {what} for {target}");
1214 self.group(&msg)
1215 }
1216
1217 #[track_caller]
1218 fn group(&self, msg: &str) -> Option<gha::Group> {
1219 match self.config.get_dry_run() {
1220 DryRun::SelfCheck => None,
1221 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1222 }
1223 }
1224
1225 fn jobs(&self) -> u32 {
1228 self.config.jobs.unwrap_or_else(|| {
1229 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1230 })
1231 }
1232
1233 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1234 if !self.config.rust_remap_debuginfo {
1235 return None;
1236 }
1237
1238 match which {
1239 GitRepo::Rustc => {
1240 let sha = self.rust_sha().unwrap_or(&self.version);
1241
1242 match remap_scheme {
1243 RemapScheme::Compiler => {
1244 Some(format!("/rustc-dev/{sha}"))
1253 }
1254 RemapScheme::NonCompiler => {
1255 Some(format!("/rustc/{sha}"))
1257 }
1258 }
1259 }
1260 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1261 }
1262 }
1263
1264 fn cc(&self, target: TargetSelection) -> PathBuf {
1266 if self.config.dry_run() {
1267 return PathBuf::new();
1268 }
1269 self.cc[&target].path().into()
1270 }
1271
1272 fn cc_tool(&self, target: TargetSelection) -> Tool {
1274 self.cc[&target].clone()
1275 }
1276
1277 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1279 self.cxx[&target].clone()
1280 }
1281
1282 fn cc_handled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1285 if self.config.dry_run() {
1286 return Vec::new();
1287 }
1288 let base = match c {
1289 CLang::C => self.cc[&target].clone(),
1290 CLang::Cxx => self.cxx[&target].clone(),
1291 };
1292
1293 base.args()
1296 .iter()
1297 .map(|s| s.to_string_lossy().into_owned())
1298 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1299 .collect::<Vec<String>>()
1300 }
1301
1302 fn cc_unhandled_cflags(
1304 &self,
1305 target: TargetSelection,
1306 which: GitRepo,
1307 c: CLang,
1308 ) -> Vec<String> {
1309 let mut base = Vec::new();
1310
1311 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1315 base.push("-stdlib=libc++".into());
1316 }
1317
1318 if &*target.triple == "i686-pc-windows-gnu" {
1322 base.push("-fno-omit-frame-pointer".into());
1323 }
1324
1325 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1326 let map = format!("{}={}", self.src.display(), map_to);
1327 let cc = self.cc(target);
1328 if cc.ends_with("clang") || cc.ends_with("gcc") {
1329 base.push(format!("-fdebug-prefix-map={map}"));
1330 } else if cc.ends_with("clang-cl.exe") {
1331 base.push("-Xclang".into());
1332 base.push(format!("-fdebug-prefix-map={map}"));
1333 }
1334 }
1335 base
1336 }
1337
1338 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1340 if self.config.dry_run() {
1341 return None;
1342 }
1343 self.ar.get(&target).cloned()
1344 }
1345
1346 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1348 if self.config.dry_run() {
1349 return None;
1350 }
1351 self.ranlib.get(&target).cloned()
1352 }
1353
1354 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1356 if self.config.dry_run() {
1357 return Ok(PathBuf::new());
1358 }
1359 match self.cxx.get(&target) {
1360 Some(p) => Ok(p.path().into()),
1361 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1362 }
1363 }
1364
1365 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1367 if self.config.dry_run() {
1368 return Some(PathBuf::new());
1369 }
1370 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1371 {
1372 Some(linker)
1373 } else if target.contains("vxworks") {
1374 Some(self.cxx[&target].path().into())
1377 } else if !self.config.is_host_target(target)
1378 && helpers::use_host_linker(target)
1379 && !target.is_msvc()
1380 {
1381 Some(self.cc(target))
1382 } else if self.config.bootstrap_override_lld.is_used()
1383 && self.is_lld_direct_linker(target)
1384 && self.host_target == target
1385 {
1386 match self.config.bootstrap_override_lld {
1387 BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1388 BootstrapOverrideLld::External => Some("lld".into()),
1389 BootstrapOverrideLld::None => None,
1390 }
1391 } else {
1392 None
1393 }
1394 }
1395
1396 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1399 target.is_msvc()
1400 }
1401
1402 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1404 if target.contains("pc-windows-msvc") {
1405 Some(true)
1406 } else {
1407 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1408 }
1409 }
1410
1411 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1416 let configured_root = self
1417 .config
1418 .target_config
1419 .get(&target)
1420 .and_then(|t| t.musl_root.as_ref())
1421 .or(self.config.musl_root.as_ref())
1422 .map(|p| &**p);
1423
1424 if self.config.is_host_target(target) && configured_root.is_none() {
1425 Some(Path::new("/usr"))
1426 } else {
1427 configured_root
1428 }
1429 }
1430
1431 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1433 self.config
1434 .target_config
1435 .get(&target)
1436 .and_then(|t| t.musl_libdir.clone())
1437 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1438 }
1439
1440 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1447 let configured =
1448 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1449 if let Some(path) = configured {
1450 return Some(path.join("lib").join(target.to_string()));
1451 }
1452 let mut env_root = self.wasi_sdk_path.clone()?;
1453 env_root.push("share");
1454 env_root.push("wasi-sysroot");
1455 env_root.push("lib");
1456 env_root.push(target.to_string());
1457 Some(env_root)
1458 }
1459
1460 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1462 self.config.target_config.get(&target).map(|t| t.no_std)
1463 }
1464
1465 fn remote_tested(&self, target: TargetSelection) -> bool {
1468 self.qemu_rootfs(target).is_some()
1469 || target.contains("android")
1470 || env::var_os("TEST_DEVICE_ADDR").is_some()
1471 }
1472
1473 fn runner(&self, target: TargetSelection) -> Option<String> {
1479 let configured_runner =
1480 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1481 if let Some(runner) = configured_runner {
1482 return Some(runner.to_owned());
1483 }
1484
1485 if target.starts_with("wasm") && target.contains("wasi") {
1486 self.default_wasi_runner(target)
1487 } else {
1488 None
1489 }
1490 }
1491
1492 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1496 let mut finder = crate::core::sanity::Finder::new();
1497
1498 if let Some(path) = finder.maybe_have("wasmtime")
1502 && let Ok(mut path) = path.into_os_string().into_string()
1503 {
1504 path.push_str(" run -Wexceptions -C cache=n --dir .");
1505 path.push_str(" --env RUSTC_BOOTSTRAP");
1512
1513 if target.contains("wasip2") {
1514 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1515 }
1516
1517 return Some(path);
1518 }
1519
1520 None
1521 }
1522
1523 fn tool_enabled(&self, tool: &str) -> bool {
1528 if !self.config.extended {
1529 return false;
1530 }
1531 match &self.config.tools {
1532 Some(set) => set.contains(tool),
1533 None => true,
1534 }
1535 }
1536
1537 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1543 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1544 }
1545
1546 fn extended_error_dir(&self) -> PathBuf {
1548 self.out.join("tmp/extended-error-metadata")
1549 }
1550
1551 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1570 !self.config.full_bootstrap
1571 && !self.config.download_rustc()
1572 && stage >= 2
1573 && (self.hosts.contains(&target) || target == self.host_target)
1574 }
1575
1576 fn force_use_stage2(&self, stage: u32) -> bool {
1582 self.config.download_rustc() && stage >= 2
1583 }
1584
1585 fn release(&self, num: &str) -> String {
1591 match &self.config.channel[..] {
1592 "stable" => num.to_string(),
1593 "beta" => {
1594 if !self.config.omit_git_hash {
1595 format!("{}-beta.{}", num, self.beta_prerelease_version())
1596 } else {
1597 format!("{num}-beta")
1598 }
1599 }
1600 "nightly" => format!("{num}-nightly"),
1601 _ => format!("{num}-dev"),
1602 }
1603 }
1604
1605 fn beta_prerelease_version(&self) -> u32 {
1606 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1607 let version = fs::read_to_string(version_file).ok()?;
1608
1609 helpers::extract_beta_rev(&version)
1610 }
1611
1612 if let Some(s) = self.prerelease_version.get() {
1613 return s;
1614 }
1615
1616 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1620 helpers::git(Some(&self.src))
1624 .arg("rev-list")
1625 .arg("--count")
1626 .arg("--merges")
1627 .arg(format!(
1628 "refs/remotes/origin/{}..HEAD",
1629 self.config.stage0_metadata.config.nightly_branch
1630 ))
1631 .run_in_dry_run()
1632 .run_capture(self)
1633 .stdout()
1634 });
1635 let n = count.trim().parse().unwrap();
1636 self.prerelease_version.set(Some(n));
1637 n
1638 }
1639
1640 fn rust_release(&self) -> String {
1642 self.release(&self.version)
1643 }
1644
1645 fn rust_package_vers(&self) -> String {
1651 match &self.config.channel[..] {
1652 "stable" => self.version.to_string(),
1653 "beta" => "beta".to_string(),
1654 "nightly" => "nightly".to_string(),
1655 _ => format!("{}-dev", self.version),
1656 }
1657 }
1658
1659 fn rust_version(&self) -> String {
1665 let mut version = self.rust_info().version(self, &self.version);
1666 if let Some(ref s) = self.config.description
1667 && !s.is_empty()
1668 {
1669 version.push_str(" (");
1670 version.push_str(s);
1671 version.push(')');
1672 }
1673 version
1674 }
1675
1676 fn rust_sha(&self) -> Option<&str> {
1678 self.rust_info().sha()
1679 }
1680
1681 fn release_num(&self, package: &str) -> String {
1683 if self.config.dry_run() {
1684 return "0.0.0 (dry-run)".into();
1685 }
1686 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1687 let toml = t!(fs::read_to_string(toml_file_name));
1688 for line in toml.lines() {
1689 if let Some(stripped) =
1690 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1691 {
1692 return stripped.to_owned();
1693 }
1694 }
1695
1696 panic!("failed to find version in {package}'s Cargo.toml")
1697 }
1698
1699 fn unstable_features(&self) -> bool {
1702 !matches!(&self.config.channel[..], "stable" | "beta")
1703 }
1704
1705 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1709 let mut ret = Vec::new();
1710 let mut list = vec![root.to_owned()];
1711 let mut visited = HashSet::new();
1712 while let Some(krate) = list.pop() {
1713 let krate = self
1714 .crates
1715 .get(&krate)
1716 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1717 ret.push(krate);
1718 for dep in &krate.deps {
1719 if !self.crates.contains_key(dep) {
1720 continue;
1722 }
1723 if visited.insert(dep)
1729 && (dep != "profiler_builtins"
1730 || target
1731 .map(|t| self.config.profiler_enabled(t))
1732 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1733 && (dep != "rustc_codegen_llvm"
1734 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1735 {
1736 list.push(dep.clone());
1737 }
1738 }
1739 }
1740
1741 ret.sort_unstable_by(|a, b| Ord::cmp(&a.name, &b.name));
1743 ret
1744 }
1745
1746 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1747 if self.config.dry_run() {
1748 return Vec::new();
1749 }
1750
1751 if !stamp.path().exists() {
1752 eprintln!(
1753 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1754 stamp.path().display()
1755 );
1756 crate::exit!(1);
1757 }
1758
1759 let mut paths = Vec::new();
1760 let contents = t!(fs::read(stamp.path()), stamp.path());
1761 for part in contents.split(|b| *b == 0) {
1764 if part.is_empty() {
1765 continue;
1766 }
1767 let dependency_type = match part[0] as char {
1768 'h' => DependencyType::Host,
1769 's' => DependencyType::TargetSelfContained,
1770 't' => DependencyType::Target,
1771 _ => unreachable!(),
1772 };
1773 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1774 paths.push((path, dependency_type));
1775 }
1776 paths
1777 }
1778
1779 #[track_caller]
1784 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1785 self.copy_link_internal(src, dst, true);
1786 }
1787
1788 #[track_caller]
1793 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1794 self.copy_link_internal(src, dst, false);
1795
1796 if file_type.could_have_split_debuginfo()
1797 && let Some(dbg_file) = split_debuginfo(src)
1798 {
1799 self.copy_link_internal(
1800 &dbg_file,
1801 &dst.with_extension(dbg_file.extension().unwrap()),
1802 false,
1803 );
1804 }
1805 }
1806
1807 #[track_caller]
1808 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1809 if self.config.dry_run() {
1810 return;
1811 }
1812 if src == dst {
1813 return;
1814 }
1815
1816 #[cfg(feature = "tracing")]
1817 let _span = trace_io!("file-copy-link", ?src, ?dst);
1818
1819 if let Err(e) = fs::remove_file(dst)
1820 && cfg!(windows)
1821 && e.kind() != io::ErrorKind::NotFound
1822 {
1823 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1826 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1827 }
1828 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1829 let mut src = src.to_path_buf();
1830 if metadata.file_type().is_symlink() {
1831 if dereference_symlinks {
1832 src = t!(fs::canonicalize(src));
1833 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1834 } else {
1835 let link = t!(fs::read_link(src));
1836 t!(self.symlink_file(link, dst));
1837 return;
1838 }
1839 }
1840 if let Ok(()) = fs::hard_link(&src, dst) {
1841 } else {
1844 if let Err(e) = fs::copy(&src, dst) {
1845 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1846 }
1847 t!(fs::set_permissions(dst, metadata.permissions()));
1848
1849 let file_times = fs::FileTimes::new()
1852 .set_accessed(t!(metadata.accessed()))
1853 .set_modified(t!(metadata.modified()));
1854 t!(set_file_times(dst, file_times));
1855 }
1856 }
1857
1858 #[track_caller]
1862 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1863 if self.config.dry_run() {
1864 return;
1865 }
1866 for f in self.read_dir(src) {
1867 let path = f.path();
1868 let name = path.file_name().unwrap();
1869 let dst = dst.join(name);
1870 if t!(f.file_type()).is_dir() {
1871 t!(fs::create_dir_all(&dst));
1872 self.cp_link_r(&path, &dst);
1873 } else {
1874 self.copy_link(&path, &dst, FileType::Regular);
1875 }
1876 }
1877 }
1878
1879 #[track_caller]
1885 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1886 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1888 }
1889
1890 #[track_caller]
1892 fn cp_link_filtered_recurse(
1893 &self,
1894 src: &Path,
1895 dst: &Path,
1896 relative: &Path,
1897 filter: &dyn Fn(&Path) -> bool,
1898 ) {
1899 for f in self.read_dir(src) {
1900 let path = f.path();
1901 let name = path.file_name().unwrap();
1902 let dst = dst.join(name);
1903 let relative = relative.join(name);
1904 if filter(&relative) {
1906 if t!(f.file_type()).is_dir() {
1907 let _ = fs::remove_dir_all(&dst);
1908 self.create_dir(&dst);
1909 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1910 } else {
1911 self.copy_link(&path, &dst, FileType::Regular);
1912 }
1913 }
1914 }
1915 }
1916
1917 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1918 let file_name = src.file_name().unwrap();
1919 let dest = dest_folder.join(file_name);
1920 self.copy_link(src, &dest, FileType::Regular);
1921 }
1922
1923 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1924 if self.config.dry_run() {
1925 return;
1926 }
1927 let dst = dstdir.join(src.file_name().unwrap());
1928
1929 #[cfg(feature = "tracing")]
1930 let _span = trace_io!("install", ?src, ?dst);
1931
1932 t!(fs::create_dir_all(dstdir));
1933 if !src.exists() {
1934 panic!("ERROR: File \"{}\" not found!", src.display());
1935 }
1936
1937 self.copy_link_internal(src, &dst, true);
1938 chmod(&dst, file_type.perms());
1939
1940 if file_type.could_have_split_debuginfo()
1942 && let Some(dbg_file) = split_debuginfo(src)
1943 {
1944 self.install(&dbg_file, dstdir, FileType::Regular);
1945 }
1946 }
1947
1948 fn read(&self, path: &Path) -> String {
1949 if self.config.dry_run() {
1950 return String::new();
1951 }
1952 t!(fs::read_to_string(path))
1953 }
1954
1955 #[track_caller]
1956 fn create_dir(&self, dir: &Path) {
1957 if self.config.dry_run() {
1958 return;
1959 }
1960
1961 #[cfg(feature = "tracing")]
1962 let _span = trace_io!("dir-create", ?dir);
1963
1964 t!(fs::create_dir_all(dir))
1965 }
1966
1967 fn remove_dir(&self, dir: &Path) {
1968 if self.config.dry_run() {
1969 return;
1970 }
1971
1972 #[cfg(feature = "tracing")]
1973 let _span = trace_io!("dir-remove", ?dir);
1974
1975 t!(fs::remove_dir_all(dir))
1976 }
1977
1978 fn clear_dir(&self, dir: &Path) {
1981 if self.config.dry_run() {
1982 return;
1983 }
1984
1985 #[cfg(feature = "tracing")]
1986 let _span = trace_io!("dir-clear", ?dir);
1987
1988 let _ = std::fs::remove_dir_all(dir);
1989 self.create_dir(dir);
1990 }
1991
1992 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1993 let iter = match fs::read_dir(dir) {
1994 Ok(v) => v,
1995 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1996 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1997 };
1998 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1999 }
2000
2001 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
2002 #[cfg(unix)]
2003 use std::os::unix::fs::symlink as symlink_file;
2004 #[cfg(windows)]
2005 use std::os::windows::fs::symlink_file;
2006 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
2007 }
2008
2009 fn ninja(&self) -> bool {
2012 let mut cmd_finder = crate::core::sanity::Finder::new();
2013
2014 if self.config.ninja_in_file {
2015 if cmd_finder.maybe_have("ninja-build").is_none()
2018 && cmd_finder.maybe_have("ninja").is_none()
2019 {
2020 eprintln!(
2021 "
2022Couldn't find required command: ninja (or ninja-build)
2023
2024You should install ninja as described at
2025<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
2026or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
2027Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
2028to download LLVM rather than building it.
2029"
2030 );
2031 exit!(1);
2032 }
2033 }
2034
2035 if !self.config.ninja_in_file
2043 && self.config.host_target.is_msvc()
2044 && cmd_finder.maybe_have("ninja").is_some()
2045 {
2046 return true;
2047 }
2048
2049 self.config.ninja_in_file
2050 }
2051
2052 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2053 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
2054 }
2055
2056 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2057 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
2058 }
2059
2060 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2061 where
2062 C: Fn(ColorChoice) -> StandardStream,
2063 F: FnOnce(&mut dyn WriteColor) -> R,
2064 {
2065 let choice = match self.config.color {
2066 flags::Color::Always => ColorChoice::Always,
2067 flags::Color::Never => ColorChoice::Never,
2068 flags::Color::Auto if !is_tty => ColorChoice::Never,
2069 flags::Color::Auto => ColorChoice::Auto,
2070 };
2071 let mut stream = constructor(choice);
2072 let result = f(&mut stream);
2073 stream.reset().unwrap();
2074 result
2075 }
2076
2077 pub fn exec_ctx(&self) -> &ExecutionContext {
2078 &self.config.exec_ctx
2079 }
2080
2081 pub fn report_summary(&self, path: &Path, start_time: Instant) {
2082 self.config.exec_ctx.profiler().report_summary(path, start_time);
2083 }
2084
2085 #[cfg(feature = "tracing")]
2086 pub fn report_step_graph(self, directory: &Path) {
2087 self.step_graph.into_inner().store_to_dot_files(directory);
2088 }
2089}
2090
2091impl AsRef<ExecutionContext> for Build {
2092 fn as_ref(&self) -> &ExecutionContext {
2093 &self.config.exec_ctx
2094 }
2095}
2096
2097#[cfg(unix)]
2098fn chmod(path: &Path, perms: u32) {
2099 use std::os::unix::fs::*;
2100 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2101}
2102#[cfg(windows)]
2103fn chmod(_path: &Path, _perms: u32) {}
2104
2105impl Compiler {
2106 pub fn new(stage: u32, host: TargetSelection) -> Self {
2107 Self { stage, host, forced_compiler: false }
2108 }
2109
2110 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2111 self.forced_compiler = forced_compiler;
2112 }
2113
2114 pub fn is_snapshot(&self, build: &Build) -> bool {
2116 self.stage == 0 && self.host == build.host_target
2117 }
2118
2119 pub fn is_forced_compiler(&self) -> bool {
2121 self.forced_compiler
2122 }
2123}
2124
2125fn envify(s: &str) -> String {
2126 s.chars()
2129 .map(|c| match c {
2130 '-' | '.' => '_',
2131 c => c,
2132 })
2133 .flat_map(|c| c.to_uppercase())
2134 .collect()
2135}
2136
2137pub fn prepare_behaviour_dump_dir(build: &Build) {
2139 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2140
2141 let dump_path = build.out.join("bootstrap-shims-dump");
2142
2143 let initialized = INITIALIZED.get().unwrap_or(&false);
2144 if !initialized {
2145 if dump_path.exists() {
2147 t!(fs::remove_dir_all(&dump_path));
2148 }
2149
2150 t!(fs::create_dir_all(&dump_path));
2151
2152 t!(INITIALIZED.set(true));
2153 }
2154}
2155
2156#[macro_export]
2157macro_rules! exit {
2158 ($code:expr) => {
2159 $crate::utils::helpers::detail_exit($code, cfg!(test));
2160 };
2161}