bootstrap/
lib.rs

1//! Implementation of bootstrap, the Rust build system.
2//!
3//! This module, and its descendants, are the implementation of the Rust build
4//! system. Most of this build system is backed by Cargo but the outer layer
5//! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6//! builds, building artifacts like LLVM, etc. The goals of bootstrap are:
7//!
8//! * To be an easily understandable, easily extensible, and maintainable build
9//!   system.
10//! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11//!   crates.io and Cargo.
12//! * A standard interface to build across all platforms, including MSVC
13//!
14//! ## Further information
15//!
16//! More documentation can be found in each respective module below, and you can
17//! also check out the `src/bootstrap/README.md` file for more information.
18#![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",      // used to generate coverage report
64    "llvm-nm",       // used to inspect binaries; it shows symbol names, their sizes and visibility
65    "llvm-objcopy",  // used to transform ELFs into binary format which flashing tools consume
66    "llvm-objdump",  // used to disassemble programs
67    "llvm-profdata", // used to inspect and merge files generated by profiles
68    "llvm-readobj",  // used to get information from ELFs/objects that the other tools don't provide
69    "llvm-size",     // used to prints the size of the linker sections of a program
70    "llvm-strip",    // used to discard symbols from binary files to reduce their size
71    "llvm-ar",       // used for creating and modifying archive files
72    "llvm-as",       // used to convert LLVM assembly to LLVM bitcode
73    "llvm-dis",      // used to disassemble LLVM bitcode
74    "llvm-link",     // Used to link LLVM bitcode
75    "llc",           // used to compile LLVM bytecode
76    "opt",           // used to optimize LLVM bytecode
77];
78
79/// LLD file names for all flavors.
80const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
81
82/// Extra `--check-cfg` to add when building the compiler or tools
83/// (Mode restriction, config name, config values (if any))
84#[expect(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
85const 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    // Any library specific cfgs like `target_os`, `target_arch` should be put in
96    // priority the `[lints.rust.unexpected_cfgs.check-cfg]` table
97    // in the appropriate `library/{std,alloc,core}/Cargo.toml`
98];
99
100/// A structure representing a Rust compiler.
101///
102/// Each compiler has a `stage` that it is associated with and a `host` that
103/// corresponds to the platform the compiler runs on. This structure is used as
104/// a parameter to many methods below.
105#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
106pub struct Compiler {
107    stage: u32,
108    host: TargetSelection,
109    /// Indicates whether the compiler was forced to use a specific stage.
110    /// This field is ignored in `Hash` and `PartialEq` implementations as only the `stage`
111    /// and `host` fields are relevant for those.
112    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/// Represents a codegen backend.
129#[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    /// Name of the codegen backend, as identified in the `compiler` directory
140    /// (`rustc_codegen_<name>`).
141    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    /// Name of the codegen backend's crate, e.g. `rustc_codegen_cranelift`.
151    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    /// Run normal tests and doc tests (default).
185    Yes,
186    /// Do not run any doc tests.
187    No,
188    /// Only run doc tests.
189    Only,
190}
191
192pub enum GitRepo {
193    Rustc,
194    Llvm,
195}
196
197/// Global configuration for the build system.
198///
199/// This structure transitively contains all configuration for the build system.
200/// All filesystem-encoded configuration is in `config`, all flags are in
201/// `flags`, and then parsed or probed information is listed in the keys below.
202///
203/// This structure is a parameter of almost all methods in the build system,
204/// although most functions are implemented as free functions rather than
205/// methods specifically on this structure itself (to make it easier to
206/// organize).
207pub struct Build {
208    /// User-specified configuration from `bootstrap.toml`.
209    config: Config,
210
211    // Version information
212    version: String,
213
214    // Properties derived from the above configuration
215    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    /// Build triple for the pre-compiled snapshot compiler.
232    host_target: TargetSelection,
233    /// Which triples to produce a compiler toolchain for.
234    hosts: Vec<TargetSelection>,
235    /// Which triples to build libraries (core/alloc/std/test/proc_macro) for.
236    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    // Runtime state filled in later on
246    // C/C++ compilers and archiver for all targets
247    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    // Miscellaneous
254    // allow bidirectional lookups: both name -> path and path -> name
255    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/// When building Rust various objects are handled differently.
282#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
283pub enum DependencyType {
284    /// Libraries originating from proc-macros.
285    Host,
286    /// Typical Rust libraries.
287    Target,
288    /// Non Rust libraries and objects shipped to ease usage of certain targets.
289    TargetSelfContained,
290}
291
292/// The various "modes" of invoking Cargo.
293///
294/// These entries currently correspond to the various output directories of the
295/// build system, with each mod generating output in a different directory.
296#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
297pub enum Mode {
298    /// Build the standard library, placing output in the "stageN-std" directory.
299    Std,
300
301    /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
302    Rustc,
303
304    /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
305    Codegen,
306
307    /// Build a tool, placing output in the "bootstrap-tools"
308    /// directory. This is for miscellaneous sets of tools that extend
309    /// bootstrap.
310    ///
311    /// These tools are intended to be only executed on the host system that
312    /// invokes bootstrap, and they thus cannot be cross-compiled.
313    ///
314    /// They are always built using the stage0 compiler, and they
315    /// can be compiled with stable Rust.
316    ///
317    /// These tools also essentially do not participate in staging.
318    ToolBootstrap,
319
320    /// Build a cross-compilable helper tool. These tools do not depend on unstable features or
321    /// compiler internals, but they might be cross-compilable (so we cannot build them using the
322    /// stage0 compiler, unlike `ToolBootstrap`).
323    ///
324    /// Some of these tools are also shipped in our `dist` archives.
325    /// While we could compile them using the stage0 compiler when not cross-compiling, we instead
326    /// use the in-tree compiler (and std) to build them, so that we can ship e.g. std security
327    /// fixes and avoid depending fully on stage0 for the artifacts that we ship.
328    ///
329    /// This mode is used e.g. for linkers and linker tools invoked by rustc on its host target.
330    ToolTarget,
331
332    /// Build a tool which uses the locally built std, placing output in the
333    /// "stageN-tools" directory. Its usage is quite rare, mainly used by
334    /// compiletest which needs libtest.
335    ToolStd,
336
337    /// Build a tool which uses the locally built rustc and the target std,
338    /// placing the output in the "stageN-tools" directory. This is used for
339    /// anything that needs a fully functional rustc, such as rustdoc, clippy,
340    /// cargo, rustfmt, miri, etc.
341    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
364/// When `rust.rust_remap_debuginfo` is requested, the compiler needs to know how to
365/// opportunistically unremap compiler vs non-compiler sources. We use two schemes,
366/// [`RemapScheme::Compiler`] and [`RemapScheme::NonCompiler`].
367pub enum RemapScheme {
368    /// The [`RemapScheme::Compiler`] scheme will remap to `/rustc-dev/{hash}`.
369    Compiler,
370    /// The [`RemapScheme::NonCompiler`] scheme will remap to `/rustc/{hash}`.
371    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    /// An executable binary file (like a `.exe`).
383    Executable,
384    /// A native, binary library file (like a `.so`, `.dll`, `.a`, `.lib` or `.o`).
385    NativeLibrary,
386    /// An executable (non-binary) script file (like a `.py` or `.sh`).
387    Script,
388    /// Any other regular file that is non-executable.
389    Regular,
390}
391
392impl FileType {
393    /// Get Unix permissions appropriate for this file type.
394    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
429/// An alternative way of specifying what target and stage is involved in some bootstrap activity.
430/// Ideally using a `Compiler` directly should be preferred.
431struct 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    /// Creates a new set of build configuration from the `flags` on the command
450    /// line and the filesystem `config`.
451    ///
452    /// By default all build output will be placed in the current directory.
453    pub fn new(mut config: Config) -> Build {
454        let src = config.src.clone();
455        let out = config.out.clone();
456
457        #[cfg(unix)]
458        // keep this consistent with the equivalent check in x.py:
459        // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
460        let is_sudo = match env::var_os("SUDO_USER") {
461            Some(_sudo_user) => {
462                // SAFETY: getuid() system call is always successful and no return value is reserved
463                // to indicate an error.
464                //
465                // For more context, see https://man7.org/linux/man-pages/man2/geteuid.2.html
466                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            // On tests, bootstrap uses the shim rustc, not the one from the stage0 toolchain.
500            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        // Since bootstrap is hardlink to deps/bootstrap-*, Solaris can sometimes give
527        // path with deps/ which is bad and needs to be avoided.
528        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            // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
533            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        // If local-rust is the same major.minor as the current version, then force a
593        // local-rebuild
594        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        // When running `setup`, the profile is about to change, so any requirements we have now may
613        // be different on the next invocation. Don't check for them until the next time x.py is
614        // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
615        //
616        // Similarly, for `setup` we don't actually need submodules or cargo metadata.
617        if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
618            build.verbose(|| println!("running sanity check"));
619            crate::core::sanity::check(&mut build);
620
621            // Make sure we update these before gathering metadata so we don't get an error about missing
622            // Cargo.toml files.
623            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            // Now, update all existing submodules.
634            build.update_existing_submodules();
635
636            build.verbose(|| println!("learning about cargo"));
637            crate::core::metadata::build(&mut build);
638        }
639
640        // Create symbolic link to use host sysroot from a consistent path (e.g., in the rust-analyzer config file).
641        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            // Left over from a previous build; overwrite it.
646            // This matters if `build.build` has changed between invocations.
647            #[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    /// Updates a submodule, and exits with a failure if submodule management
661    /// is disabled and the submodule does not exist.
662    ///
663    /// The given submodule name should be its path relative to the root of
664    /// the main repository.
665    ///
666    /// The given `err_hint` will be shown to the user if the submodule is not
667    /// checked out and submodule management is disabled.
668    #[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        // When testing bootstrap itself, it is much faster to ignore
683        // submodules. Almost all Steps work fine without their submodules.
684        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    /// If any submodule has been initialized already, sync it unconditionally.
707    /// This avoids contributors checking in a submodule change by accident.
708    fn update_existing_submodules(&self) {
709        // Avoid running git when there isn't a git checkout, or the user has
710        // explicitly disabled submodules in `bootstrap.toml`.
711        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            // Look for `submodule.$name.path = $path`
722            // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
723            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    /// Updates the given submodule only if it's initialized already; nothing happens otherwise.
734    pub fn update_existing_submodule(config: &Config, submodule: &str) {
735        // Avoid running git when there isn't a git checkout.
736        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    /// Executes the entire build, as configured by the flags and configuration.
746    #[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        // Handle hard-coded subcommands.
754        {
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            // We first do a dry-run. This is a sanity-check to ensure that
785            // steps don't do anything expensive in the dry-run.
786            {
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            // Actual run.
796            {
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        // Check for postponed failures from `test --no-fail-fast`.
816        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    /// Gets the space-separated set of activated features for the standard library.
827    /// This can be configured with the `std-features` key in bootstrap.toml.
828    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 zkvm target, generate memcpy, etc.
847        if target.contains("zkvm") {
848            features.insert("compiler-builtins-mem");
849        }
850
851        features.into_iter().collect::<Vec<_>>().join(" ")
852    }
853
854    /// Gets the space-separated set of activated features for the compiler.
855    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        // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
872        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 debug logging is on, then we want the default for tracing:
880        // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
881        // which is everything (including debug/trace/etc.)
882        // if its unset, if debug_assertions is on, then debug_logging will also be on
883        // as well as tracing *ignoring* this feature when debug_assertions is on
884        if !self.config.rust_debug_logging && check("max_level_info") {
885            features.push("max_level_info");
886        }
887
888        features.join(" ")
889    }
890
891    /// Component directory that Cargo will produce output into (e.g.
892    /// release/debug)
893    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    /// Returns the root directory for all output generated in a particular
907    /// stage when being built with a particular build compiler.
908    ///
909    /// The mode indicates what the root directory is for.
910    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            // Std is special, stage N std is built with stage N rustc
922            Mode::Std => (Some(build_compiler.stage), "std"),
923            // The rest of things are built with stage N-1 rustc
924            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 we're not cross-compiling (the common case), share the target directory with
930                // bootstrap tools to reuse the build cache.
931                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    /// Returns the root output directory for all Cargo output in a given stage,
948    /// running a particular compiler, whether or not we're building the
949    /// standard library, and targeting the specified architecture.
950    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    /// Root output directory of LLVM for `target`
955    ///
956    /// Note that if LLVM is configured externally then the directory returned
957    /// will likely be empty.
958    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    /// Output directory for all documentation for a target
979    fn doc_out(&self, target: TargetSelection) -> PathBuf {
980        self.out.join(target).join("doc")
981    }
982
983    /// Output directory for all JSON-formatted documentation for a target
984    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    /// Output directory for all documentation for a target
993    fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
994        self.out.join(target).join("compiler-doc")
995    }
996
997    /// Output directory for some generated md crate documentation for a target (temporary)
998    fn md_doc_out(&self, target: TargetSelection) -> PathBuf {
999        self.out.join(target).join("md-doc")
1000    }
1001
1002    /// Path to the vendored Rust crates.
1003    fn vendored_crates_path(&self) -> Option<PathBuf> {
1004        if self.config.vendor { Some(self.src.join(VENDOR_DIR)) } else { None }
1005    }
1006
1007    /// Returns the path to `FileCheck` binary for the specified target
1008    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                // On Fedora the system LLVM installs FileCheck in the
1019                // llvm subdirectory of the libdir.
1020                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                    // Return the most normal file name, even though
1027                    // it doesn't exist, so that any error message
1028                    // refers to that.
1029                    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    /// Directory for libraries built from C/C++ code and shared between stages.
1052    fn native_dir(&self, target: TargetSelection) -> PathBuf {
1053        self.out.join(target).join("native")
1054    }
1055
1056    /// Root output directory for rust_test_helpers library compiled for
1057    /// `target`
1058    fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
1059        self.native_dir(target).join("rust-test-helpers")
1060    }
1061
1062    /// Adds the `RUST_TEST_THREADS` env var if necessary
1063    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    /// Returns the libdir of the snapshot compiler.
1070    fn rustc_snapshot_libdir(&self) -> PathBuf {
1071        self.rustc_snapshot_sysroot().join(libdir(self.config.host_target))
1072    }
1073
1074    /// Returns the sysroot of the snapshot compiler.
1075    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    /// Check if verbosity is greater than the `level`
1090    pub fn is_verbose_than(&self, level: usize) -> bool {
1091        self.verbosity > level
1092    }
1093
1094    /// Runs a function if verbosity is greater than `level`.
1095    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    /// Return a `Group` guard for a [`Step`] that:
1111    /// - Performs `action`
1112    ///   - If the action is `Kind::Test`, use [`Build::msg_test`] instead.
1113    /// - On `what`
1114    ///   - Where `what` possibly corresponds to a `mode`
1115    /// - `action` is performed with/on the given compiler (`target_and_stage`).
1116    ///   - Since for some steps it is not possible to pass a single compiler here, it is also
1117    ///     possible to pass the host and stage explicitly.
1118    /// - With a given `target`.
1119    ///
1120    /// [`Step`]: crate::core::builder::Step
1121    #[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            // Std has the same stage as the compiler that builds it
1140            Some(Mode::Std) => target_and_stage.stage,
1141            // Other things have stage corresponding to their build compiler + 1
1142            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    /// Return a `Group` guard for a [`Step`] that tests `what` with the given `stage` and `target`.
1174    /// Use this instead of [`Build::msg`] for test steps, because for them it is not always clear
1175    /// what exactly is a build compiler.
1176    ///
1177    /// [`Step`]: crate::core::builder::Step
1178    #[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    /// Return a `Group` guard for a [`Step`] that is only built once and isn't affected by `--stage`.
1192    ///
1193    /// [`Step`]: crate::core::builder::Step
1194    #[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    /// Returns the number of parallel jobs that have been configured for this
1216    /// build.
1217    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                        // For compiler sources, remap via `/rustc-dev/{sha}` to allow
1235                        // distinguishing between compiler sources vs library sources, since
1236                        // `rustc-dev` dist component places them under
1237                        // `$sysroot/lib/rustlib/rustc-src/rust` as opposed to `rust-src`'s
1238                        // `$sysroot/lib/rustlib/src/rust`.
1239                        //
1240                        // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s
1241                        // `try_to_translate_virtual_to_real`.
1242                        Some(format!("/rustc-dev/{sha}"))
1243                    }
1244                    RemapScheme::NonCompiler => {
1245                        // For non-compiler sources, use `/rustc/{sha}` remapping scheme.
1246                        Some(format!("/rustc/{sha}"))
1247                    }
1248                }
1249            }
1250            GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1251        }
1252    }
1253
1254    /// Returns the path to the C compiler for the target specified.
1255    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    /// Returns the internal `cc::Tool` for the C compiler.
1263    fn cc_tool(&self, target: TargetSelection) -> Tool {
1264        self.cc[&target].clone()
1265    }
1266
1267    /// Returns the internal `cc::Tool` for the C++ compiler.
1268    fn cxx_tool(&self, target: TargetSelection) -> Tool {
1269        self.cxx[&target].clone()
1270    }
1271
1272    /// Returns C flags that `cc-rs` thinks should be enabled for the
1273    /// specified target by default.
1274    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        // Filter out -O and /O (the optimization flags) that we picked up
1284        // from cc-rs, that's up to the caller to figure out.
1285        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    /// Returns extra C flags that `cc-rs` doesn't handle.
1293    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 we're compiling C++ on macOS then we add a flag indicating that
1302        // we want libc++ (more filled out than libstdc++), ensuring that
1303        // LLVM/etc are all properly compiled.
1304        if matches!(c, CLang::Cxx) && target.contains("apple-darwin") {
1305            base.push("-stdlib=libc++".into());
1306        }
1307
1308        // Work around an apparently bad MinGW / GCC optimization,
1309        // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1310        // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1311        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    /// Returns the path to the `ar` archive utility for the target specified.
1329    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    /// Returns the path to the `ranlib` utility for the target specified.
1337    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    /// Returns the path to the C++ compiler for the target specified.
1345    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    /// Returns the path to the linker for the given target if it needs to be overridden.
1356    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            // need to use CXX compiler as linker to resolve the exception functions
1365            // that are only existed in CXX libraries
1366            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    // Is LLD configured directly through `-Clinker`?
1387    // Only MSVC targets use LLD directly at the moment.
1388    fn is_lld_direct_linker(&self, target: TargetSelection) -> bool {
1389        target.is_msvc()
1390    }
1391
1392    /// Returns if this target should statically link the C runtime, if specified
1393    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    /// Returns the "musl root" for this `target`, if defined.
1402    ///
1403    /// If this is a native target (host is also musl) and no musl-root is given,
1404    /// it falls back to the system toolchain in /usr.
1405    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    /// Returns the "musl libdir" for this `target`.
1422    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    /// Returns the `lib` directory for the WASI target specified, if
1431    /// configured.
1432    ///
1433    /// This first consults `wasi-root` as configured in per-target
1434    /// configuration, and failing that it assumes that `$WASI_SDK_PATH` is
1435    /// set in the environment, and failing that `None` is returned.
1436    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    /// Returns `true` if this is a no-std `target`, if defined
1451    fn no_std(&self, target: TargetSelection) -> Option<bool> {
1452        self.config.target_config.get(&target).map(|t| t.no_std)
1453    }
1454
1455    /// Returns `true` if the target will be tested using the `remote-test-client`
1456    /// and `remote-test-server` binaries.
1457    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    /// Returns an optional "runner" to pass to `compiletest` when executing
1464    /// test binaries.
1465    ///
1466    /// An example of this would be a WebAssembly runtime when testing the wasm
1467    /// targets.
1468    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    /// When a `runner` configuration is not provided and a WASI-looking target
1483    /// is being tested this is consulted to prove the environment to see if
1484    /// there's a runtime already lying around that seems reasonable to use.
1485    fn default_wasi_runner(&self, target: TargetSelection) -> Option<String> {
1486        let mut finder = crate::core::sanity::Finder::new();
1487
1488        // Look for Wasmtime, and for its default options be sure to disable
1489        // its caching system since we're executing quite a lot of tests and
1490        // ideally shouldn't pollute the cache too much.
1491        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            // Make sure that tests have access to RUSTC_BOOTSTRAP. This (for example) is
1496            // required for libtest to work on beta/stable channels.
1497            //
1498            // NB: with Wasmtime 20 this can change to `-S inherit-env` to
1499            // inherit the entire environment rather than just this single
1500            // environment variable.
1501            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    /// Returns whether the specified tool is configured as part of this build.
1514    ///
1515    /// This requires that both the `extended` key is set and the `tools` key is
1516    /// either unset or specifically contains the specified tool.
1517    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    /// Returns the root of the "rootfs" image that this target will be using,
1528    /// if one was configured.
1529    ///
1530    /// If `Some` is returned then that means that tests for this target are
1531    /// emulated with QEMU and binaries will need to be shipped to the emulator.
1532    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    /// Path to the python interpreter to use
1537    fn python(&self) -> &Path {
1538        if self.config.host_target.ends_with("apple-darwin") {
1539            // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1540            // LLDB plugin's compiled module which only works with the system python
1541            // (namely not Homebrew-installed python)
1542            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    /// Temporary directory that extended error information is emitted to.
1552    fn extended_error_dir(&self) -> PathBuf {
1553        self.out.join("tmp/extended-error-metadata")
1554    }
1555
1556    /// Tests whether the `compiler` compiling for `target` should be forced to
1557    /// use a stage1 compiler instead.
1558    ///
1559    /// Currently, by default, the build system does not perform a "full
1560    /// bootstrap" by default where we compile the compiler three times.
1561    /// Instead, we compile the compiler two times. The final stage (stage2)
1562    /// just copies the libraries from the previous stage, which is what this
1563    /// method detects.
1564    ///
1565    /// Here we return `true` if:
1566    ///
1567    /// * The build isn't performing a full bootstrap
1568    /// * The `compiler` is in the final stage, 2
1569    /// * We're not cross-compiling, so the artifacts are already available in
1570    ///   stage1
1571    ///
1572    /// When all of these conditions are met the build will lift artifacts from
1573    /// the previous stage forward.
1574    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    /// Checks whether the `compiler` compiling for `target` should be forced to
1582    /// use a stage2 compiler instead.
1583    ///
1584    /// When we download the pre-compiled version of rustc and compiler stage is >= 2,
1585    /// it should be forced to use a stage2 compiler.
1586    fn force_use_stage2(&self, stage: u32) -> bool {
1587        self.config.download_rustc() && stage >= 2
1588    }
1589
1590    /// Given `num` in the form "a.b.c" return a "release string" which
1591    /// describes the release version number.
1592    ///
1593    /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1594    /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1595    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        // First check if there is a version file available.
1622        // If available, we read the beta revision from that file.
1623        // This only happens when building from a source tarball when Git should not be used.
1624        let count = extract_beta_rev_from_file(self.src.join("version")).unwrap_or_else(|| {
1625            // Figure out how many merge commits happened since we branched off master.
1626            // That's our beta number!
1627            // (Note that we use a `..` range, not the `...` symmetric difference.)
1628            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    /// Returns the value of `release` above for Rust itself.
1646    fn rust_release(&self) -> String {
1647        self.release(&self.version)
1648    }
1649
1650    /// Returns the "package version" for a component given the `num` release
1651    /// number.
1652    ///
1653    /// The package version is typically what shows up in the names of tarballs.
1654    /// For channels like beta/nightly it's just the channel name, otherwise
1655    /// it's the `num` provided.
1656    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    /// Returns the value of `package_vers` above for Rust itself.
1666    fn rust_package_vers(&self) -> String {
1667        self.package_vers(&self.version)
1668    }
1669
1670    /// Returns the `version` string associated with this compiler for Rust
1671    /// itself.
1672    ///
1673    /// Note that this is a descriptive string which includes the commit date,
1674    /// sha, version, etc.
1675    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    /// Returns the full commit hash.
1688    fn rust_sha(&self) -> Option<&str> {
1689        self.rust_info().sha()
1690    }
1691
1692    /// Returns the `a.b.c` version that the given package is at.
1693    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    /// Returns `true` if unstable features should be enabled for the compiler
1708    /// we're building.
1709    fn unstable_features(&self) -> bool {
1710        !matches!(&self.config.channel[..], "stable" | "beta")
1711    }
1712
1713    /// Returns a Vec of all the dependencies of the given root crate,
1714    /// including transitive dependencies and the root itself. Only includes
1715    /// "local" crates (those in the local source tree, not from a registry).
1716    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                    // Ignore non-workspace members.
1729                    continue;
1730                }
1731                // Don't include optional deps if their features are not
1732                // enabled. Ideally this would be computed from `cargo
1733                // metadata --features …`, but that is somewhat slow. In
1734                // the future, we may want to consider just filtering all
1735                // build and dev dependencies in metadata::build.
1736                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()); // reproducible order needed for tests
1749        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        // This is the method we use for extracting paths from the stamp file passed to us. See
1768        // run_cargo for more information (in compile.rs).
1769        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    /// Copies a file from `src` to `dst`.
1786    ///
1787    /// If `src` is a symlink, `src` will be resolved to the actual path
1788    /// and copied to `dst` instead of the symlink itself.
1789    #[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    /// Links a file from `src` to `dst`.
1795    /// Attempts to use hard links if possible, falling back to copying.
1796    /// You can neither rely on this being a copy nor it being a link,
1797    /// so do not write to dst.
1798    #[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            // workaround for https://github.com/rust-lang/rust/issues/127126
1831            // if removing the file fails, attempt to rename it instead.
1832            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            // Attempt to "easy copy" by creating a hard link (symlinks are privileged on windows),
1849            // but if that fails just fall back to a slow `copy` operation.
1850        } 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            // Restore file times because changing permissions on e.g. Linux using `chmod` can cause
1857            // file access time to change.
1858            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    /// Links the `src` directory recursively to `dst`. Both are assumed to exist
1866    /// when this function is called.
1867    /// Will attempt to use hard links if possible and fall back to copying.
1868    #[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    /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1887    /// when this function is called.
1888    /// Will attempt to use hard links if possible and fall back to copying.
1889    /// Unwanted files or directories can be skipped
1890    /// by returning `false` from the filter function.
1891    #[track_caller]
1892    pub fn cp_link_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1893        // Immediately recurse with an empty relative path
1894        self.cp_link_filtered_recurse(src, dst, Path::new(""), filter)
1895    }
1896
1897    // Inner function does the actual work
1898    #[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            // Only copy file or directory if the filter function returns true
1912            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 this file can have debuginfo, look for split debuginfo and install it too.
1945        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    /// Make sure that `dir` will be an empty existing directory after this function ends.
1983    /// If it existed before, it will be first deleted.
1984    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    /// Returns if config.ninja is enabled, and checks for ninja existence,
2014    /// exiting with a nicer error message if not.
2015    fn ninja(&self) -> bool {
2016        let mut cmd_finder = crate::core::sanity::Finder::new();
2017
2018        if self.config.ninja_in_file {
2019            // Some Linux distros rename `ninja` to `ninja-build`.
2020            // CMake can work with either binary name.
2021            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 ninja isn't enabled but we're building for MSVC then we try
2040        // doubly hard to enable it. It was realized in #43767 that the msbuild
2041        // CMake generator for MSVC doesn't respect configuration options like
2042        // disabling LLVM assertions, which can often be quite important!
2043        //
2044        // In these cases we automatically enable Ninja if we find it in the
2045        // environment.
2046        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    /// Returns `true` if this is a snapshot compiler for `build`'s configuration
2119    pub fn is_snapshot(&self, build: &Build) -> bool {
2120        self.stage == 0 && self.host == build.host_target
2121    }
2122
2123    /// Indicates whether the compiler was forced to use a specific stage.
2124    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
2139/// Ensures that the behavior dump directory is properly initialized.
2140pub 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        // clear old dumps
2148        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}