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};
31#[cfg(feature = "tracing")]
32use tracing::{instrument, span};
33
34use crate::core::build_steps::format::InternalRustfmt;
35use crate::core::build_steps::vendor::VENDOR_DIR;
36#[cfg(feature = "tracing")]
37use crate::core::builder::STEP_SPAN_TARGET;
38use crate::core::builder::{self, Kind, StepStack};
39use crate::core::config::flags::{Flags, Subcommand};
40use crate::core::config::{
41 BootstrapOverrideLld, ChangeId, Config, DryRun, LlvmLibunwind, TargetSelection, flags,
42};
43use crate::utils::build_stamp::BuildStamp;
44use crate::utils::change_tracker::{
45 CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
46};
47use crate::utils::channel::GitInfo;
48use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
49use crate::utils::helpers::{
50 self, PanicTracker, dir_is_empty, exe, libdir, set_file_times, split_debuginfo, symlink_dir,
51};
52
53pub mod cli_main;
54mod core;
55mod utils;
56
57const LLVM_TOOLS: &[&str] = &[
58 "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", ];
73
74const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
76
77#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
81 (Some(Mode::Rustc), "bootstrap", None),
82 (Some(Mode::Codegen), "bootstrap", None),
83 (Some(Mode::ToolRustcPrivate), "bootstrap", None),
84 (Some(Mode::ToolStd), "bootstrap", None),
85 (Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
86 (Some(Mode::ToolStd), "rust_analyzer", None),
87 ];
91
92#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
98pub struct Compiler {
99 stage: u32,
100 host: TargetSelection,
101 forced_compiler: bool,
105}
106
107impl std::hash::Hash for Compiler {
108 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
109 self.stage.hash(state);
110 self.host.hash(state);
111 }
112}
113
114impl PartialEq for Compiler {
115 fn eq(&self, other: &Self) -> bool {
116 self.stage == other.stage && self.host == other.host
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
122pub enum CodegenBackendKind {
123 #[default]
124 Llvm,
125 Cranelift,
126 Gcc,
127 Custom(String),
128}
129
130impl CodegenBackendKind {
131 pub fn name(&self) -> &str {
134 match self {
135 CodegenBackendKind::Llvm => "llvm",
136 CodegenBackendKind::Cranelift => "cranelift",
137 CodegenBackendKind::Gcc => "gcc",
138 CodegenBackendKind::Custom(name) => name,
139 }
140 }
141
142 pub fn crate_name(&self) -> String {
144 format!("rustc_codegen_{}", self.name())
145 }
146
147 pub fn is_llvm(&self) -> bool {
148 matches!(self, Self::Llvm)
149 }
150
151 pub fn is_cranelift(&self) -> bool {
152 matches!(self, Self::Cranelift)
153 }
154
155 pub fn is_gcc(&self) -> bool {
156 matches!(self, Self::Gcc)
157 }
158}
159
160impl std::str::FromStr for CodegenBackendKind {
161 type Err = &'static str;
162
163 fn from_str(s: &str) -> Result<Self, Self::Err> {
164 match s.to_lowercase().as_str() {
165 "" => Err("Invalid empty backend name"),
166 "gcc" => Ok(Self::Gcc),
167 "llvm" => Ok(Self::Llvm),
168 "cranelift" => Ok(Self::Cranelift),
169 _ => Ok(Self::Custom(s.to_string())),
170 }
171 }
172}
173
174#[derive(PartialEq, Eq, Copy, Clone, Debug)]
175pub enum TestTarget {
176 Default,
178 AllTargets,
180 DocOnly,
182 Tests,
184}
185
186impl TestTarget {
187 fn runs_doctests(&self) -> bool {
188 matches!(self, TestTarget::DocOnly | TestTarget::Default)
189 }
190}
191
192pub enum GitRepo {
193 Rustc,
194 Llvm,
195}
196
197pub struct Build {
208 config: Config,
210
211 version: String,
213
214 src: PathBuf,
216 out: PathBuf,
217 bootstrap_out: PathBuf,
218 cargo_info: GitInfo,
219 rust_analyzer_info: GitInfo,
220 clippy_info: GitInfo,
221 miri_info: GitInfo,
222 rustfmt_info: GitInfo,
223 enzyme_info: GitInfo,
224 in_tree_llvm_info: GitInfo,
225 in_tree_gcc_info: GitInfo,
226 local_rebuild: bool,
227 fail_fast: bool,
228 test_target: TestTarget,
229 verbosity: usize,
230
231 host_target: TargetSelection,
233 hosts: Vec<TargetSelection>,
235 targets: Vec<TargetSelection>,
237
238 initial_rustc: PathBuf,
239 initial_rustdoc: PathBuf,
240 initial_cargo: PathBuf,
241 initial_lld: PathBuf,
242 initial_relative_libdir: PathBuf,
243 initial_sysroot: PathBuf,
244
245 cc: HashMap<TargetSelection, cc::Tool>,
248 cxx: HashMap<TargetSelection, cc::Tool>,
249 ar: HashMap<TargetSelection, PathBuf>,
250 ranlib: HashMap<TargetSelection, PathBuf>,
251 wasi_sdk_path: Option<PathBuf>,
252
253 crates: HashMap<String, Crate>,
256 crate_paths: HashMap<PathBuf, String>,
257 is_sudo: bool,
258 prerelease_version: Cell<Option<u32>>,
259
260 #[cfg(feature = "build-metrics")]
261 metrics: crate::utils::metrics::BuildMetrics,
262
263 #[cfg(feature = "tracing")]
264 step_graph: std::cell::RefCell<crate::utils::step_graph::StepGraph>,
265}
266
267#[derive(Debug, Clone)]
268struct Crate {
269 name: String,
270 deps: HashSet<String>,
271 path: PathBuf,
272 features: Vec<String>,
273}
274
275impl Crate {
276 fn local_path(&self, build: &Build) -> PathBuf {
277 self.path.strip_prefix(&build.config.src).unwrap().into()
278 }
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
283pub enum DependencyType {
284 Host,
286 Target,
288 TargetSelfContained,
290}
291
292#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
297pub enum Mode {
298 Std,
300
301 Rustc,
303
304 Codegen,
306
307 ToolBootstrap,
319
320 ToolTarget,
331
332 ToolStd,
336
337 ToolRustcPrivate,
343}
344
345impl Mode {
346 pub fn must_support_dlopen(&self) -> bool {
347 match self {
348 Mode::Std | Mode::Codegen => true,
349 Mode::ToolBootstrap
350 | Mode::ToolRustcPrivate
351 | Mode::ToolStd
352 | Mode::ToolTarget
353 | Mode::Rustc => false,
354 }
355 }
356}
357
358pub enum RemapScheme {
362 Compiler,
364 NonCompiler,
366}
367
368#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
369pub enum CLang {
370 C,
371 Cxx,
372}
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375pub enum FileType {
376 Executable,
378 NativeLibrary,
380 Script,
382 Regular,
384}
385
386impl FileType {
387 pub fn perms(self) -> u32 {
389 match self {
390 FileType::Executable | FileType::Script => 0o755,
391 FileType::Regular | FileType::NativeLibrary => 0o644,
392 }
393 }
394
395 pub fn could_have_split_debuginfo(self) -> bool {
396 match self {
397 FileType::Executable | FileType::NativeLibrary => true,
398 FileType::Script | FileType::Regular => false,
399 }
400 }
401}
402
403macro_rules! forward {
404 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
405 impl Build {
406 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
407 self.config.$fn( $($param),* )
408 } )+
409 }
410 }
411}
412
413forward! {
414 do_if_verbose(f: impl Fn()),
415 is_verbose() -> bool,
416 create(path: &Path, s: &str),
417 remove(f: &Path),
418 tempdir() -> PathBuf,
419 llvm_link_shared() -> bool,
420 download_rustc() -> bool,
421}
422
423struct TargetAndStage {
426 target: TargetSelection,
427 stage: u32,
428}
429
430impl From<(TargetSelection, u32)> for TargetAndStage {
431 fn from((target, stage): (TargetSelection, u32)) -> Self {
432 Self { target, stage }
433 }
434}
435
436impl From<Compiler> for TargetAndStage {
437 fn from(compiler: Compiler) -> Self {
438 Self { target: compiler.host, stage: compiler.stage }
439 }
440}
441
442impl Build {
443 pub fn new(mut config: Config) -> Build {
448 let src = config.src.clone();
449 let out = config.out.clone();
450
451 #[cfg(unix)]
452 let is_sudo = match env::var_os("SUDO_USER") {
455 Some(_sudo_user) => {
456 let uid = unsafe { libc::getuid() };
461 uid == 0
462 }
463 None => false,
464 };
465 #[cfg(not(unix))]
466 let is_sudo = false;
467
468 let rust_info = config.rust_info.clone();
469 let cargo_info = config.cargo_info.clone();
470 let rust_analyzer_info = config.rust_analyzer_info.clone();
471 let clippy_info = config.clippy_info.clone();
472 let miri_info = config.miri_info.clone();
473 let rustfmt_info = config.rustfmt_info.clone();
474 let enzyme_info = config.enzyme_info.clone();
475 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
476 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
477
478 let initial_target_libdir = command(&config.initial_rustc)
479 .run_in_dry_run()
480 .args(["--print", "target-libdir"])
481 .run_capture_stdout(&config)
482 .stdout()
483 .trim()
484 .to_owned();
485
486 let initial_target_dir = Path::new(&initial_target_libdir)
487 .parent()
488 .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent"));
489
490 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
491
492 let initial_relative_libdir = if cfg!(test) {
493 PathBuf::default()
495 } else {
496 let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
497 panic!("Not enough ancestors for {}", initial_target_dir.display())
498 });
499
500 ancestor
501 .strip_prefix(&config.initial_sysroot)
502 .unwrap_or_else(|_| {
503 panic!(
504 "Couldn’t resolve the initial relative libdir from {}",
505 initial_target_dir.display()
506 )
507 })
508 .to_path_buf()
509 };
510
511 let version = std::fs::read_to_string(src.join("src").join("version"))
512 .expect("failed to read src/version");
513 let version = version.trim();
514
515 let mut bootstrap_out = std::env::current_exe()
516 .expect("could not determine path to running process")
517 .parent()
518 .unwrap()
519 .to_path_buf();
520 if bootstrap_out.ends_with("deps") {
523 bootstrap_out.pop();
524 }
525 if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
526 panic!(
528 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
529 bootstrap_out.display()
530 )
531 }
532
533 if rust_info.is_from_tarball() && config.description.is_none() {
534 config.description = Some("built from a source tarball".to_owned());
535 }
536
537 let mut build = Build {
538 initial_lld,
539 initial_relative_libdir,
540 initial_rustc: config.initial_rustc.clone(),
541 initial_rustdoc: config.initial_rustdoc.clone(),
542 initial_cargo: config.initial_cargo.clone(),
543 initial_sysroot: config.initial_sysroot.clone(),
544 local_rebuild: config.local_rebuild,
545 fail_fast: config.cmd.fail_fast(),
546 test_target: config.cmd.test_target(),
547 verbosity: config.exec_ctx.verbosity as usize,
548
549 host_target: config.host_target,
550 hosts: config.hosts.clone(),
551 targets: config.targets.clone(),
552
553 config,
554 version: version.to_string(),
555 src,
556 out,
557 bootstrap_out,
558
559 cargo_info,
560 rust_analyzer_info,
561 clippy_info,
562 miri_info,
563 rustfmt_info,
564 enzyme_info,
565 in_tree_llvm_info,
566 in_tree_gcc_info,
567 cc: HashMap::new(),
568 cxx: HashMap::new(),
569 ar: HashMap::new(),
570 ranlib: HashMap::new(),
571 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
572 crates: HashMap::new(),
573 crate_paths: HashMap::new(),
574 is_sudo,
575 prerelease_version: Cell::new(None),
576
577 #[cfg(feature = "build-metrics")]
578 metrics: crate::utils::metrics::BuildMetrics::init(),
579
580 #[cfg(feature = "tracing")]
581 step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()),
582 };
583
584 let local_version_verbose = command(&build.initial_rustc)
587 .run_in_dry_run()
588 .args(["--version", "--verbose"])
589 .run_capture_stdout(&build)
590 .stdout();
591 let local_release = local_version_verbose
592 .lines()
593 .filter_map(|x| x.strip_prefix("release:"))
594 .next()
595 .unwrap()
596 .trim();
597 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
598 build.do_if_verbose(|| println!("auto-detected local-rebuild {local_release}"));
599 build.local_rebuild = true;
600 }
601
602 build.do_if_verbose(|| println!("finding compilers"));
603 utils::cc_detect::fill_compilers(&mut build);
604 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
610 build.do_if_verbose(|| println!("running sanity check"));
611 crate::core::sanity::check(&mut build);
612
613 let rust_submodules = ["library/backtrace"];
616 for s in rust_submodules {
617 build.require_submodule(
618 s,
619 Some(
620 "The submodule is required for the standard library \
621 and the main Cargo workspace.",
622 ),
623 );
624 }
625 build.update_existing_submodules();
627
628 build.do_if_verbose(|| println!("learning about cargo"));
629 crate::core::metadata::build(&mut build);
630 }
631
632 let build_triple = build.out.join(build.host_target);
634 t!(fs::create_dir_all(&build_triple));
635 let host = build.out.join("host");
636 if host.is_symlink() {
637 #[cfg(windows)]
640 t!(fs::remove_dir(&host));
641 #[cfg(not(windows))]
642 t!(fs::remove_file(&host));
643 }
644 t!(
645 symlink_dir(&build.config, &build_triple, &host),
646 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
647 );
648
649 build
650 }
651
652 #[cfg_attr(
661 feature = "tracing",
662 instrument(
663 level = "trace",
664 name = "Build::require_submodule",
665 skip_all,
666 fields(submodule = submodule),
667 ),
668 )]
669 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
670 if self.rust_info().is_from_tarball() {
671 return;
672 }
673
674 if self.config.dry_run() {
675 return;
676 }
677
678 if cfg!(test) && !self.config.submodules() {
681 return;
682 }
683 self.config.update_submodule(submodule);
684 let absolute_path = self.config.src.join(submodule);
685 if !absolute_path.exists() || dir_is_empty(&absolute_path) {
686 let maybe_enable = if !self.config.submodules()
687 && self.config.rust_info.is_managed_git_subrepository()
688 {
689 "\nConsider setting `build.submodules = true` or manually initializing the submodules."
690 } else {
691 ""
692 };
693 let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}"));
694 eprintln!(
695 "submodule {submodule} does not appear to be checked out, \
696 but it is required for this step{maybe_enable}{err_hint}"
697 );
698 exit!(1);
699 }
700 }
701
702 fn update_existing_submodules(&self) {
705 if !self.config.submodules() {
708 return;
709 }
710 let output = helpers::git(Some(&self.src))
711 .args(["config", "--file"])
712 .arg(".gitmodules")
713 .args(["--get-regexp", "path"])
714 .run_capture(self)
715 .stdout();
716 std::thread::scope(|s| {
717 for line in output.lines() {
720 let submodule = line.split_once(' ').unwrap().1;
721 let config = self.config.clone();
722 s.spawn(move || {
723 Self::update_existing_submodule(&config, submodule);
724 });
725 }
726 });
727 }
728
729 pub fn update_existing_submodule(config: &Config, submodule: &str) {
731 if !config.submodules() {
733 return;
734 }
735
736 if config.git_info(false, Path::new(submodule)).is_managed_git_subrepository() {
737 config.update_submodule(submodule);
738 }
739 }
740
741 #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Build::build", skip_all))]
743 pub fn build(&mut self) {
744 trace!("setting up job management");
745 unsafe {
746 crate::utils::job::setup(self);
747 }
748
749 {
751 #[cfg(feature = "tracing")]
752 let _hardcoded_span =
753 span!(tracing::Level::DEBUG, "handling hardcoded subcommands (Format, Perf)")
754 .entered();
755
756 match &self.config.cmd {
757 Subcommand::Format { check, all } => {
758 let builder = builder::Builder::new(self);
759 let rustfmt_path = builder.ensure(InternalRustfmt).unwrap_or_else(|| {
760 eprintln!("fmt error: `x fmt` is not supported on this channel");
761 crate::exit!(1);
762 });
763 return core::build_steps::format::format(
764 &builder,
765 rustfmt_path,
766 *check,
767 *all,
768 &self.config.paths,
769 );
770 }
771 Subcommand::Perf(args) => {
772 return core::build_steps::perf::perf(&builder::Builder::new(self), args);
773 }
774 _cmd => {
775 debug!(cmd = ?_cmd, "not a hardcoded subcommand; returning to normal handling");
776 }
777 }
778
779 debug!("handling subcommand normally");
780 }
781
782 if !self.config.dry_run() {
783 #[cfg(feature = "tracing")]
784 let _real_run_span = span!(tracing::Level::DEBUG, "executing real run").entered();
785
786 {
789 #[cfg(feature = "tracing")]
790 let _sanity_check_span =
791 span!(tracing::Level::DEBUG, "(1) executing dry-run sanity-check").entered();
792 self.config.set_dry_run(DryRun::SelfCheck);
793 let builder = builder::Builder::new(self);
794 builder.execute_cli();
795 }
796
797 {
799 #[cfg(feature = "tracing")]
800 let _actual_run_span =
801 span!(tracing::Level::DEBUG, "(2) executing actual run").entered();
802 self.config.set_dry_run(DryRun::Disabled);
803 let builder = builder::Builder::new(self);
804 builder.execute_cli();
805 }
806 } else {
807 #[cfg(feature = "tracing")]
808 let _dry_run_span = span!(tracing::Level::DEBUG, "executing dry run").entered();
809
810 let builder = builder::Builder::new(self);
811 builder.execute_cli();
812 }
813
814 #[cfg(feature = "tracing")]
815 debug!("checking for postponed test failures from `test --no-fail-fast`");
816
817 self.config.exec_ctx().report_failures_and_exit();
819
820 #[cfg(feature = "build-metrics")]
821 self.metrics.persist(self);
822 }
823
824 fn rust_info(&self) -> &GitInfo {
825 &self.config.rust_info
826 }
827
828 fn std_features(&self, target: TargetSelection) -> String {
831 let mut features: BTreeSet<&str> =
832 self.config.rust_std_features.iter().map(|s| s.as_str()).collect();
833
834 match self.config.llvm_libunwind(target) {
835 LlvmLibunwind::InTree => features.insert("llvm-libunwind"),
836 LlvmLibunwind::System => features.insert("system-llvm-libunwind"),
837 LlvmLibunwind::No => false,
838 };
839
840 if self.config.backtrace {
841 features.insert("backtrace");
842 }
843
844 if self.config.profiler_enabled(target) {
845 features.insert("profiler");
846 }
847
848 if target.contains("zkvm") {
850 features.insert("compiler-builtins-mem");
851 }
852
853 features.into_iter().collect::<Vec<_>>().join(" ")
854 }
855
856 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
858 let possible_features_by_crates: HashSet<_> = crates
859 .iter()
860 .flat_map(|krate| &self.crates[krate].features)
861 .map(std::ops::Deref::deref)
862 .collect();
863 let check = |feature: &str| -> bool {
864 crates.is_empty() || possible_features_by_crates.contains(feature)
865 };
866 let mut features = vec![];
867
868 if let Some(allocator_feature_name) = self.config.allocator(target).feature_name()
869 && check(allocator_feature_name)
870 {
871 features.push(allocator_feature_name);
872 }
873 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
874 features.push("llvm");
875 }
876 if self.config.llvm_offload {
877 features.push("llvm_offload");
878 }
879 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
881 features.push("rustc_randomized_layouts");
882 }
883 if self.config.compile_time_deps && kind == Kind::Check {
884 features.push("check_only");
885 }
886
887 if crates.iter().any(|c| c == "rustc_transmute") {
888 features.push("rustc");
891 }
892
893 if !self.config.rust_debug_logging && check("max_level_info") {
899 features.push("max_level_info");
900 }
901
902 features.join(" ")
903 }
904
905 fn cargo_dir(&self, mode: Mode) -> &'static str {
908 match (mode, self.config.rust_optimize.is_release()) {
909 (Mode::Std, _) => "dist",
910 (_, true) => "release",
911 (_, false) => "debug",
912 }
913 }
914
915 fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
916 let out = self
917 .out
918 .join(build_compiler.host)
919 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
920 t!(fs::create_dir_all(&out));
921 out
922 }
923
924 fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
929 use std::fmt::Write;
930
931 fn bootstrap_tool() -> (Option<u32>, &'static str) {
932 (None, "bootstrap-tools")
933 }
934 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
935 (Some(build_compiler.stage + 1), "tools")
936 }
937
938 let (stage, suffix) = match mode {
939 Mode::Std => (Some(build_compiler.stage), "std"),
941 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
943 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
944 Mode::ToolBootstrap => bootstrap_tool(),
945 Mode::ToolStd | Mode::ToolRustcPrivate => (Some(build_compiler.stage + 1), "tools"),
946 Mode::ToolTarget => {
947 if build_compiler.stage == 0 {
950 bootstrap_tool()
951 } else {
952 staged_tool(build_compiler)
953 }
954 }
955 };
956 let path = self.out.join(build_compiler.host);
957 let mut dir_name = String::new();
958 if let Some(stage) = stage {
959 write!(dir_name, "stage{stage}-").unwrap();
960 }
961 dir_name.push_str(suffix);
962 path.join(dir_name)
963 }
964
965 fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
969 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir(mode))
970 }
971
972 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
977 if self.config.llvm_from_ci && self.config.is_host_target(target) {
978 self.config.ci_llvm_root()
979 } else {
980 self.out.join(target).join("llvm")
981 }
982 }
983
984 fn doc_out(&self, target: TargetSelection) -> PathBuf {
986 self.out.join(target).join("doc")
987 }
988
989 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
991 self.out.join(target).join("json-doc")
992 }
993
994 fn test_out(&self, target: TargetSelection) -> PathBuf {
995 self.out.join(target).join("test")
996 }
997
998 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
1000 self.out.join(target).join("compiler-doc")
1001 }
1002
1003 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
1005 self.out.join(target).join("md-doc")
1006 }
1007
1008 fn vendored_crates_path(&self) -> Option<PathBuf> {
1010 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1011 }
1012
1013 fn native_dir(&self, target: TargetSelection) -> PathBuf {
1015 self.out.join(target).join("native")
1016 }
1017
1018 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1021 self.native_dir(target).join("rust-test-helpers")
1022 }
1023
1024 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1026 if env::var_os("RUST_TEST_THREADS").is_none() {
1027 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1028 }
1029 }
1030
1031 fn rustc_snapshot_libdir(&self) -> PathBuf {
1033 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1034 }
1035
1036 fn rustc_snapshot_sysroot(&self) -> &Path {
1038 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1039 SYSROOT_CACHE.get_or_init(|| {
1040 command(&self.initial_rustc)
1041 .run_in_dry_run()
1042 .args(["--print", "sysroot"])
1043 .run_capture_stdout(self)
1044 .stdout()
1045 .trim()
1046 .to_owned()
1047 .into()
1048 })
1049 }
1050
1051 fn info(&self, msg: &str) {
1052 match self.config.get_dry_run() {
1053 DryRun::SelfCheck => (),
1054 DryRun::Disabled | DryRun::UserSelected => {
1055 println!("{msg}");
1056 }
1057 }
1058 }
1059
1060 #[must_use = "Groups should not be dropped until the Step finishes running"]
1072 #[track_caller]
1073 fn msg(
1074 &self,
1075 action: impl Into<Kind>,
1076 what: impl Display,
1077 mode: impl Into<Option<Mode>>,
1078 target_and_stage: impl Into<TargetAndStage>,
1079 target: impl Into<Option<TargetSelection>>,
1080 ) -> Option<gha::Group> {
1081 let target_and_stage = target_and_stage.into();
1082 let action = action.into();
1083 assert!(
1084 action != Kind::Test,
1085 "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1086 );
1087
1088 let actual_stage = match mode.into() {
1089 Some(Mode::Std) => target_and_stage.stage,
1091 Some(
1093 Mode::Rustc
1094 | Mode::Codegen
1095 | Mode::ToolBootstrap
1096 | Mode::ToolTarget
1097 | Mode::ToolStd
1098 | Mode::ToolRustcPrivate,
1099 )
1100 | None => target_and_stage.stage + 1,
1101 };
1102
1103 let action = action.description();
1104 let what = what.to_string();
1105 let msg = |fmt| {
1106 let space = if !what.is_empty() { " " } else { "" };
1107 format!("{action} stage{actual_stage} {what}{space}{fmt}")
1108 };
1109 let msg = if let Some(target) = target.into() {
1110 let build_stage = target_and_stage.stage;
1111 let host = target_and_stage.target;
1112 if host == target {
1113 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1114 } else {
1115 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1116 }
1117 } else {
1118 msg(format_args!(""))
1119 };
1120 self.group(&msg)
1121 }
1122
1123 #[must_use = "Groups should not be dropped until the Step finishes running"]
1129 #[track_caller]
1130 fn msg_test(
1131 &self,
1132 what: impl Display,
1133 target: TargetSelection,
1134 stage: u32,
1135 ) -> Option<gha::Group> {
1136 let action = Kind::Test.description();
1137 let msg = format!("{action} stage{stage} {what} ({target})");
1138 self.group(&msg)
1139 }
1140
1141 #[must_use = "Groups should not be dropped until the Step finishes running"]
1145 #[track_caller]
1146 fn msg_unstaged(
1147 &self,
1148 action: impl Into<Kind>,
1149 what: impl Display,
1150 target: TargetSelection,
1151 ) -> Option<gha::Group> {
1152 let action = action.into().description();
1153 let msg = format!("{action} {what} for {target}");
1154 self.group(&msg)
1155 }
1156
1157 #[track_caller]
1158 fn group(&self, msg: &str) -> Option<gha::Group> {
1159 match self.config.get_dry_run() {
1160 DryRun::SelfCheck => None,
1161 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1162 }
1163 }
1164
1165 fn jobs(&self) -> u32 {
1168 self.config.jobs.unwrap_or_else(|| {
1169 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1170 })
1171 }
1172
1173 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1174 if !self.config.rust_remap_debuginfo {
1175 return None;
1176 }
1177
1178 match which {
1179 GitRepo::Rustc => {
1180 let sha = self.rust_sha().unwrap_or(&self.version);
1181
1182 match remap_scheme {
1183 RemapScheme::Compiler => {
1184 Some(format!("/rustc-dev/{sha}"))
1193 }
1194 RemapScheme::NonCompiler => {
1195 Some(format!("/rustc/{sha}"))
1197 }
1198 }
1199 }
1200 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1201 }
1202 }
1203
1204 fn cc(&self, target: TargetSelection) -> PathBuf {
1206 if self.config.dry_run() {
1207 return PathBuf::new();
1208 }
1209 self.cc[&target].path().into()
1210 }
1211
1212 fn cc_tool(&self, target: TargetSelection) -> Tool {
1214 self.cc[&target].clone()
1215 }
1216
1217 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1219 self.cxx[&target].clone()
1220 }
1221
1222 fn cc_handled_cflags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1225 if self.config.dry_run() {
1226 return Vec::new();
1227 }
1228 let base = match c {
1229 CLang::C => self.cc[&target].clone(),
1230 CLang::Cxx => self.cxx[&target].clone(),
1231 };
1232
1233 base.args()
1236 .iter()
1237 .map(|s| s.to_string_lossy().into_owned())
1238 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1239 .collect::<Vec<String>>()
1240 }
1241
1242 fn cc_unhandled_cflags(
1244 &self,
1245 target: TargetSelection,
1246 which: GitRepo,
1247 c: CLang,
1248 ) -> Vec<String> {
1249 let mut base = Vec::new();
1250
1251 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1255 base.push("-stdlib=libc++".into());
1256 }
1257
1258 if &*target.triple == "i686-pc-windows-gnu" {
1262 base.push("-fno-omit-frame-pointer".into());
1263 }
1264
1265 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1266 let map = format!("{}={}", self.src.display(), map_to);
1267 let cc = self.cc_tool(target);
1268 if cc.is_like_clang() || cc.is_like_gnu() {
1269 base.push(format!("-fdebug-prefix-map={map}"));
1270 } else if cc.is_like_clang_cl() {
1271 base.push("-Xclang".into());
1272 base.push(format!("-fdebug-prefix-map={map}"));
1273 }
1274 }
1275 base
1276 }
1277
1278 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1280 if self.config.dry_run() {
1281 return None;
1282 }
1283 self.ar.get(&target).cloned()
1284 }
1285
1286 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1288 if self.config.dry_run() {
1289 return None;
1290 }
1291 self.ranlib.get(&target).cloned()
1292 }
1293
1294 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1296 if self.config.dry_run() {
1297 return Ok(PathBuf::new());
1298 }
1299 match self.cxx.get(&target) {
1300 Some(p) => Ok(p.path().into()),
1301 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1302 }
1303 }
1304
1305 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1307 if self.config.dry_run() {
1308 return Some(PathBuf::new());
1309 }
1310 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1311 {
1312 Some(linker)
1313 } else if target.contains("vxworks") {
1314 Some(self.cxx[&target].path().into())
1317 } else if !self.config.is_host_target(target)
1318 && helpers::use_host_linker(target)
1319 && !target.is_msvc()
1320 {
1321 Some(self.cc(target))
1322 } else if self.config.bootstrap_override_lld.is_used()
1323 && self.is_lld_direct_linker(target)
1324 && self.host_target == target
1325 {
1326 match self.config.bootstrap_override_lld {
1327 BootstrapOverrideLld::SelfContained => Some(self.initial_lld.clone()),
1328 BootstrapOverrideLld::External => Some("lld".into()),
1329 BootstrapOverrideLld::None => None,
1330 }
1331 } else {
1332 None
1333 }
1334 }
1335
1336 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1339 target.is_msvc()
1340 }
1341
1342 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1344 if target.contains("pc-windows-msvc") {
1345 Some(true)
1346 } else {
1347 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1348 }
1349 }
1350
1351 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1356 let configured_root = self
1357 .config
1358 .target_config
1359 .get(&target)
1360 .and_then(|t| t.musl_root.as_ref())
1361 .or(self.config.musl_root.as_ref())
1362 .map(|p| &**p);
1363
1364 if self.config.is_host_target(target) && configured_root.is_none() {
1365 Some(Path::new("/usr"))
1366 } else {
1367 configured_root
1368 }
1369 }
1370
1371 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1373 self.config
1374 .target_config
1375 .get(&target)
1376 .and_then(|t| t.musl_libdir.clone())
1377 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1378 }
1379
1380 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1387 let configured =
1388 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1389 if let Some(path) = configured {
1390 return Some(path.join("lib").join(target.to_string()));
1391 }
1392 let mut env_root = self.wasi_sdk_path.clone()?;
1393 env_root.push("share");
1394 env_root.push("wasi-sysroot");
1395 env_root.push("lib");
1396 env_root.push(target.to_string());
1397 Some(env_root)
1398 }
1399
1400 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1402 self.config.target_config.get(&target).map(|t| t.no_std)
1403 }
1404
1405 fn remote_tested(&self, target: TargetSelection) -> bool {
1408 self.qemu_rootfs(target).is_some()
1409 || target.contains("android")
1410 || env::var_os("TEST_DEVICE_ADDR").is_some()
1411 }
1412
1413 fn runner(&self, target: TargetSelection) -> Option<String> {
1419 let configured_runner =
1420 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1421 if let Some(runner) = configured_runner {
1422 return Some(runner.to_owned());
1423 }
1424
1425 if target.starts_with("wasm") && target.contains("wasi") {
1426 self.default_wasi_runner(target)
1427 } else {
1428 None
1429 }
1430 }
1431
1432 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1436 let mut finder = crate::core::sanity::Finder::new();
1437
1438 if let Some(path) = finder.maybe_have("wasmtime")
1442 && let Ok(mut path) = path.into_os_string().into_string()
1443 {
1444 path.push_str(" run -Wexceptions -C cache=n --dir .");
1445 path.push_str(" --env RUSTC_BOOTSTRAP");
1452
1453 if target.contains("wasip2") {
1454 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1455 }
1456
1457 return Some(path);
1458 }
1459
1460 None
1461 }
1462
1463 fn tool_enabled(&self, tool: &str) -> bool {
1468 if !self.config.extended {
1469 return false;
1470 }
1471 match &self.config.tools {
1472 Some(set) => set.contains(tool),
1473 None => true,
1474 }
1475 }
1476
1477 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1483 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1484 }
1485
1486 fn extended_error_dir(&self) -> PathBuf {
1488 self.out.join("tmp/extended-error-metadata")
1489 }
1490
1491 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1510 !self.config.full_bootstrap
1511 && !self.config.download_rustc()
1512 && stage >= 2
1513 && (self.hosts.contains(&target) || target == self.host_target)
1514 }
1515
1516 fn force_use_stage2(&self, stage: u32) -> bool {
1522 self.config.download_rustc() && stage >= 2
1523 }
1524
1525 fn release(&self, num: &str) -> String {
1531 match &self.config.channel[..] {
1532 "stable" => num.to_string(),
1533 "beta" => {
1534 if !self.config.omit_git_hash {
1535 format!("{}-beta.{}", num, self.beta_prerelease_version())
1536 } else {
1537 format!("{num}-beta")
1538 }
1539 }
1540 "nightly" => format!("{num}-nightly"),
1541 _ => format!("{num}-dev"),
1542 }
1543 }
1544
1545 fn beta_prerelease_version(&self) -> u32 {
1546 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1547 let version = fs::read_to_string(version_file).ok()?;
1548
1549 helpers::extract_beta_rev(&version)
1550 }
1551
1552 if let Some(s) = self.prerelease_version.get() {
1553 return s;
1554 }
1555
1556 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1560 helpers::git(Some(&self.src))
1564 .arg("rev-list")
1565 .arg("--count")
1566 .arg("--merges")
1567 .arg(format!(
1568 "refs/remotes/origin/{}..HEAD",
1569 self.config.stage0_metadata.config.nightly_branch
1570 ))
1571 .run_in_dry_run()
1572 .run_capture(self)
1573 .stdout()
1574 });
1575 let n = count.trim().parse().unwrap();
1576 self.prerelease_version.set(Some(n));
1577 n
1578 }
1579
1580 fn rust_release(&self) -> String {
1582 self.release(&self.version)
1583 }
1584
1585 fn rust_package_vers(&self) -> String {
1591 match &self.config.channel[..] {
1592 "stable" => self.version.to_string(),
1593 "beta" => "beta".to_string(),
1594 "nightly" => "nightly".to_string(),
1595 _ => format!("{}-dev", self.version),
1596 }
1597 }
1598
1599 fn rust_version(&self) -> String {
1605 let mut version = self.rust_info().version(self, &self.version);
1606 if let Some(ref s) = self.config.description
1607 && !s.is_empty()
1608 {
1609 version.push_str(" (");
1610 version.push_str(s);
1611 version.push(')');
1612 }
1613 version
1614 }
1615
1616 fn rust_sha(&self) -> Option<&str> {
1618 self.rust_info().sha()
1619 }
1620
1621 fn release_num(&self, package: &str) -> String {
1623 if self.config.dry_run() {
1624 return "0.0.0 (dry-run)".into();
1625 }
1626 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1627 let toml = t!(fs::read_to_string(toml_file_name));
1628 for line in toml.lines() {
1629 if let Some(stripped) =
1630 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1631 {
1632 return stripped.to_owned();
1633 }
1634 }
1635
1636 panic!("failed to find version in {package}'s Cargo.toml")
1637 }
1638
1639 fn unstable_features(&self) -> bool {
1642 !matches!(&self.config.channel[..], "stable" | "beta")
1643 }
1644
1645 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1649 let mut ret = Vec::new();
1650 let mut list = vec![root.to_owned()];
1651 let mut visited = HashSet::new();
1652 while let Some(krate) = list.pop() {
1653 let krate = self
1654 .crates
1655 .get(&krate)
1656 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1657 ret.push(krate);
1658 for dep in &krate.deps {
1659 if !self.crates.contains_key(dep) {
1660 continue;
1662 }
1663 if visited.insert(dep)
1669 && (dep != "profiler_builtins"
1670 || target
1671 .map(|t| self.config.profiler_enabled(t))
1672 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1673 && (dep != "rustc_codegen_llvm"
1674 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1675 {
1676 list.push(dep.clone());
1677 }
1678 }
1679 }
1680
1681 ret.sort_unstable_by(|a, b| Ord::cmp(&a.name, &b.name));
1683 ret
1684 }
1685
1686 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1687 if self.config.dry_run() {
1688 return Vec::new();
1689 }
1690
1691 if !stamp.path().exists() {
1692 eprintln!(
1693 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1694 stamp.path().display()
1695 );
1696 crate::exit!(1);
1697 }
1698
1699 let mut paths = Vec::new();
1700 let contents = t!(fs::read(stamp.path()), stamp.path());
1701 for part in contents.split(|b| *b == 0) {
1704 if part.is_empty() {
1705 continue;
1706 }
1707 let dependency_type = match part[0] as char {
1708 'h' => DependencyType::Host,
1709 's' => DependencyType::TargetSelfContained,
1710 't' => DependencyType::Target,
1711 _ => unreachable!(),
1712 };
1713 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1714 paths.push((path, dependency_type));
1715 }
1716 paths
1717 }
1718
1719 #[track_caller]
1724 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1725 self.copy_link_internal(src, dst, true);
1726 }
1727
1728 #[track_caller]
1733 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1734 self.copy_link_internal(src, dst, false);
1735
1736 if file_type.could_have_split_debuginfo()
1737 && let Some(dbg_file) = split_debuginfo(src)
1738 {
1739 self.copy_link_internal(
1740 &dbg_file,
1741 &dst.with_extension(dbg_file.extension().unwrap()),
1742 false,
1743 );
1744 }
1745 }
1746
1747 #[track_caller]
1748 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1749 if self.config.dry_run() {
1750 return;
1751 }
1752 if src == dst {
1753 return;
1754 }
1755
1756 #[cfg(feature = "tracing")]
1757 let _span = trace_io!("file-copy-link", ?src, ?dst);
1758
1759 if let Err(e) = fs::remove_file(dst)
1760 && cfg!(windows)
1761 && e.kind() != io::ErrorKind::NotFound
1762 {
1763 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1766 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1767 }
1768 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1769 let mut src = src.to_path_buf();
1770 if metadata.file_type().is_symlink() {
1771 if dereference_symlinks {
1772 src = t!(fs::canonicalize(src));
1773 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1774 } else {
1775 let link = t!(fs::read_link(src));
1776 t!(self.symlink_file(link, dst));
1777 return;
1778 }
1779 }
1780 if let Ok(()) = fs::hard_link(&src, dst) {
1781 } else {
1784 if let Err(e) = fs::copy(&src, dst) {
1785 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1786 }
1787 t!(fs::set_permissions(dst, metadata.permissions()));
1788
1789 let file_times = fs::FileTimes::new()
1792 .set_accessed(t!(metadata.accessed()))
1793 .set_modified(t!(metadata.modified()));
1794 t!(set_file_times(dst, file_times));
1795 }
1796 }
1797
1798 #[track_caller]
1802 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1803 if self.config.dry_run() {
1804 return;
1805 }
1806 for f in self.read_dir(src) {
1807 let path = f.path();
1808 let name = path.file_name().unwrap();
1809 let dst = dst.join(name);
1810 if t!(f.file_type()).is_dir() {
1811 t!(fs::create_dir_all(&dst));
1812 self.cp_link_r(&path, &dst);
1813 } else {
1814 self.copy_link(&path, &dst, FileType::Regular);
1815 }
1816 }
1817 }
1818
1819 #[track_caller]
1825 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1826 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1828 }
1829
1830 #[track_caller]
1832 fn cp_link_filtered_recurse(
1833 &self,
1834 src: &Path,
1835 dst: &Path,
1836 relative: &Path,
1837 filter: &dyn Fn(&Path) -> bool,
1838 ) {
1839 for f in self.read_dir(src) {
1840 let path = f.path();
1841 let name = path.file_name().unwrap();
1842 let dst = dst.join(name);
1843 let relative = relative.join(name);
1844 if filter(&relative) {
1846 if t!(f.file_type()).is_dir() {
1847 let _ = fs::remove_dir_all(&dst);
1848 self.create_dir(&dst);
1849 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1850 } else {
1851 self.copy_link(&path, &dst, FileType::Regular);
1852 }
1853 }
1854 }
1855 }
1856
1857 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1858 let file_name = src.file_name().unwrap();
1859 let dest = dest_folder.join(file_name);
1860 self.copy_link(src, &dest, FileType::Regular);
1861 }
1862
1863 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1864 if self.config.dry_run() {
1865 return;
1866 }
1867 let dst = dstdir.join(src.file_name().unwrap());
1868
1869 #[cfg(feature = "tracing")]
1870 let _span = trace_io!("install", ?src, ?dst);
1871
1872 t!(fs::create_dir_all(dstdir));
1873 if !src.exists() {
1874 panic!("ERROR: File \"{}\" not found!", src.display());
1875 }
1876
1877 self.copy_link_internal(src, &dst, true);
1878 chmod(&dst, file_type.perms());
1879
1880 if file_type.could_have_split_debuginfo()
1882 && let Some(dbg_file) = split_debuginfo(src)
1883 {
1884 self.install(&dbg_file, dstdir, FileType::Regular);
1885 }
1886 }
1887
1888 fn read(&self, path: &Path) -> String {
1889 if self.config.dry_run() {
1890 return String::new();
1891 }
1892 t!(fs::read_to_string(path))
1893 }
1894
1895 #[track_caller]
1896 fn create_dir(&self, dir: &Path) {
1897 if self.config.dry_run() {
1898 return;
1899 }
1900
1901 #[cfg(feature = "tracing")]
1902 let _span = trace_io!("dir-create", ?dir);
1903
1904 t!(fs::create_dir_all(dir))
1905 }
1906
1907 fn remove_dir(&self, dir: &Path) {
1908 if self.config.dry_run() {
1909 return;
1910 }
1911
1912 #[cfg(feature = "tracing")]
1913 let _span = trace_io!("dir-remove", ?dir);
1914
1915 t!(fs::remove_dir_all(dir))
1916 }
1917
1918 fn clear_dir(&self, dir: &Path) {
1921 if self.config.dry_run() {
1922 return;
1923 }
1924
1925 #[cfg(feature = "tracing")]
1926 let _span = trace_io!("dir-clear", ?dir);
1927
1928 let _ = std::fs::remove_dir_all(dir);
1929 self.create_dir(dir);
1930 }
1931
1932 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1933 let iter = match fs::read_dir(dir) {
1934 Ok(v) => v,
1935 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1936 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
1937 };
1938 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1939 }
1940
1941 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1942 #[cfg(unix)]
1943 use std::os::unix::fs::symlink as symlink_file;
1944 #[cfg(windows)]
1945 use std::os::windows::fs::symlink_file;
1946 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1947 }
1948
1949 fn ninja(&self) -> bool {
1952 let mut cmd_finder = crate::core::sanity::Finder::new();
1953
1954 if self.config.ninja_in_file {
1955 if cmd_finder.maybe_have("ninja-build").is_none()
1958 && cmd_finder.maybe_have("ninja").is_none()
1959 {
1960 eprintln!(
1961 "
1962Couldn't find required command: ninja (or ninja-build)
1963
1964You should install ninja as described at
1965<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1966or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
1967Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1968to download LLVM rather than building it.
1969"
1970 );
1971 exit!(1);
1972 }
1973 }
1974
1975 if !self.config.ninja_in_file
1983 && self.config.host_target.is_msvc()
1984 && cmd_finder.maybe_have("ninja").is_some()
1985 {
1986 return true;
1987 }
1988
1989 self.config.ninja_in_file
1990 }
1991
1992 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1993 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
1994 }
1995
1996 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
1997 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
1998 }
1999
2000 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2001 where
2002 C: Fn(ColorChoice) -> StandardStream,
2003 F: FnOnce(&mut dyn WriteColor) -> R,
2004 {
2005 let choice = match self.config.color {
2006 flags::Color::Always => ColorChoice::Always,
2007 flags::Color::Never => ColorChoice::Never,
2008 flags::Color::Auto if !is_tty => ColorChoice::Never,
2009 flags::Color::Auto => ColorChoice::Auto,
2010 };
2011 let mut stream = constructor(choice);
2012 let result = f(&mut stream);
2013 stream.reset().unwrap();
2014 result
2015 }
2016
2017 pub fn exec_ctx(&self) -> &ExecutionContext {
2018 &self.config.exec_ctx
2019 }
2020
2021 pub fn report_summary(&self, path: &Path, start_time: Instant) {
2022 self.config.exec_ctx.profiler().report_summary(path, start_time);
2023 }
2024
2025 #[cfg(feature = "tracing")]
2026 pub fn report_step_graph(self, directory: &Path) {
2027 self.step_graph.into_inner().store_to_dot_files(directory);
2028 }
2029}
2030
2031impl AsRef<ExecutionContext> for Build {
2032 fn as_ref(&self) -> &ExecutionContext {
2033 &self.config.exec_ctx
2034 }
2035}
2036
2037#[cfg(unix)]
2038fn chmod(path: &Path, perms: u32) {
2039 use std::os::unix::fs::*;
2040 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2041}
2042#[cfg(windows)]
2043fn chmod(_path: &Path, _perms: u32) {}
2044
2045impl Compiler {
2046 pub fn new(stage: u32, host: TargetSelection) -> Self {
2047 Self { stage, host, forced_compiler: false }
2048 }
2049
2050 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2051 self.forced_compiler = forced_compiler;
2052 }
2053
2054 pub fn is_snapshot(&self, build: &Build) -> bool {
2056 self.stage == 0 && self.host == build.host_target
2057 }
2058
2059 pub fn is_forced_compiler(&self) -> bool {
2061 self.forced_compiler
2062 }
2063}
2064
2065fn envify(s: &str) -> String {
2066 s.chars()
2069 .map(|c| match c {
2070 '-' | '.' => '_',
2071 c => c,
2072 })
2073 .flat_map(|c| c.to_uppercase())
2074 .collect()
2075}
2076
2077pub fn prepare_behaviour_dump_dir(build: &Build) {
2079 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2080
2081 let dump_path = build.out.join("bootstrap-shims-dump");
2082
2083 let initialized = INITIALIZED.get().unwrap_or(&false);
2084 if !initialized {
2085 if dump_path.exists() {
2087 t!(fs::remove_dir_all(&dump_path));
2088 }
2089
2090 t!(fs::create_dir_all(&dump_path));
2091
2092 t!(INITIALIZED.set(true));
2093 }
2094}
2095
2096#[macro_export]
2097macro_rules! exit {
2098 ($code:expr) => {
2099 $crate::utils::helpers::detail_exit($code, cfg!(test));
2100 };
2101}