1#![cfg_attr(test, allow(unused))]
19
20use std::cell::Cell;
21use std::collections::{BTreeSet, HashMap, HashSet};
22use std::fmt::Display;
23use std::path::{Path, PathBuf};
24use std::sync::OnceLock;
25use std::time::{Instant, SystemTime};
26use std::{env, fs, io, str};
27
28use build_helper::ci::gha;
29use build_helper::exit;
30use cc::Tool;
31use termcolor::{ColorChoice, StandardStream, WriteColor};
32use utils::build_stamp::BuildStamp;
33use utils::channel::GitInfo;
34use utils::exec::ExecutionContext;
35
36use crate::core::builder;
37use crate::core::builder::Kind;
38use crate::core::config::{DryRun, LldMode, LlvmLibunwind, TargetSelection, flags};
39use crate::utils::exec::{BootstrapCommand, command};
40use crate::utils::helpers::{self, dir_is_empty, exe, libdir, set_file_times, split_debuginfo};
41
42mod core;
43mod utils;
44
45pub use core::builder::PathSet;
46#[cfg(feature = "tracing")]
47pub use core::builder::STEP_SPAN_TARGET;
48pub use core::config::flags::{Flags, Subcommand};
49pub use core::config::{ChangeId, Config};
50
51#[cfg(feature = "tracing")]
52use tracing::{instrument, span};
53pub use utils::change_tracker::{
54 CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes,
55};
56pub use utils::helpers::{PanicTracker, symlink_dir};
57#[cfg(feature = "tracing")]
58pub use utils::tracing::setup_tracing;
59
60use crate::core::build_steps::vendor::VENDOR_DIR;
61
62const LLVM_TOOLS: &[&str] = &[
63 "llvm-cov", "llvm-nm", "llvm-objcopy", "llvm-objdump", "llvm-profdata", "llvm-readobj", "llvm-size", "llvm-strip", "llvm-ar", "llvm-as", "llvm-dis", "llvm-link", "llc", "opt", ];
78
79const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
81
82#[expect(clippy::type_complexity)] const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
86 (Some(Mode::Rustc), "bootstrap", None),
87 (Some(Mode::Codegen), "bootstrap", None),
88 (Some(Mode::ToolRustc), "bootstrap", None),
89 (Some(Mode::ToolStd), "bootstrap", None),
90 (Some(Mode::Rustc), "llvm_enzyme", None),
91 (Some(Mode::Codegen), "llvm_enzyme", None),
92 (Some(Mode::ToolRustc), "llvm_enzyme", None),
93 (Some(Mode::ToolRustc), "rust_analyzer", None),
94 (Some(Mode::ToolStd), "rust_analyzer", None),
95 ];
99
100#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
106pub struct Compiler {
107 stage: u32,
108 host: TargetSelection,
109 forced_compiler: bool,
113}
114
115impl std::hash::Hash for Compiler {
116 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
117 self.stage.hash(state);
118 self.host.hash(state);
119 }
120}
121
122impl PartialEq for Compiler {
123 fn eq(&self, other: &Self) -> bool {
124 self.stage == other.stage && self.host == other.host
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
130pub enum CodegenBackendKind {
131 #[default]
132 Llvm,
133 Cranelift,
134 Gcc,
135 Custom(String),
136}
137
138impl CodegenBackendKind {
139 pub fn name(&self) -> &str {
142 match self {
143 CodegenBackendKind::Llvm => "llvm",
144 CodegenBackendKind::Cranelift => "cranelift",
145 CodegenBackendKind::Gcc => "gcc",
146 CodegenBackendKind::Custom(name) => name,
147 }
148 }
149
150 pub fn crate_name(&self) -> String {
152 format!("rustc_codegen_{}", self.name())
153 }
154
155 pub fn is_llvm(&self) -> bool {
156 matches!(self, Self::Llvm)
157 }
158
159 pub fn is_cranelift(&self) -> bool {
160 matches!(self, Self::Cranelift)
161 }
162
163 pub fn is_gcc(&self) -> bool {
164 matches!(self, Self::Gcc)
165 }
166}
167
168impl std::str::FromStr for CodegenBackendKind {
169 type Err = &'static str;
170
171 fn from_str(s: &str) -> Result<Self, Self::Err> {
172 match s.to_lowercase().as_str() {
173 "" => Err("Invalid empty backend name"),
174 "gcc" => Ok(Self::Gcc),
175 "llvm" => Ok(Self::Llvm),
176 "cranelift" => Ok(Self::Cranelift),
177 _ => Ok(Self::Custom(s.to_string())),
178 }
179 }
180}
181
182#[derive(PartialEq, Eq, Copy, Clone, Debug)]
183pub enum DocTests {
184 Yes,
186 No,
188 Only,
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 doc_tests: DocTests,
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 ToolRustc,
342}
343
344impl Mode {
345 pub fn is_tool(&self) -> bool {
346 match self {
347 Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd | Mode::ToolTarget => true,
348 Mode::Std | Mode::Codegen | Mode::Rustc => false,
349 }
350 }
351
352 pub fn must_support_dlopen(&self) -> bool {
353 match self {
354 Mode::Std | Mode::Codegen => true,
355 Mode::ToolBootstrap
356 | Mode::ToolRustc
357 | Mode::ToolStd
358 | Mode::ToolTarget
359 | Mode::Rustc => false,
360 }
361 }
362}
363
364pub enum RemapScheme {
368 Compiler,
370 NonCompiler,
372}
373
374#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
375pub enum CLang {
376 C,
377 Cxx,
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
381pub enum FileType {
382 Executable,
384 NativeLibrary,
386 Script,
388 Regular,
390}
391
392impl FileType {
393 pub fn perms(self) -> u32 {
395 match self {
396 FileType::Executable | FileType::Script => 0o755,
397 FileType::Regular | FileType::NativeLibrary => 0o644,
398 }
399 }
400
401 pub fn could_have_split_debuginfo(self) -> bool {
402 match self {
403 FileType::Executable | FileType::NativeLibrary => true,
404 FileType::Script | FileType::Regular => false,
405 }
406 }
407}
408
409macro_rules! forward {
410 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
411 impl Build {
412 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
413 self.config.$fn( $($param),* )
414 } )+
415 }
416 }
417}
418
419forward! {
420 verbose(f: impl Fn()),
421 is_verbose() -> bool,
422 create(path: &Path, s: &str),
423 remove(f: &Path),
424 tempdir() -> PathBuf,
425 llvm_link_shared() -> bool,
426 download_rustc() -> bool,
427}
428
429struct TargetAndStage {
432 target: TargetSelection,
433 stage: u32,
434}
435
436impl From<(TargetSelection, u32)> for TargetAndStage {
437 fn from((target, stage): (TargetSelection, u32)) -> Self {
438 Self { target, stage }
439 }
440}
441
442impl From<Compiler> for TargetAndStage {
443 fn from(compiler: Compiler) -> Self {
444 Self { target: compiler.host, stage: compiler.stage }
445 }
446}
447
448impl Build {
449 pub fn new(mut config: Config) -> Build {
454 let src = config.src.clone();
455 let out = config.out.clone();
456
457 #[cfg(unix)]
458 let is_sudo = match env::var_os("SUDO_USER") {
461 Some(_sudo_user) => {
462 let uid = unsafe { libc::getuid() };
467 uid == 0
468 }
469 None => false,
470 };
471 #[cfg(not(unix))]
472 let is_sudo = false;
473
474 let rust_info = config.rust_info.clone();
475 let cargo_info = config.cargo_info.clone();
476 let rust_analyzer_info = config.rust_analyzer_info.clone();
477 let clippy_info = config.clippy_info.clone();
478 let miri_info = config.miri_info.clone();
479 let rustfmt_info = config.rustfmt_info.clone();
480 let enzyme_info = config.enzyme_info.clone();
481 let in_tree_llvm_info = config.in_tree_llvm_info.clone();
482 let in_tree_gcc_info = config.in_tree_gcc_info.clone();
483
484 let initial_target_libdir = command(&config.initial_rustc)
485 .run_in_dry_run()
486 .args(["--print", "target-libdir"])
487 .run_capture_stdout(&config)
488 .stdout()
489 .trim()
490 .to_owned();
491
492 let initial_target_dir = Path::new(&initial_target_libdir)
493 .parent()
494 .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent"));
495
496 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
497
498 let initial_relative_libdir = if cfg!(test) {
499 PathBuf::default()
501 } else {
502 let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| {
503 panic!("Not enough ancestors for {}", initial_target_dir.display())
504 });
505
506 ancestor
507 .strip_prefix(&config.initial_sysroot)
508 .unwrap_or_else(|_| {
509 panic!(
510 "Couldn’t resolve the initial relative libdir from {}",
511 initial_target_dir.display()
512 )
513 })
514 .to_path_buf()
515 };
516
517 let version = std::fs::read_to_string(src.join("src").join("version"))
518 .expect("failed to read src/version");
519 let version = version.trim();
520
521 let mut bootstrap_out = std::env::current_exe()
522 .expect("could not determine path to running process")
523 .parent()
524 .unwrap()
525 .to_path_buf();
526 if bootstrap_out.ends_with("deps") {
529 bootstrap_out.pop();
530 }
531 if !bootstrap_out.join(exe("rustc", config.host_target)).exists() && !cfg!(test) {
532 panic!(
534 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
535 bootstrap_out.display()
536 )
537 }
538
539 if rust_info.is_from_tarball() && config.description.is_none() {
540 config.description = Some("built from a source tarball".to_owned());
541 }
542
543 let mut build = Build {
544 initial_lld,
545 initial_relative_libdir,
546 initial_rustc: config.initial_rustc.clone(),
547 initial_rustdoc: config
548 .initial_rustc
549 .with_file_name(exe("rustdoc", config.host_target)),
550 initial_cargo: config.initial_cargo.clone(),
551 initial_sysroot: config.initial_sysroot.clone(),
552 local_rebuild: config.local_rebuild,
553 fail_fast: config.cmd.fail_fast(),
554 doc_tests: config.cmd.doc_tests(),
555 verbosity: config.exec_ctx.verbosity as usize,
556
557 host_target: config.host_target,
558 hosts: config.hosts.clone(),
559 targets: config.targets.clone(),
560
561 config,
562 version: version.to_string(),
563 src,
564 out,
565 bootstrap_out,
566
567 cargo_info,
568 rust_analyzer_info,
569 clippy_info,
570 miri_info,
571 rustfmt_info,
572 enzyme_info,
573 in_tree_llvm_info,
574 in_tree_gcc_info,
575 cc: HashMap::new(),
576 cxx: HashMap::new(),
577 ar: HashMap::new(),
578 ranlib: HashMap::new(),
579 wasi_sdk_path: env::var_os("WASI_SDK_PATH").map(PathBuf::from),
580 crates: HashMap::new(),
581 crate_paths: HashMap::new(),
582 is_sudo,
583 prerelease_version: Cell::new(None),
584
585 #[cfg(feature = "build-metrics")]
586 metrics: crate::utils::metrics::BuildMetrics::init(),
587
588 #[cfg(feature = "tracing")]
589 step_graph: std::cell::RefCell::new(crate::utils::step_graph::StepGraph::default()),
590 };
591
592 let local_version_verbose = command(&build.initial_rustc)
595 .run_in_dry_run()
596 .args(["--version", "--verbose"])
597 .run_capture_stdout(&build)
598 .stdout();
599 let local_release = local_version_verbose
600 .lines()
601 .filter_map(|x| x.strip_prefix("release:"))
602 .next()
603 .unwrap()
604 .trim();
605 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
606 build.verbose(|| println!("auto-detected local-rebuild {local_release}"));
607 build.local_rebuild = true;
608 }
609
610 build.verbose(|| println!("finding compilers"));
611 utils::cc_detect::fill_compilers(&mut build);
612 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
618 build.verbose(|| println!("running sanity check"));
619 crate::core::sanity::check(&mut build);
620
621 let rust_submodules = ["library/backtrace"];
624 for s in rust_submodules {
625 build.require_submodule(
626 s,
627 Some(
628 "The submodule is required for the standard library \
629 and the main Cargo workspace.",
630 ),
631 );
632 }
633 build.update_existing_submodules();
635
636 build.verbose(|| println!("learning about cargo"));
637 crate::core::metadata::build(&mut build);
638 }
639
640 let build_triple = build.out.join(build.host_target);
642 t!(fs::create_dir_all(&build_triple));
643 let host = build.out.join("host");
644 if host.is_symlink() {
645 #[cfg(windows)]
648 t!(fs::remove_dir(&host));
649 #[cfg(not(windows))]
650 t!(fs::remove_file(&host));
651 }
652 t!(
653 symlink_dir(&build.config, &build_triple, &host),
654 format!("symlink_dir({} => {}) failed", host.display(), build_triple.display())
655 );
656
657 build
658 }
659
660 #[cfg_attr(
669 feature = "tracing",
670 instrument(
671 level = "trace",
672 name = "Build::require_submodule",
673 skip_all,
674 fields(submodule = submodule),
675 ),
676 )]
677 pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) {
678 if self.rust_info().is_from_tarball() {
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 features.into_iter().collect::<Vec<_>>().join(" ")
852 }
853
854 fn rustc_features(&self, kind: Kind, target: TargetSelection, crates: &[String]) -> String {
856 let possible_features_by_crates: HashSet<_> = crates
857 .iter()
858 .flat_map(|krate| &self.crates[krate].features)
859 .map(std::ops::Deref::deref)
860 .collect();
861 let check = |feature: &str| -> bool {
862 crates.is_empty() || possible_features_by_crates.contains(feature)
863 };
864 let mut features = vec![];
865 if self.config.jemalloc(target) && check("jemalloc") {
866 features.push("jemalloc");
867 }
868 if (self.config.llvm_enabled(target) || kind == Kind::Check) && check("llvm") {
869 features.push("llvm");
870 }
871 if self.config.rust_randomize_layout && check("rustc_randomized_layouts") {
873 features.push("rustc_randomized_layouts");
874 }
875 if self.config.compile_time_deps && kind == Kind::Check {
876 features.push("check_only");
877 }
878
879 if !self.config.rust_debug_logging && check("max_level_info") {
885 features.push("max_level_info");
886 }
887
888 features.join(" ")
889 }
890
891 fn cargo_dir(&self) -> &'static str {
894 if self.config.rust_optimize.is_release() { "release" } else { "debug" }
895 }
896
897 fn tools_dir(&self, build_compiler: Compiler) -> PathBuf {
898 let out = self
899 .out
900 .join(build_compiler.host)
901 .join(format!("stage{}-tools-bin", build_compiler.stage + 1));
902 t!(fs::create_dir_all(&out));
903 out
904 }
905
906 fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf {
911 use std::fmt::Write;
912
913 fn bootstrap_tool() -> (Option<u32>, &'static str) {
914 (None, "bootstrap-tools")
915 }
916 fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) {
917 (Some(build_compiler.stage + 1), "tools")
918 }
919
920 let (stage, suffix) = match mode {
921 Mode::Std => (Some(build_compiler.stage), "std"),
923 Mode::Rustc => (Some(build_compiler.stage + 1), "rustc"),
925 Mode::Codegen => (Some(build_compiler.stage + 1), "codegen"),
926 Mode::ToolBootstrap => bootstrap_tool(),
927 Mode::ToolStd | Mode::ToolRustc => (Some(build_compiler.stage + 1), "tools"),
928 Mode::ToolTarget => {
929 if build_compiler.stage == 0 {
932 bootstrap_tool()
933 } else {
934 staged_tool(build_compiler)
935 }
936 }
937 };
938 let path = self.out.join(build_compiler.host);
939 let mut dir_name = String::new();
940 if let Some(stage) = stage {
941 write!(dir_name, "stage{stage}-").unwrap();
942 }
943 dir_name.push_str(suffix);
944 path.join(dir_name)
945 }
946
947 fn cargo_out(&self, build_compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
951 self.stage_out(build_compiler, mode).join(target).join(self.cargo_dir())
952 }
953
954 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
959 if self.config.llvm_from_ci && self.config.is_host_target(target) {
960 self.config.ci_llvm_root()
961 } else {
962 self.out.join(target).join("llvm")
963 }
964 }
965
966 fn enzyme_out(&self, target: TargetSelection) -> PathBuf {
967 self.out.join(&*target.triple).join("enzyme")
968 }
969
970 fn gcc_out(&self, target: TargetSelection) -> PathBuf {
971 self.out.join(&*target.triple).join("gcc")
972 }
973
974 fn lld_out(&self, target: TargetSelection) -> PathBuf {
975 self.out.join(target).join("lld")
976 }
977
978 fn doc_out(&self, target: TargetSelection) -> PathBuf {
980 self.out.join(target).join("doc")
981 }
982
983 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
985 self.out.join(target).join("json-doc")
986 }
987
988 fn test_out(&self, target: TargetSelection) -> PathBuf {
989 self.out.join(target).join("test")
990 }
991
992 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
994 self.out.join(target).join("compiler-doc")
995 }
996
997 fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
999 self.out.join(target).join("md-doc")
1000 }
1001
1002 fn vendored_crates_path(&self) -> Option<PathBuf> {
1004 if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1005 }
1006
1007 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
1009 let target_config = self.config.target_config.get(&target);
1010 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
1011 s.to_path_buf()
1012 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
1013 let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout();
1014 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
1015 if filecheck.exists() {
1016 filecheck
1017 } else {
1018 let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout();
1021 let lib_filecheck =
1022 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
1023 if lib_filecheck.exists() {
1024 lib_filecheck
1025 } else {
1026 filecheck
1030 }
1031 }
1032 } else {
1033 let base = self.llvm_out(target).join("build");
1034 let base = if !self.ninja() && target.is_msvc() {
1035 if self.config.llvm_optimize {
1036 if self.config.llvm_release_debuginfo {
1037 base.join("RelWithDebInfo")
1038 } else {
1039 base.join("Release")
1040 }
1041 } else {
1042 base.join("Debug")
1043 }
1044 } else {
1045 base
1046 };
1047 base.join("bin").join(exe("FileCheck", target))
1048 }
1049 }
1050
1051 fn native_dir(&self, target: TargetSelection) -> PathBuf {
1053 self.out.join(target).join("native")
1054 }
1055
1056 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1059 self.native_dir(target).join("rust-test-helpers")
1060 }
1061
1062 fn add_rust_test_threads(&self, cmd: &mut BootstrapCommand) {
1064 if env::var_os("RUST_TEST_THREADS").is_none() {
1065 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
1066 }
1067 }
1068
1069 fn rustc_snapshot_libdir(&self) -> PathBuf {
1071 self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1072 }
1073
1074 fn rustc_snapshot_sysroot(&self) -> &Path {
1076 static SYSROOT_CACHE: OnceLock<PathBuf> = OnceLock::new();
1077 SYSROOT_CACHE.get_or_init(|| {
1078 command(&self.initial_rustc)
1079 .run_in_dry_run()
1080 .args(["--print", "sysroot"])
1081 .run_capture_stdout(self)
1082 .stdout()
1083 .trim()
1084 .to_owned()
1085 .into()
1086 })
1087 }
1088
1089 pub fn is_verbose_than(&self, level: usize) -> bool {
1091 self.verbosity > level
1092 }
1093
1094 fn verbose_than(&self, level: usize, f: impl Fn()) {
1096 if self.is_verbose_than(level) {
1097 f()
1098 }
1099 }
1100
1101 fn info(&self, msg: &str) {
1102 match self.config.get_dry_run() {
1103 DryRun::SelfCheck => (),
1104 DryRun::Disabled | DryRun::UserSelected => {
1105 println!("{msg}");
1106 }
1107 }
1108 }
1109
1110 #[must_use = "Groups should not be dropped until the Step finishes running"]
1122 #[track_caller]
1123 fn msg(
1124 &self,
1125 action: impl Into<Kind>,
1126 what: impl Display,
1127 mode: impl Into<Option<Mode>>,
1128 target_and_stage: impl Into<TargetAndStage>,
1129 target: impl Into<Option<TargetSelection>>,
1130 ) -> Option<gha::Group> {
1131 let target_and_stage = target_and_stage.into();
1132 let action = action.into();
1133 assert!(
1134 action != Kind::Test,
1135 "Please use `Build::msg_test` instead of `Build::msg(Kind::Test)`"
1136 );
1137
1138 let actual_stage = match mode.into() {
1139 Some(Mode::Std) => target_and_stage.stage,
1141 Some(
1143 Mode::Rustc
1144 | Mode::Codegen
1145 | Mode::ToolBootstrap
1146 | Mode::ToolTarget
1147 | Mode::ToolStd
1148 | Mode::ToolRustc,
1149 )
1150 | None => target_and_stage.stage + 1,
1151 };
1152
1153 let action = action.description();
1154 let what = what.to_string();
1155 let msg = |fmt| {
1156 let space = if !what.is_empty() { " " } else { "" };
1157 format!("{action} stage{actual_stage} {what}{space}{fmt}")
1158 };
1159 let msg = if let Some(target) = target.into() {
1160 let build_stage = target_and_stage.stage;
1161 let host = target_and_stage.target;
1162 if host == target {
1163 msg(format_args!("(stage{build_stage} -> stage{actual_stage}, {target})"))
1164 } else {
1165 msg(format_args!("(stage{build_stage}:{host} -> stage{actual_stage}:{target})"))
1166 }
1167 } else {
1168 msg(format_args!(""))
1169 };
1170 self.group(&msg)
1171 }
1172
1173 #[must_use = "Groups should not be dropped until the Step finishes running"]
1179 #[track_caller]
1180 fn msg_test(
1181 &self,
1182 what: impl Display,
1183 target: TargetSelection,
1184 stage: u32,
1185 ) -> Option<gha::Group> {
1186 let action = Kind::Test.description();
1187 let msg = format!("{action} stage{stage} {what} ({target})");
1188 self.group(&msg)
1189 }
1190
1191 #[must_use = "Groups should not be dropped until the Step finishes running"]
1195 #[track_caller]
1196 fn msg_unstaged(
1197 &self,
1198 action: impl Into<Kind>,
1199 what: impl Display,
1200 target: TargetSelection,
1201 ) -> Option<gha::Group> {
1202 let action = action.into().description();
1203 let msg = format!("{action} {what} for {target}");
1204 self.group(&msg)
1205 }
1206
1207 #[track_caller]
1208 fn group(&self, msg: &str) -> Option<gha::Group> {
1209 match self.config.get_dry_run() {
1210 DryRun::SelfCheck => None,
1211 DryRun::Disabled | DryRun::UserSelected => Some(gha::group(msg)),
1212 }
1213 }
1214
1215 fn jobs(&self) -> u32 {
1218 self.config.jobs.unwrap_or_else(|| {
1219 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1220 })
1221 }
1222
1223 fn debuginfo_map_to(&self, which: GitRepo, remap_scheme: RemapScheme) -> Option<String> {
1224 if !self.config.rust_remap_debuginfo {
1225 return None;
1226 }
1227
1228 match which {
1229 GitRepo::Rustc => {
1230 let sha = self.rust_sha().unwrap_or(&self.version);
1231
1232 match remap_scheme {
1233 RemapScheme::Compiler => {
1234 Some(format!("/rustc-dev/{sha}"))
1243 }
1244 RemapScheme::NonCompiler => {
1245 Some(format!("/rustc/{sha}"))
1247 }
1248 }
1249 }
1250 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1251 }
1252 }
1253
1254 fn cc(&self, target: TargetSelection) -> PathBuf {
1256 if self.config.dry_run() {
1257 return PathBuf::new();
1258 }
1259 self.cc[&target].path().into()
1260 }
1261
1262 fn cc_tool(&self, target: TargetSelection) -> Tool {
1264 self.cc[&target].clone()
1265 }
1266
1267 fn cxx_tool(&self, target: TargetSelection) -> Tool {
1269 self.cxx[&target].clone()
1270 }
1271
1272 fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> {
1275 if self.config.dry_run() {
1276 return Vec::new();
1277 }
1278 let base = match c {
1279 CLang::C => self.cc[&target].clone(),
1280 CLang::Cxx => self.cxx[&target].clone(),
1281 };
1282
1283 base.args()
1286 .iter()
1287 .map(|s| s.to_string_lossy().into_owned())
1288 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1289 .collect::<Vec<String>>()
1290 }
1291
1292 fn cc_unhandled_cflags(
1294 &self,
1295 target: TargetSelection,
1296 which: GitRepo,
1297 c: CLang,
1298 ) -> Vec<String> {
1299 let mut base = Vec::new();
1300
1301 if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1305 base.push("-stdlib=libc++".into());
1306 }
1307
1308 if &*target.triple == "i686-pc-windows-gnu" {
1312 base.push("-fno-omit-frame-pointer".into());
1313 }
1314
1315 if let Some(map_to) = self.debuginfo_map_to(which, RemapScheme::NonCompiler) {
1316 let map = format!("{}={}", self.src.display(), map_to);
1317 let cc = self.cc(target);
1318 if cc.ends_with("clang") || cc.ends_with("gcc") {
1319 base.push(format!("-fdebug-prefix-map={map}"));
1320 } else if cc.ends_with("clang-cl.exe") {
1321 base.push("-Xclang".into());
1322 base.push(format!("-fdebug-prefix-map={map}"));
1323 }
1324 }
1325 base
1326 }
1327
1328 fn ar(&self, target: TargetSelection) -> Option<PathBuf> {
1330 if self.config.dry_run() {
1331 return None;
1332 }
1333 self.ar.get(&target).cloned()
1334 }
1335
1336 fn ranlib(&self, target: TargetSelection) -> Option<PathBuf> {
1338 if self.config.dry_run() {
1339 return None;
1340 }
1341 self.ranlib.get(&target).cloned()
1342 }
1343
1344 fn cxx(&self, target: TargetSelection) -> Result<PathBuf, String> {
1346 if self.config.dry_run() {
1347 return Ok(PathBuf::new());
1348 }
1349 match self.cxx.get(&target) {
1350 Some(p) => Ok(p.path().into()),
1351 None => Err(format!("target `{target}` is not configured as a host, only as a target")),
1352 }
1353 }
1354
1355 fn linker(&self, target: TargetSelection) -> Option<PathBuf> {
1357 if self.config.dry_run() {
1358 return Some(PathBuf::new());
1359 }
1360 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.clone())
1361 {
1362 Some(linker)
1363 } else if target.contains("vxworks") {
1364 Some(self.cxx[&target].path().into())
1367 } else if !self.config.is_host_target(target)
1368 && helpers::use_host_linker(target)
1369 && !target.is_msvc()
1370 {
1371 Some(self.cc(target))
1372 } else if self.config.lld_mode.is_used()
1373 && self.is_lld_direct_linker(target)
1374 && self.host_target == target
1375 {
1376 match self.config.lld_mode {
1377 LldMode::SelfContained => Some(self.initial_lld.clone()),
1378 LldMode::External => Some("lld".into()),
1379 LldMode::Unused => None,
1380 }
1381 } else {
1382 None
1383 }
1384 }
1385
1386 fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1389 target.is_msvc()
1390 }
1391
1392 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1394 if target.contains("pc-windows-msvc") {
1395 Some(true)
1396 } else {
1397 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1398 }
1399 }
1400
1401 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1406 let configured_root = self
1407 .config
1408 .target_config
1409 .get(&target)
1410 .and_then(|t| t.musl_root.as_ref())
1411 .or(self.config.musl_root.as_ref())
1412 .map(|p| &**p);
1413
1414 if self.config.is_host_target(target) && configured_root.is_none() {
1415 Some(Path::new("/usr"))
1416 } else {
1417 configured_root
1418 }
1419 }
1420
1421 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1423 self.config
1424 .target_config
1425 .get(&target)
1426 .and_then(|t| t.musl_libdir.clone())
1427 .or_else(|| self.musl_root(target).map(|root| root.join("lib")))
1428 }
1429
1430 fn wasi_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1437 let configured =
1438 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p);
1439 if let Some(path) = configured {
1440 return Some(path.join("lib").join(target.to_string()));
1441 }
1442 let mut env_root = self.wasi_sdk_path.clone()?;
1443 env_root.push("share");
1444 env_root.push("wasi-sysroot");
1445 env_root.push("lib");
1446 env_root.push(target.to_string());
1447 Some(env_root)
1448 }
1449
1450 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1452 self.config.target_config.get(&target).map(|t| t.no_std)
1453 }
1454
1455 fn remote_tested(&self, target: TargetSelection) -> bool {
1458 self.qemu_rootfs(target).is_some()
1459 || target.contains("android")
1460 || env::var_os("TEST_DEVICE_ADDR").is_some()
1461 }
1462
1463 fn runner(&self, target: TargetSelection) -> Option<String> {
1469 let configured_runner =
1470 self.config.target_config.get(&target).and_then(|t| t.runner.as_ref()).map(|p| &**p);
1471 if let Some(runner) = configured_runner {
1472 return Some(runner.to_owned());
1473 }
1474
1475 if target.starts_with("wasm") && target.contains("wasi") {
1476 self.default_wasi_runner(target)
1477 } else {
1478 None
1479 }
1480 }
1481
1482 fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1486 let mut finder = crate::core::sanity::Finder::new();
1487
1488 if let Some(path) = finder.maybe_have("wasmtime")
1492 && let Ok(mut path) = path.into_os_string().into_string()
1493 {
1494 path.push_str(" run -C cache=n --dir .");
1495 path.push_str(" --env RUSTC_BOOTSTRAP");
1502
1503 if target.contains("wasip2") {
1504 path.push_str(" --wasi inherit-network --wasi allow-ip-name-lookup");
1505 }
1506
1507 return Some(path);
1508 }
1509
1510 None
1511 }
1512
1513 fn tool_enabled(&self, tool: &str) -> bool {
1518 if !self.config.extended {
1519 return false;
1520 }
1521 match &self.config.tools {
1522 Some(set) => set.contains(tool),
1523 None => true,
1524 }
1525 }
1526
1527 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1533 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1534 }
1535
1536 fn python(&self) -> &Path {
1538 if self.config.host_target.ends_with("apple-darwin") {
1539 Path::new("/usr/bin/python3")
1543 } else {
1544 self.config
1545 .python
1546 .as_ref()
1547 .expect("python is required for running LLDB or rustdoc tests")
1548 }
1549 }
1550
1551 fn extended_error_dir(&self) -> PathBuf {
1553 self.out.join("tmp/extended-error-metadata")
1554 }
1555
1556 fn force_use_stage1(&self, stage: u32, target: TargetSelection) -> bool {
1575 !self.config.full_bootstrap
1576 && !self.config.download_rustc()
1577 && stage >= 2
1578 && (self.hosts.contains(&target) || target == self.host_target)
1579 }
1580
1581 fn force_use_stage2(&self, stage: u32) -> bool {
1587 self.config.download_rustc() && stage >= 2
1588 }
1589
1590 fn release(&self, num: &str) -> String {
1596 match &self.config.channel[..] {
1597 "stable" => num.to_string(),
1598 "beta" => {
1599 if !self.config.omit_git_hash {
1600 format!("{}-beta.{}", num, self.beta_prerelease_version())
1601 } else {
1602 format!("{num}-beta")
1603 }
1604 }
1605 "nightly" => format!("{num}-nightly"),
1606 _ => format!("{num}-dev"),
1607 }
1608 }
1609
1610 fn beta_prerelease_version(&self) -> u32 {
1611 fn extract_beta_rev_from_file<P: AsRef<Path>>(version_file: P) -> Option<String> {
1612 let version = fs::read_to_string(version_file).ok()?;
1613
1614 helpers::extract_beta_rev(&version)
1615 }
1616
1617 if let Some(s) = self.prerelease_version.get() {
1618 return s;
1619 }
1620
1621 let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1625 helpers::git(Some(&self.src))
1629 .arg("rev-list")
1630 .arg("--count")
1631 .arg("--merges")
1632 .arg(format!(
1633 "refs/remotes/origin/{}..HEAD",
1634 self.config.stage0_metadata.config.nightly_branch
1635 ))
1636 .run_in_dry_run()
1637 .run_capture(self)
1638 .stdout()
1639 });
1640 let n = count.trim().parse().unwrap();
1641 self.prerelease_version.set(Some(n));
1642 n
1643 }
1644
1645 fn rust_release(&self) -> String {
1647 self.release(&self.version)
1648 }
1649
1650 fn package_vers(&self, num: &str) -> String {
1657 match &self.config.channel[..] {
1658 "stable" => num.to_string(),
1659 "beta" => "beta".to_string(),
1660 "nightly" => "nightly".to_string(),
1661 _ => format!("{num}-dev"),
1662 }
1663 }
1664
1665 fn rust_package_vers(&self) -> String {
1667 self.package_vers(&self.version)
1668 }
1669
1670 fn rust_version(&self) -> String {
1676 let mut version = self.rust_info().version(self, &self.version);
1677 if let Some(ref s) = self.config.description
1678 && !s.is_empty()
1679 {
1680 version.push_str(" (");
1681 version.push_str(s);
1682 version.push(')');
1683 }
1684 version
1685 }
1686
1687 fn rust_sha(&self) -> Option<&str> {
1689 self.rust_info().sha()
1690 }
1691
1692 fn release_num(&self, package: &str) -> String {
1694 let toml_file_name = self.src.join(format!("src/tools/{package}/Cargo.toml"));
1695 let toml = t!(fs::read_to_string(toml_file_name));
1696 for line in toml.lines() {
1697 if let Some(stripped) =
1698 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix('"'))
1699 {
1700 return stripped.to_owned();
1701 }
1702 }
1703
1704 panic!("failed to find version in {package}'s Cargo.toml")
1705 }
1706
1707 fn unstable_features(&self) -> bool {
1710 !matches!(&self.config.channel[..], "stable" | "beta")
1711 }
1712
1713 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1717 let mut ret = Vec::new();
1718 let mut list = vec![root.to_owned()];
1719 let mut visited = HashSet::new();
1720 while let Some(krate) = list.pop() {
1721 let krate = self
1722 .crates
1723 .get(&krate)
1724 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1725 ret.push(krate);
1726 for dep in &krate.deps {
1727 if !self.crates.contains_key(dep) {
1728 continue;
1730 }
1731 if visited.insert(dep)
1737 && (dep != "profiler_builtins"
1738 || target
1739 .map(|t| self.config.profiler_enabled(t))
1740 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1741 && (dep != "rustc_codegen_llvm"
1742 || self.config.hosts.iter().any(|host| self.config.llvm_enabled(*host)))
1743 {
1744 list.push(dep.clone());
1745 }
1746 }
1747 }
1748 ret.sort_unstable_by_key(|krate| krate.name.clone()); ret
1750 }
1751
1752 fn read_stamp_file(&self, stamp: &BuildStamp) -> Vec<(PathBuf, DependencyType)> {
1753 if self.config.dry_run() {
1754 return Vec::new();
1755 }
1756
1757 if !stamp.path().exists() {
1758 eprintln!(
1759 "ERROR: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1760 stamp.path().display()
1761 );
1762 crate::exit!(1);
1763 }
1764
1765 let mut paths = Vec::new();
1766 let contents = t!(fs::read(stamp.path()), stamp.path());
1767 for part in contents.split(|b| *b == 0) {
1770 if part.is_empty() {
1771 continue;
1772 }
1773 let dependency_type = match part[0] as char {
1774 'h' => DependencyType::Host,
1775 's' => DependencyType::TargetSelfContained,
1776 't' => DependencyType::Target,
1777 _ => unreachable!(),
1778 };
1779 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1780 paths.push((path, dependency_type));
1781 }
1782 paths
1783 }
1784
1785 #[track_caller]
1790 pub fn resolve_symlink_and_copy(&self, src: &Path, dst: &Path) {
1791 self.copy_link_internal(src, dst, true);
1792 }
1793
1794 #[track_caller]
1799 pub fn copy_link(&self, src: &Path, dst: &Path, file_type: FileType) {
1800 self.copy_link_internal(src, dst, false);
1801
1802 if file_type.could_have_split_debuginfo()
1803 && let Some(dbg_file) = split_debuginfo(src)
1804 {
1805 self.copy_link_internal(
1806 &dbg_file,
1807 &dst.with_extension(dbg_file.extension().unwrap()),
1808 false,
1809 );
1810 }
1811 }
1812
1813 #[track_caller]
1814 fn copy_link_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1815 if self.config.dry_run() {
1816 return;
1817 }
1818 self.verbose_than(1, || println!("Copy/Link {src:?} to {dst:?}"));
1819 if src == dst {
1820 return;
1821 }
1822
1823 #[cfg(feature = "tracing")]
1824 let _span = trace_io!("file-copy-link", ?src, ?dst);
1825
1826 if let Err(e) = fs::remove_file(dst)
1827 && cfg!(windows)
1828 && e.kind() != io::ErrorKind::NotFound
1829 {
1830 let now = t!(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH));
1833 let _ = fs::rename(dst, format!("{}-{}", dst.display(), now.as_nanos()));
1834 }
1835 let mut metadata = t!(src.symlink_metadata(), format!("src = {}", src.display()));
1836 let mut src = src.to_path_buf();
1837 if metadata.file_type().is_symlink() {
1838 if dereference_symlinks {
1839 src = t!(fs::canonicalize(src));
1840 metadata = t!(fs::metadata(&src), format!("target = {}", src.display()));
1841 } else {
1842 let link = t!(fs::read_link(src));
1843 t!(self.symlink_file(link, dst));
1844 return;
1845 }
1846 }
1847 if let Ok(()) = fs::hard_link(&src, dst) {
1848 } else {
1851 if let Err(e) = fs::copy(&src, dst) {
1852 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1853 }
1854 t!(fs::set_permissions(dst, metadata.permissions()));
1855
1856 let file_times = fs::FileTimes::new()
1859 .set_accessed(t!(metadata.accessed()))
1860 .set_modified(t!(metadata.modified()));
1861 t!(set_file_times(dst, file_times));
1862 }
1863 }
1864
1865 #[track_caller]
1869 pub fn cp_link_r(&self, src: &Path, dst: &Path) {
1870 if self.config.dry_run() {
1871 return;
1872 }
1873 for f in self.read_dir(src) {
1874 let path = f.path();
1875 let name = path.file_name().unwrap();
1876 let dst = dst.join(name);
1877 if t!(f.file_type()).is_dir() {
1878 t!(fs::create_dir_all(&dst));
1879 self.cp_link_r(&path, &dst);
1880 } else {
1881 self.copy_link(&path, &dst, FileType::Regular);
1882 }
1883 }
1884 }
1885
1886 #[track_caller]
1892 pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1893 self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1895 }
1896
1897 #[track_caller]
1899 fn cp_link_filtered_recurse(
1900 &self,
1901 src: &Path,
1902 dst: &Path,
1903 relative: &Path,
1904 filter: &dyn Fn(&Path) -> bool,
1905 ) {
1906 for f in self.read_dir(src) {
1907 let path = f.path();
1908 let name = path.file_name().unwrap();
1909 let dst = dst.join(name);
1910 let relative = relative.join(name);
1911 if filter(&relative) {
1913 if t!(f.file_type()).is_dir() {
1914 let _ = fs::remove_dir_all(&dst);
1915 self.create_dir(&dst);
1916 self.cp_link_filtered_recurse(&path, &dst, &relative, filter);
1917 } else {
1918 self.copy_link(&path, &dst, FileType::Regular);
1919 }
1920 }
1921 }
1922 }
1923
1924 fn copy_link_to_folder(&self, src: &Path, dest_folder: &Path) {
1925 let file_name = src.file_name().unwrap();
1926 let dest = dest_folder.join(file_name);
1927 self.copy_link(src, &dest, FileType::Regular);
1928 }
1929
1930 fn install(&self, src: &Path, dstdir: &Path, file_type: FileType) {
1931 if self.config.dry_run() {
1932 return;
1933 }
1934 let dst = dstdir.join(src.file_name().unwrap());
1935 self.verbose_than(1, || println!("Install {src:?} to {dst:?}"));
1936 t!(fs::create_dir_all(dstdir));
1937 if !src.exists() {
1938 panic!("ERROR: File \"{}\" not found!", src.display());
1939 }
1940
1941 self.copy_link_internal(src, &dst, true);
1942 chmod(&dst, file_type.perms());
1943
1944 if file_type.could_have_split_debuginfo()
1946 && let Some(dbg_file) = split_debuginfo(src)
1947 {
1948 self.install(&dbg_file, dstdir, FileType::Regular);
1949 }
1950 }
1951
1952 fn read(&self, path: &Path) -> String {
1953 if self.config.dry_run() {
1954 return String::new();
1955 }
1956 t!(fs::read_to_string(path))
1957 }
1958
1959 #[track_caller]
1960 fn create_dir(&self, dir: &Path) {
1961 if self.config.dry_run() {
1962 return;
1963 }
1964
1965 #[cfg(feature = "tracing")]
1966 let _span = trace_io!("dir-create", ?dir);
1967
1968 t!(fs::create_dir_all(dir))
1969 }
1970
1971 fn remove_dir(&self, dir: &Path) {
1972 if self.config.dry_run() {
1973 return;
1974 }
1975
1976 #[cfg(feature = "tracing")]
1977 let _span = trace_io!("dir-remove", ?dir);
1978
1979 t!(fs::remove_dir_all(dir))
1980 }
1981
1982 fn clear_dir(&self, dir: &Path) {
1985 if self.config.dry_run() {
1986 return;
1987 }
1988
1989 #[cfg(feature = "tracing")]
1990 let _span = trace_io!("dir-clear", ?dir);
1991
1992 let _ = std::fs::remove_dir_all(dir);
1993 self.create_dir(dir);
1994 }
1995
1996 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1997 let iter = match fs::read_dir(dir) {
1998 Ok(v) => v,
1999 Err(_) if self.config.dry_run() => return vec![].into_iter(),
2000 Err(err) => panic!("could not read dir {dir:?}: {err:?}"),
2001 };
2002 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
2003 }
2004
2005 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
2006 #[cfg(unix)]
2007 use std::os::unix::fs::symlink as symlink_file;
2008 #[cfg(windows)]
2009 use std::os::windows::fs::symlink_file;
2010 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
2011 }
2012
2013 fn ninja(&self) -> bool {
2016 let mut cmd_finder = crate::core::sanity::Finder::new();
2017
2018 if self.config.ninja_in_file {
2019 if cmd_finder.maybe_have("ninja-build").is_none()
2022 && cmd_finder.maybe_have("ninja").is_none()
2023 {
2024 eprintln!(
2025 "
2026Couldn't find required command: ninja (or ninja-build)
2027
2028You should install ninja as described at
2029<https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
2030or set `ninja = false` in the `[llvm]` section of `bootstrap.toml`.
2031Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
2032to download LLVM rather than building it.
2033"
2034 );
2035 exit!(1);
2036 }
2037 }
2038
2039 if !self.config.ninja_in_file
2047 && self.config.host_target.is_msvc()
2048 && cmd_finder.maybe_have("ninja").is_some()
2049 {
2050 return true;
2051 }
2052
2053 self.config.ninja_in_file
2054 }
2055
2056 pub fn colored_stdout<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2057 self.colored_stream_inner(StandardStream::stdout, self.config.stdout_is_tty, f)
2058 }
2059
2060 pub fn colored_stderr<R, F: FnOnce(&mut dyn WriteColor) -> R>(&self, f: F) -> R {
2061 self.colored_stream_inner(StandardStream::stderr, self.config.stderr_is_tty, f)
2062 }
2063
2064 fn colored_stream_inner<R, F, C>(&self, constructor: C, is_tty: bool, f: F) -> R
2065 where
2066 C: Fn(ColorChoice) -> StandardStream,
2067 F: FnOnce(&mut dyn WriteColor) -> R,
2068 {
2069 let choice = match self.config.color {
2070 flags::Color::Always => ColorChoice::Always,
2071 flags::Color::Never => ColorChoice::Never,
2072 flags::Color::Auto if !is_tty => ColorChoice::Never,
2073 flags::Color::Auto => ColorChoice::Auto,
2074 };
2075 let mut stream = constructor(choice);
2076 let result = f(&mut stream);
2077 stream.reset().unwrap();
2078 result
2079 }
2080
2081 pub fn exec_ctx(&self) -> &ExecutionContext {
2082 &self.config.exec_ctx
2083 }
2084
2085 pub fn report_summary(&self, path: &Path, start_time: Instant) {
2086 self.config.exec_ctx.profiler().report_summary(path, start_time);
2087 }
2088
2089 #[cfg(feature = "tracing")]
2090 pub fn report_step_graph(self, directory: &Path) {
2091 self.step_graph.into_inner().store_to_dot_files(directory);
2092 }
2093}
2094
2095impl AsRef<ExecutionContext> for Build {
2096 fn as_ref(&self) -> &ExecutionContext {
2097 &self.config.exec_ctx
2098 }
2099}
2100
2101#[cfg(unix)]
2102fn chmod(path: &Path, perms: u32) {
2103 use std::os::unix::fs::*;
2104 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
2105}
2106#[cfg(windows)]
2107fn chmod(_path: &Path, _perms: u32) {}
2108
2109impl Compiler {
2110 pub fn new(stage: u32, host: TargetSelection) -> Self {
2111 Self { stage, host, forced_compiler: false }
2112 }
2113
2114 pub fn forced_compiler(&mut self, forced_compiler: bool) {
2115 self.forced_compiler = forced_compiler;
2116 }
2117
2118 pub fn is_snapshot(&self, build: &Build) -> bool {
2120 self.stage == 0 && self.host == build.host_target
2121 }
2122
2123 pub fn is_forced_compiler(&self) -> bool {
2125 self.forced_compiler
2126 }
2127}
2128
2129fn envify(s: &str) -> String {
2130 s.chars()
2131 .map(|c| match c {
2132 '-' => '_',
2133 c => c,
2134 })
2135 .flat_map(|c| c.to_uppercase())
2136 .collect()
2137}
2138
2139pub fn prepare_behaviour_dump_dir(build: &Build) {
2141 static INITIALIZED: OnceLock<bool> = OnceLock::new();
2142
2143 let dump_path = build.out.join("bootstrap-shims-dump");
2144
2145 let initialized = INITIALIZED.get().unwrap_or(&false);
2146 if !initialized {
2147 if dump_path.exists() {
2149 t!(fs::remove_dir_all(&dump_path));
2150 }
2151
2152 t!(fs::create_dir_all(&dump_path));
2153
2154 t!(INITIALIZED.set(true));
2155 }
2156}