bootstrap/core/config/
config.rs

1//! This module defines the central `Config` struct, which aggregates all components
2//! of the bootstrap configuration into a single unit.
3//!
4//! It serves as the primary public interface for accessing the bootstrap configuration.
5//! The module coordinates the overall configuration parsing process using logic from `parsing.rs`
6//! and provides top-level methods such as `Config::parse()` for initialization, as well as
7//! utility methods for querying and manipulating the complete configuration state.
8//!
9//! Additionally, this module contains the core logic for parsing, validating, and inferring
10//! the final `Config` from various raw inputs.
11//!
12//! It manages the process of reading command-line arguments, environment variables,
13//! and the `bootstrap.toml` file—merging them, applying defaults, and performing
14//! cross-component validation. The main `parse_inner` function and its supporting
15//! helpers reside here, transforming raw `Toml` data into the structured `Config` type.
16
17use std::cell::Cell;
18use std::collections::{BTreeSet, HashMap, HashSet};
19use std::io::IsTerminal;
20use std::path::{Path, PathBuf, absolute};
21use std::str::FromStr;
22use std::sync::{Arc, Mutex};
23use std::{cmp, env, fs};
24
25use build_helper::ci::CiEnv;
26use build_helper::exit;
27use build_helper::git::{GitConfig, PathFreshness, check_path_modifications};
28use serde::Deserialize;
29#[cfg(feature = "tracing")]
30use tracing::{instrument, span};
31
32use crate::core::build_steps::llvm;
33use crate::core::build_steps::llvm::LLVM_INVALIDATION_PATHS;
34pub use crate::core::config::flags::Subcommand;
35use crate::core::config::flags::{Color, Flags};
36use crate::core::config::target_selection::TargetSelectionList;
37use crate::core::config::toml::TomlConfig;
38use crate::core::config::toml::build::{Build, Tool};
39use crate::core::config::toml::change_id::ChangeId;
40use crate::core::config::toml::rust::{
41    LldMode, RustOptimize, check_incompatible_options_for_ci_rustc,
42};
43use crate::core::config::toml::target::Target;
44use crate::core::config::{
45    DebuginfoLevel, DryRun, GccCiMode, LlvmLibunwind, Merge, ReplaceOpt, RustcLto, SplitDebuginfo,
46    StringOrBool, set, threads_from_config,
47};
48use crate::core::download::is_download_ci_available;
49use crate::utils::channel;
50use crate::utils::exec::command;
51use crate::utils::execution_context::ExecutionContext;
52use crate::utils::helpers::{exe, get_host_target};
53use crate::{GitInfo, OnceLock, TargetSelection, check_ci_llvm, helpers, t};
54
55/// Each path in this list is considered "allowed" in the `download-rustc="if-unchanged"` logic.
56/// This means they can be modified and changes to these paths should never trigger a compiler build
57/// when "if-unchanged" is set.
58///
59/// NOTE: Paths must have the ":!" prefix to tell git to ignore changes in those paths during
60/// the diff check.
61///
62/// WARNING: Be cautious when adding paths to this list. If a path that influences the compiler build
63/// is added here, it will cause bootstrap to skip necessary rebuilds, which may lead to risky results.
64/// For example, "src/bootstrap" should never be included in this list as it plays a crucial role in the
65/// final output/compiler, which can be significantly affected by changes made to the bootstrap sources.
66#[rustfmt::skip] // We don't want rustfmt to oneline this list
67pub const RUSTC_IF_UNCHANGED_ALLOWED_PATHS: &[&str] = &[
68    ":!library",
69    ":!src/tools",
70    ":!src/librustdoc",
71    ":!src/rustdoc-json-types",
72    ":!tests",
73    ":!triagebot.toml",
74];
75
76/// Global configuration for the entire build and/or bootstrap.
77///
78/// This structure is parsed from `bootstrap.toml`, and some of the fields are inferred from `git` or build-time parameters.
79///
80/// Note that this structure is not decoded directly into, but rather it is
81/// filled out from the decoded forms of the structs below. For documentation
82/// on each field, see the corresponding fields in
83/// `bootstrap.example.toml`.
84#[derive(Default, Clone)]
85pub struct Config {
86    pub change_id: Option<ChangeId>,
87    pub bypass_bootstrap_lock: bool,
88    pub ccache: Option<String>,
89    /// Call Build::ninja() instead of this.
90    pub ninja_in_file: bool,
91    pub verbose: usize,
92    pub submodules: Option<bool>,
93    pub compiler_docs: bool,
94    pub library_docs_private_items: bool,
95    pub docs_minification: bool,
96    pub docs: bool,
97    pub locked_deps: bool,
98    pub vendor: bool,
99    pub target_config: HashMap<TargetSelection, Target>,
100    pub full_bootstrap: bool,
101    pub bootstrap_cache_path: Option<PathBuf>,
102    pub extended: bool,
103    pub tools: Option<HashSet<String>>,
104    /// Specify build configuration specific for some tool, such as enabled features, see [Tool].
105    /// The key in the map is the name of the tool, and the value is tool-specific configuration.
106    pub tool: HashMap<String, Tool>,
107    pub sanitizers: bool,
108    pub profiler: bool,
109    pub omit_git_hash: bool,
110    pub skip: Vec<PathBuf>,
111    pub include_default_paths: bool,
112    pub rustc_error_format: Option<String>,
113    pub json_output: bool,
114    pub test_compare_mode: bool,
115    pub color: Color,
116    pub patch_binaries_for_nix: Option<bool>,
117    pub stage0_metadata: build_helper::stage0_parser::Stage0,
118    pub android_ndk: Option<PathBuf>,
119    /// Whether to use the `c` feature of the `compiler_builtins` crate.
120    pub optimized_compiler_builtins: bool,
121
122    pub stdout_is_tty: bool,
123    pub stderr_is_tty: bool,
124
125    pub on_fail: Option<String>,
126    pub explicit_stage_from_cli: bool,
127    pub explicit_stage_from_config: bool,
128    pub stage: u32,
129    pub keep_stage: Vec<u32>,
130    pub keep_stage_std: Vec<u32>,
131    pub src: PathBuf,
132    /// defaults to `bootstrap.toml`
133    pub config: Option<PathBuf>,
134    pub jobs: Option<u32>,
135    pub cmd: Subcommand,
136    pub incremental: bool,
137    pub dump_bootstrap_shims: bool,
138    /// Arguments appearing after `--` to be forwarded to tools,
139    /// e.g. `--fix-broken` or test arguments.
140    pub free_args: Vec<String>,
141
142    /// `None` if we shouldn't download CI compiler artifacts, or the commit to download if we should.
143    pub download_rustc_commit: Option<String>,
144
145    pub deny_warnings: bool,
146    pub backtrace_on_ice: bool,
147
148    // llvm codegen options
149    pub llvm_assertions: bool,
150    pub llvm_tests: bool,
151    pub llvm_enzyme: bool,
152    pub llvm_offload: bool,
153    pub llvm_plugins: bool,
154    pub llvm_optimize: bool,
155    pub llvm_thin_lto: bool,
156    pub llvm_release_debuginfo: bool,
157    pub llvm_static_stdcpp: bool,
158    pub llvm_libzstd: bool,
159    pub llvm_link_shared: Cell<Option<bool>>,
160    pub llvm_clang_cl: Option<String>,
161    pub llvm_targets: Option<String>,
162    pub llvm_experimental_targets: Option<String>,
163    pub llvm_link_jobs: Option<u32>,
164    pub llvm_version_suffix: Option<String>,
165    pub llvm_use_linker: Option<String>,
166    pub llvm_allow_old_toolchain: bool,
167    pub llvm_polly: bool,
168    pub llvm_clang: bool,
169    pub llvm_enable_warnings: bool,
170    pub llvm_from_ci: bool,
171    pub llvm_build_config: HashMap<String, String>,
172
173    pub lld_mode: LldMode,
174    pub lld_enabled: bool,
175    pub llvm_tools_enabled: bool,
176    pub llvm_bitcode_linker_enabled: bool,
177
178    pub llvm_cflags: Option<String>,
179    pub llvm_cxxflags: Option<String>,
180    pub llvm_ldflags: Option<String>,
181    pub llvm_use_libcxx: bool,
182
183    // gcc codegen options
184    pub gcc_ci_mode: GccCiMode,
185
186    // rust codegen options
187    pub rust_optimize: RustOptimize,
188    pub rust_codegen_units: Option<u32>,
189    pub rust_codegen_units_std: Option<u32>,
190
191    pub rustc_debug_assertions: bool,
192    pub std_debug_assertions: bool,
193    pub tools_debug_assertions: bool,
194
195    pub rust_overflow_checks: bool,
196    pub rust_overflow_checks_std: bool,
197    pub rust_debug_logging: bool,
198    pub rust_debuginfo_level_rustc: DebuginfoLevel,
199    pub rust_debuginfo_level_std: DebuginfoLevel,
200    pub rust_debuginfo_level_tools: DebuginfoLevel,
201    pub rust_debuginfo_level_tests: DebuginfoLevel,
202    pub rust_rpath: bool,
203    pub rust_strip: bool,
204    pub rust_frame_pointers: bool,
205    pub rust_stack_protector: Option<String>,
206    pub rustc_default_linker: Option<String>,
207    pub rust_optimize_tests: bool,
208    pub rust_dist_src: bool,
209    pub rust_codegen_backends: Vec<String>,
210    pub rust_verify_llvm_ir: bool,
211    pub rust_thin_lto_import_instr_limit: Option<u32>,
212    pub rust_randomize_layout: bool,
213    pub rust_remap_debuginfo: bool,
214    pub rust_new_symbol_mangling: Option<bool>,
215    pub rust_profile_use: Option<String>,
216    pub rust_profile_generate: Option<String>,
217    pub rust_lto: RustcLto,
218    pub rust_validate_mir_opts: Option<u32>,
219    pub rust_std_features: BTreeSet<String>,
220    pub llvm_profile_use: Option<String>,
221    pub llvm_profile_generate: bool,
222    pub llvm_libunwind_default: Option<LlvmLibunwind>,
223    pub enable_bolt_settings: bool,
224
225    pub reproducible_artifacts: Vec<String>,
226
227    pub host_target: TargetSelection,
228    pub hosts: Vec<TargetSelection>,
229    pub targets: Vec<TargetSelection>,
230    pub local_rebuild: bool,
231    pub jemalloc: bool,
232    pub control_flow_guard: bool,
233    pub ehcont_guard: bool,
234
235    // dist misc
236    pub dist_sign_folder: Option<PathBuf>,
237    pub dist_upload_addr: Option<String>,
238    pub dist_compression_formats: Option<Vec<String>>,
239    pub dist_compression_profile: String,
240    pub dist_include_mingw_linker: bool,
241    pub dist_vendor: bool,
242
243    // libstd features
244    pub backtrace: bool, // support for RUST_BACKTRACE
245
246    // misc
247    pub low_priority: bool,
248    pub channel: String,
249    pub description: Option<String>,
250    pub verbose_tests: bool,
251    pub save_toolstates: Option<PathBuf>,
252    pub print_step_timings: bool,
253    pub print_step_rusage: bool,
254
255    // Fallback musl-root for all targets
256    pub musl_root: Option<PathBuf>,
257    pub prefix: Option<PathBuf>,
258    pub sysconfdir: Option<PathBuf>,
259    pub datadir: Option<PathBuf>,
260    pub docdir: Option<PathBuf>,
261    pub bindir: PathBuf,
262    pub libdir: Option<PathBuf>,
263    pub mandir: Option<PathBuf>,
264    pub codegen_tests: bool,
265    pub nodejs: Option<PathBuf>,
266    pub npm: Option<PathBuf>,
267    pub gdb: Option<PathBuf>,
268    pub lldb: Option<PathBuf>,
269    pub python: Option<PathBuf>,
270    pub reuse: Option<PathBuf>,
271    pub cargo_native_static: bool,
272    pub configure_args: Vec<String>,
273    pub out: PathBuf,
274    pub rust_info: channel::GitInfo,
275
276    pub cargo_info: channel::GitInfo,
277    pub rust_analyzer_info: channel::GitInfo,
278    pub clippy_info: channel::GitInfo,
279    pub miri_info: channel::GitInfo,
280    pub rustfmt_info: channel::GitInfo,
281    pub enzyme_info: channel::GitInfo,
282    pub in_tree_llvm_info: channel::GitInfo,
283    pub in_tree_gcc_info: channel::GitInfo,
284
285    // These are either the stage0 downloaded binaries or the locally installed ones.
286    pub initial_cargo: PathBuf,
287    pub initial_rustc: PathBuf,
288    pub initial_cargo_clippy: Option<PathBuf>,
289    pub initial_sysroot: PathBuf,
290    pub initial_rustfmt: Option<PathBuf>,
291
292    /// The paths to work with. For example: with `./x check foo bar` we get
293    /// `paths=["foo", "bar"]`.
294    pub paths: Vec<PathBuf>,
295
296    /// Command for visual diff display, e.g. `diff-tool --color=always`.
297    pub compiletest_diff_tool: Option<String>,
298
299    /// Whether to use the precompiled stage0 libtest with compiletest.
300    pub compiletest_use_stage0_libtest: bool,
301
302    pub is_running_on_ci: bool,
303
304    /// Cache for determining path modifications
305    pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
306
307    /// Skip checking the standard library if `rust.download-rustc` isn't available.
308    /// This is mostly for RA as building the stage1 compiler to check the library tree
309    /// on each code change might be too much for some computers.
310    pub skip_std_check_if_no_download_rustc: bool,
311
312    pub exec_ctx: ExecutionContext,
313}
314
315impl Config {
316    #[cfg_attr(
317        feature = "tracing",
318        instrument(target = "CONFIG_HANDLING", level = "trace", name = "Config::default_opts")
319    )]
320    pub fn default_opts() -> Config {
321        #[cfg(feature = "tracing")]
322        span!(target: "CONFIG_HANDLING", tracing::Level::TRACE, "constructing default config");
323
324        Config {
325            bypass_bootstrap_lock: false,
326            llvm_optimize: true,
327            ninja_in_file: true,
328            llvm_static_stdcpp: false,
329            llvm_libzstd: false,
330            backtrace: true,
331            rust_optimize: RustOptimize::Bool(true),
332            rust_optimize_tests: true,
333            rust_randomize_layout: false,
334            submodules: None,
335            docs: true,
336            docs_minification: true,
337            rust_rpath: true,
338            rust_strip: false,
339            channel: "dev".to_string(),
340            codegen_tests: true,
341            rust_dist_src: true,
342            rust_codegen_backends: vec!["llvm".to_owned()],
343            deny_warnings: true,
344            bindir: "bin".into(),
345            dist_include_mingw_linker: true,
346            dist_compression_profile: "fast".into(),
347
348            stdout_is_tty: std::io::stdout().is_terminal(),
349            stderr_is_tty: std::io::stderr().is_terminal(),
350
351            // set by build.rs
352            host_target: get_host_target(),
353
354            src: {
355                let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
356                // Undo `src/bootstrap`
357                manifest_dir.parent().unwrap().parent().unwrap().to_owned()
358            },
359            out: PathBuf::from("build"),
360
361            // This is needed by codegen_ssa on macOS to ship `llvm-objcopy` aliased to
362            // `rust-objcopy` to workaround bad `strip`s on macOS.
363            llvm_tools_enabled: true,
364
365            ..Default::default()
366        }
367    }
368
369    pub fn set_dry_run(&mut self, dry_run: DryRun) {
370        self.exec_ctx.set_dry_run(dry_run);
371    }
372
373    pub fn get_dry_run(&self) -> &DryRun {
374        self.exec_ctx.get_dry_run()
375    }
376
377    #[cfg_attr(
378        feature = "tracing",
379        instrument(target = "CONFIG_HANDLING", level = "trace", name = "Config::parse", skip_all)
380    )]
381    pub fn parse(flags: Flags) -> Config {
382        Self::parse_inner(flags, Self::get_toml)
383    }
384
385    #[cfg_attr(
386        feature = "tracing",
387        instrument(
388            target = "CONFIG_HANDLING",
389            level = "trace",
390            name = "Config::parse_inner",
391            skip_all
392        )
393    )]
394    pub(crate) fn parse_inner(
395        flags: Flags,
396        get_toml: impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
397    ) -> Config {
398        // Destructure flags to ensure that we use all its fields
399        // The field variables are prefixed with `flags_` to avoid clashes
400        // with values from TOML config files with same names.
401        let Flags {
402            cmd: flags_cmd,
403            verbose: flags_verbose,
404            incremental: flags_incremental,
405            config: flags_config,
406            build_dir: flags_build_dir,
407            build: flags_build,
408            host: flags_host,
409            target: flags_target,
410            exclude: flags_exclude,
411            skip: flags_skip,
412            include_default_paths: flags_include_default_paths,
413            rustc_error_format: flags_rustc_error_format,
414            on_fail: flags_on_fail,
415            dry_run: flags_dry_run,
416            dump_bootstrap_shims: flags_dump_bootstrap_shims,
417            stage: flags_stage,
418            keep_stage: flags_keep_stage,
419            keep_stage_std: flags_keep_stage_std,
420            src: flags_src,
421            jobs: flags_jobs,
422            warnings: flags_warnings,
423            json_output: flags_json_output,
424            color: flags_color,
425            bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
426            rust_profile_generate: flags_rust_profile_generate,
427            rust_profile_use: flags_rust_profile_use,
428            llvm_profile_use: flags_llvm_profile_use,
429            llvm_profile_generate: flags_llvm_profile_generate,
430            enable_bolt_settings: flags_enable_bolt_settings,
431            skip_stage0_validation: flags_skip_stage0_validation,
432            reproducible_artifact: flags_reproducible_artifact,
433            paths: mut flags_paths,
434            set: flags_set,
435            free_args: mut flags_free_args,
436            ci: flags_ci,
437            skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
438        } = flags;
439
440        let mut config = Config::default_opts();
441        let mut exec_ctx = ExecutionContext::new();
442        exec_ctx.set_verbose(flags_verbose);
443        exec_ctx.set_fail_fast(flags_cmd.fail_fast());
444
445        config.exec_ctx = exec_ctx;
446
447        // Set flags.
448        config.paths = std::mem::take(&mut flags_paths);
449
450        #[cfg(feature = "tracing")]
451        span!(
452            target: "CONFIG_HANDLING",
453            tracing::Level::TRACE,
454            "collecting paths and path exclusions",
455            "flags.paths" = ?flags_paths,
456            "flags.skip" = ?flags_skip,
457            "flags.exclude" = ?flags_exclude
458        );
459
460        #[cfg(feature = "tracing")]
461        span!(
462            target: "CONFIG_HANDLING",
463            tracing::Level::TRACE,
464            "normalizing and combining `flag.skip`/`flag.exclude` paths",
465            "config.skip" = ?config.skip,
466        );
467
468        config.include_default_paths = flags_include_default_paths;
469        config.rustc_error_format = flags_rustc_error_format;
470        config.json_output = flags_json_output;
471        config.on_fail = flags_on_fail;
472        config.cmd = flags_cmd;
473        config.incremental = flags_incremental;
474        config.set_dry_run(if flags_dry_run { DryRun::UserSelected } else { DryRun::Disabled });
475        config.dump_bootstrap_shims = flags_dump_bootstrap_shims;
476        config.keep_stage = flags_keep_stage;
477        config.keep_stage_std = flags_keep_stage_std;
478        config.color = flags_color;
479        config.free_args = std::mem::take(&mut flags_free_args);
480        config.llvm_profile_use = flags_llvm_profile_use;
481        config.llvm_profile_generate = flags_llvm_profile_generate;
482        config.enable_bolt_settings = flags_enable_bolt_settings;
483        config.bypass_bootstrap_lock = flags_bypass_bootstrap_lock;
484        config.is_running_on_ci = flags_ci.unwrap_or(CiEnv::is_ci());
485        config.skip_std_check_if_no_download_rustc = flags_skip_std_check_if_no_download_rustc;
486
487        // Infer the rest of the configuration.
488
489        if let Some(src) = flags_src {
490            config.src = src
491        } else {
492            // Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary,
493            // running on a completely different machine from where it was compiled.
494            let mut cmd = helpers::git(None);
495            // NOTE: we cannot support running from outside the repository because the only other path we have available
496            // is set at compile time, which can be wrong if bootstrap was downloaded rather than compiled locally.
497            // We still support running outside the repository if we find we aren't in a git directory.
498
499            // NOTE: We get a relative path from git to work around an issue on MSYS/mingw. If we used an absolute path,
500            // and end up using MSYS's git rather than git-for-windows, we would get a unix-y MSYS path. But as bootstrap
501            // has already been (kinda-cross-)compiled to Windows land, we require a normal Windows path.
502            cmd.arg("rev-parse").arg("--show-cdup");
503            // Discard stderr because we expect this to fail when building from a tarball.
504            let output = cmd.allow_failure().run_capture_stdout(&config);
505            if output.is_success() {
506                let git_root_relative = output.stdout();
507                // We need to canonicalize this path to make sure it uses backslashes instead of forward slashes,
508                // and to resolve any relative components.
509                let git_root = env::current_dir()
510                    .unwrap()
511                    .join(PathBuf::from(git_root_relative.trim()))
512                    .canonicalize()
513                    .unwrap();
514                let s = git_root.to_str().unwrap();
515
516                // Bootstrap is quite bad at handling /? in front of paths
517                let git_root = match s.strip_prefix("\\\\?\\") {
518                    Some(p) => PathBuf::from(p),
519                    None => git_root,
520                };
521                // If this doesn't have at least `stage0`, we guessed wrong. This can happen when,
522                // for example, the build directory is inside of another unrelated git directory.
523                // In that case keep the original `CARGO_MANIFEST_DIR` handling.
524                //
525                // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside
526                // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1.
527                if git_root.join("src").join("stage0").exists() {
528                    config.src = git_root;
529                }
530            } else {
531                // We're building from a tarball, not git sources.
532                // We don't support pre-downloaded bootstrap in this case.
533            }
534        }
535
536        if cfg!(test) {
537            // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly.
538            config.out = Path::new(
539                &env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"),
540            )
541            .parent()
542            .unwrap()
543            .to_path_buf();
544        }
545
546        config.stage0_metadata = build_helper::stage0_parser::parse_stage0_file();
547
548        // Locate the configuration file using the following priority (first match wins):
549        // 1. `--config <path>` (explicit flag)
550        // 2. `RUST_BOOTSTRAP_CONFIG` environment variable
551        // 3. `./bootstrap.toml` (local file)
552        // 4. `<root>/bootstrap.toml`
553        // 5. `./config.toml` (fallback for backward compatibility)
554        // 6. `<root>/config.toml`
555        let toml_path = flags_config
556            .clone()
557            .or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
558        let using_default_path = toml_path.is_none();
559        let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml"));
560
561        if using_default_path && !toml_path.exists() {
562            toml_path = config.src.join(PathBuf::from("bootstrap.toml"));
563            if !toml_path.exists() {
564                toml_path = PathBuf::from("config.toml");
565                if !toml_path.exists() {
566                    toml_path = config.src.join(PathBuf::from("config.toml"));
567                }
568            }
569        }
570
571        // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
572        // but not if `bootstrap.toml` hasn't been created.
573        let mut toml = if !using_default_path || toml_path.exists() {
574            config.config = Some(if cfg!(not(test)) {
575                toml_path = toml_path.canonicalize().unwrap();
576                toml_path.clone()
577            } else {
578                toml_path.clone()
579            });
580            get_toml(&toml_path).unwrap_or_else(|e| {
581                eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display());
582                exit!(2);
583            })
584        } else {
585            config.config = None;
586            TomlConfig::default()
587        };
588
589        if cfg!(test) {
590            // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the
591            // same ones used to call the tests (if custom ones are not defined in the toml). If we
592            // don't do that, bootstrap will use its own detection logic to find a suitable rustc
593            // and Cargo, which doesn't work when the caller is specìfying a custom local rustc or
594            // Cargo in their bootstrap.toml.
595            let build = toml.build.get_or_insert_with(Default::default);
596            build.rustc = build.rustc.take().or(std::env::var_os("RUSTC").map(|p| p.into()));
597            build.cargo = build.cargo.take().or(std::env::var_os("CARGO").map(|p| p.into()));
598        }
599
600        if config.git_info(false, &config.src).is_from_tarball() && toml.profile.is_none() {
601            toml.profile = Some("dist".into());
602        }
603
604        // Reverse the list to ensure the last added config extension remains the most dominant.
605        // For example, given ["a.toml", "b.toml"], "b.toml" should take precedence over "a.toml".
606        //
607        // This must be handled before applying the `profile` since `include`s should always take
608        // precedence over `profile`s.
609        for include_path in toml.include.clone().unwrap_or_default().iter().rev() {
610            let include_path = toml_path.parent().unwrap().join(include_path);
611
612            let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
613                eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display());
614                exit!(2);
615            });
616            toml.merge(
617                Some(include_path),
618                &mut Default::default(),
619                included_toml,
620                ReplaceOpt::IgnoreDuplicate,
621            );
622        }
623
624        if let Some(include) = &toml.profile {
625            // Allows creating alias for profile names, allowing
626            // profiles to be renamed while maintaining back compatibility
627            // Keep in sync with `profile_aliases` in bootstrap.py
628            let profile_aliases = HashMap::from([("user", "dist")]);
629            let include = match profile_aliases.get(include.as_str()) {
630                Some(alias) => alias,
631                None => include.as_str(),
632            };
633            let mut include_path = config.src.clone();
634            include_path.push("src");
635            include_path.push("bootstrap");
636            include_path.push("defaults");
637            include_path.push(format!("bootstrap.{include}.toml"));
638            let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
639                eprintln!(
640                    "ERROR: Failed to parse default config profile at '{}': {e}",
641                    include_path.display()
642                );
643                exit!(2);
644            });
645            toml.merge(
646                Some(include_path),
647                &mut Default::default(),
648                included_toml,
649                ReplaceOpt::IgnoreDuplicate,
650            );
651        }
652
653        let mut override_toml = TomlConfig::default();
654        for option in flags_set.iter() {
655            fn get_table(option: &str) -> Result<TomlConfig, toml::de::Error> {
656                toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table))
657            }
658
659            let mut err = match get_table(option) {
660                Ok(v) => {
661                    override_toml.merge(
662                        None,
663                        &mut Default::default(),
664                        v,
665                        ReplaceOpt::ErrorOnDuplicate,
666                    );
667                    continue;
668                }
669                Err(e) => e,
670            };
671            // We want to be able to set string values without quotes,
672            // like in `configure.py`. Try adding quotes around the right hand side
673            if let Some((key, value)) = option.split_once('=')
674                && !value.contains('"')
675            {
676                match get_table(&format!(r#"{key}="{value}""#)) {
677                    Ok(v) => {
678                        override_toml.merge(
679                            None,
680                            &mut Default::default(),
681                            v,
682                            ReplaceOpt::ErrorOnDuplicate,
683                        );
684                        continue;
685                    }
686                    Err(e) => err = e,
687                }
688            }
689            eprintln!("failed to parse override `{option}`: `{err}");
690            exit!(2)
691        }
692        toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override);
693
694        config.change_id = toml.change_id.inner;
695
696        let Build {
697            mut description,
698            build,
699            host,
700            target,
701            build_dir,
702            cargo,
703            rustc,
704            rustfmt,
705            cargo_clippy,
706            docs,
707            compiler_docs,
708            library_docs_private_items,
709            docs_minification,
710            submodules,
711            gdb,
712            lldb,
713            nodejs,
714            npm,
715            python,
716            reuse,
717            locked_deps,
718            vendor,
719            full_bootstrap,
720            bootstrap_cache_path,
721            extended,
722            tools,
723            tool,
724            verbose,
725            sanitizers,
726            profiler,
727            cargo_native_static,
728            low_priority,
729            configure_args,
730            local_rebuild,
731            print_step_timings,
732            print_step_rusage,
733            check_stage,
734            doc_stage,
735            build_stage,
736            test_stage,
737            install_stage,
738            dist_stage,
739            bench_stage,
740            patch_binaries_for_nix,
741            // This field is only used by bootstrap.py
742            metrics: _,
743            android_ndk,
744            optimized_compiler_builtins,
745            jobs,
746            compiletest_diff_tool,
747            compiletest_use_stage0_libtest,
748            mut ccache,
749            exclude,
750        } = toml.build.unwrap_or_default();
751
752        let mut paths: Vec<PathBuf> = flags_skip.into_iter().chain(flags_exclude).collect();
753
754        if let Some(exclude) = exclude {
755            paths.extend(exclude);
756        }
757
758        config.skip = paths
759            .into_iter()
760            .map(|p| {
761                // Never return top-level path here as it would break `--skip`
762                // logic on rustc's internal test framework which is utilized
763                // by compiletest.
764                if cfg!(windows) {
765                    PathBuf::from(p.to_str().unwrap().replace('/', "\\"))
766                } else {
767                    p
768                }
769            })
770            .collect();
771
772        config.jobs = Some(threads_from_config(flags_jobs.unwrap_or(jobs.unwrap_or(0))));
773
774        if let Some(flags_build) = flags_build {
775            config.host_target = TargetSelection::from_user(&flags_build);
776        } else if let Some(file_build) = build {
777            config.host_target = TargetSelection::from_user(&file_build);
778        };
779
780        set(&mut config.out, flags_build_dir.or_else(|| build_dir.map(PathBuf::from)));
781        // NOTE: Bootstrap spawns various commands with different working directories.
782        // To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
783        if !config.out.is_absolute() {
784            // `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
785            config.out = absolute(&config.out).expect("can't make empty path absolute");
786        }
787
788        if cargo_clippy.is_some() && rustc.is_none() {
789            println!(
790                "WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict."
791            );
792        }
793
794        config.initial_rustc = if let Some(rustc) = rustc {
795            if !flags_skip_stage0_validation {
796                config.check_stage0_version(&rustc, "rustc");
797            }
798            rustc
799        } else {
800            config.download_beta_toolchain();
801            config
802                .out
803                .join(config.host_target)
804                .join("stage0")
805                .join("bin")
806                .join(exe("rustc", config.host_target))
807        };
808
809        config.initial_sysroot = t!(PathBuf::from_str(
810            command(&config.initial_rustc)
811                .args(["--print", "sysroot"])
812                .run_always()
813                .run_capture_stdout(&config)
814                .stdout()
815                .trim()
816        ));
817
818        config.initial_cargo_clippy = cargo_clippy;
819
820        config.initial_cargo = if let Some(cargo) = cargo {
821            if !flags_skip_stage0_validation {
822                config.check_stage0_version(&cargo, "cargo");
823            }
824            cargo
825        } else {
826            config.download_beta_toolchain();
827            config.initial_sysroot.join("bin").join(exe("cargo", config.host_target))
828        };
829
830        // NOTE: it's important this comes *after* we set `initial_rustc` just above.
831        if config.dry_run() {
832            let dir = config.out.join("tmp-dry-run");
833            t!(fs::create_dir_all(&dir));
834            config.out = dir;
835        }
836
837        config.hosts = if let Some(TargetSelectionList(arg_host)) = flags_host {
838            arg_host
839        } else if let Some(file_host) = host {
840            file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
841        } else {
842            vec![config.host_target]
843        };
844        config.targets = if let Some(TargetSelectionList(arg_target)) = flags_target {
845            arg_target
846        } else if let Some(file_target) = target {
847            file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
848        } else {
849            // If target is *not* configured, then default to the host
850            // toolchains.
851            config.hosts.clone()
852        };
853
854        config.nodejs = nodejs.map(PathBuf::from);
855        config.npm = npm.map(PathBuf::from);
856        config.gdb = gdb.map(PathBuf::from);
857        config.lldb = lldb.map(PathBuf::from);
858        config.python = python.map(PathBuf::from);
859        config.reuse = reuse.map(PathBuf::from);
860        config.submodules = submodules;
861        config.android_ndk = android_ndk;
862        config.bootstrap_cache_path = bootstrap_cache_path;
863        set(&mut config.low_priority, low_priority);
864        set(&mut config.compiler_docs, compiler_docs);
865        set(&mut config.library_docs_private_items, library_docs_private_items);
866        set(&mut config.docs_minification, docs_minification);
867        set(&mut config.docs, docs);
868        set(&mut config.locked_deps, locked_deps);
869        set(&mut config.full_bootstrap, full_bootstrap);
870        set(&mut config.extended, extended);
871        config.tools = tools;
872        set(&mut config.tool, tool);
873        set(&mut config.verbose, verbose);
874        set(&mut config.sanitizers, sanitizers);
875        set(&mut config.profiler, profiler);
876        set(&mut config.cargo_native_static, cargo_native_static);
877        set(&mut config.configure_args, configure_args);
878        set(&mut config.local_rebuild, local_rebuild);
879        set(&mut config.print_step_timings, print_step_timings);
880        set(&mut config.print_step_rusage, print_step_rusage);
881        config.patch_binaries_for_nix = patch_binaries_for_nix;
882
883        config.verbose = cmp::max(config.verbose, flags_verbose as usize);
884
885        // Verbose flag is a good default for `rust.verbose-tests`.
886        config.verbose_tests = config.is_verbose();
887
888        config.apply_install_config(toml.install);
889
890        config.llvm_assertions =
891            toml.llvm.as_ref().is_some_and(|llvm| llvm.assertions.unwrap_or(false));
892
893        let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel")));
894        let ci_channel = file_content.trim_end();
895
896        let toml_channel = toml.rust.as_ref().and_then(|r| r.channel.clone());
897        let is_user_configured_rust_channel = match toml_channel {
898            Some(channel) if channel == "auto-detect" => {
899                config.channel = ci_channel.into();
900                true
901            }
902            Some(channel) => {
903                config.channel = channel;
904                true
905            }
906            None => false,
907        };
908
909        let default = config.channel == "dev";
910        config.omit_git_hash = toml.rust.as_ref().and_then(|r| r.omit_git_hash).unwrap_or(default);
911
912        config.rust_info = config.git_info(config.omit_git_hash, &config.src);
913        config.cargo_info =
914            config.git_info(config.omit_git_hash, &config.src.join("src/tools/cargo"));
915        config.rust_analyzer_info =
916            config.git_info(config.omit_git_hash, &config.src.join("src/tools/rust-analyzer"));
917        config.clippy_info =
918            config.git_info(config.omit_git_hash, &config.src.join("src/tools/clippy"));
919        config.miri_info =
920            config.git_info(config.omit_git_hash, &config.src.join("src/tools/miri"));
921        config.rustfmt_info =
922            config.git_info(config.omit_git_hash, &config.src.join("src/tools/rustfmt"));
923        config.enzyme_info =
924            config.git_info(config.omit_git_hash, &config.src.join("src/tools/enzyme"));
925        config.in_tree_llvm_info = config.git_info(false, &config.src.join("src/llvm-project"));
926        config.in_tree_gcc_info = config.git_info(false, &config.src.join("src/gcc"));
927
928        config.vendor = vendor.unwrap_or(
929            config.rust_info.is_from_tarball()
930                && config.src.join("vendor").exists()
931                && config.src.join(".cargo/config.toml").exists(),
932        );
933
934        if !is_user_configured_rust_channel && config.rust_info.is_from_tarball() {
935            config.channel = ci_channel.into();
936        }
937
938        config.rust_profile_use = flags_rust_profile_use;
939        config.rust_profile_generate = flags_rust_profile_generate;
940
941        config.apply_rust_config(toml.rust, flags_warnings, &mut description);
942
943        config.reproducible_artifacts = flags_reproducible_artifact;
944        config.description = description;
945
946        // We need to override `rust.channel` if it's manually specified when using the CI rustc.
947        // This is because if the compiler uses a different channel than the one specified in bootstrap.toml,
948        // tests may fail due to using a different channel than the one used by the compiler during tests.
949        if let Some(commit) = &config.download_rustc_commit
950            && is_user_configured_rust_channel
951        {
952            println!(
953                "WARNING: `rust.download-rustc` is enabled. The `rust.channel` option will be overridden by the CI rustc's channel."
954            );
955
956            let channel =
957                config.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
958
959            config.channel = channel;
960        }
961
962        config.apply_llvm_config(toml.llvm, &mut ccache);
963
964        config.apply_gcc_config(toml.gcc);
965
966        config.apply_target_config(toml.target);
967
968        match ccache {
969            Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
970            Some(StringOrBool::Bool(true)) => {
971                config.ccache = Some("ccache".to_string());
972            }
973            Some(StringOrBool::Bool(false)) | None => {}
974        }
975
976        if config.llvm_from_ci {
977            let triple = &config.host_target.triple;
978            let ci_llvm_bin = config.ci_llvm_root().join("bin");
979            let build_target = config
980                .target_config
981                .entry(config.host_target)
982                .or_insert_with(|| Target::from_triple(triple));
983
984            check_ci_llvm!(build_target.llvm_config);
985            check_ci_llvm!(build_target.llvm_filecheck);
986            build_target.llvm_config =
987                Some(ci_llvm_bin.join(exe("llvm-config", config.host_target)));
988            build_target.llvm_filecheck =
989                Some(ci_llvm_bin.join(exe("FileCheck", config.host_target)));
990        }
991
992        config.apply_dist_config(toml.dist);
993
994        config.initial_rustfmt =
995            if let Some(r) = rustfmt { Some(r) } else { config.maybe_download_rustfmt() };
996
997        if matches!(config.lld_mode, LldMode::SelfContained)
998            && !config.lld_enabled
999            && flags_stage.unwrap_or(0) > 0
1000        {
1001            panic!(
1002                "Trying to use self-contained lld as a linker, but LLD is not being added to the sysroot. Enable it with rust.lld = true."
1003            );
1004        }
1005
1006        if config.lld_enabled && config.is_system_llvm(config.host_target) {
1007            eprintln!(
1008                "Warning: LLD is enabled when using external llvm-config. LLD will not be built and copied to the sysroot."
1009            );
1010        }
1011
1012        config.optimized_compiler_builtins =
1013            optimized_compiler_builtins.unwrap_or(config.channel != "dev");
1014        config.compiletest_diff_tool = compiletest_diff_tool;
1015        config.compiletest_use_stage0_libtest = compiletest_use_stage0_libtest.unwrap_or(true);
1016
1017        let download_rustc = config.download_rustc_commit.is_some();
1018        config.explicit_stage_from_cli = flags_stage.is_some();
1019        config.explicit_stage_from_config = test_stage.is_some()
1020            || build_stage.is_some()
1021            || doc_stage.is_some()
1022            || dist_stage.is_some()
1023            || install_stage.is_some()
1024            || check_stage.is_some()
1025            || bench_stage.is_some();
1026        // See https://github.com/rust-lang/compiler-team/issues/326
1027        config.stage = match config.cmd {
1028            Subcommand::Check { .. } => flags_stage.or(check_stage).unwrap_or(0),
1029            Subcommand::Clippy { .. } | Subcommand::Fix => flags_stage.or(check_stage).unwrap_or(1),
1030            // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1031            Subcommand::Doc { .. } => {
1032                flags_stage.or(doc_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1033            }
1034            Subcommand::Build => {
1035                flags_stage.or(build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1036            }
1037            Subcommand::Test { .. } | Subcommand::Miri { .. } => {
1038                flags_stage.or(test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1039            }
1040            Subcommand::Bench { .. } => flags_stage.or(bench_stage).unwrap_or(2),
1041            Subcommand::Dist => flags_stage.or(dist_stage).unwrap_or(2),
1042            Subcommand::Install => flags_stage.or(install_stage).unwrap_or(2),
1043            Subcommand::Perf { .. } => flags_stage.unwrap_or(1),
1044            // These are all bootstrap tools, which don't depend on the compiler.
1045            // The stage we pass shouldn't matter, but use 0 just in case.
1046            Subcommand::Clean { .. }
1047            | Subcommand::Run { .. }
1048            | Subcommand::Setup { .. }
1049            | Subcommand::Format { .. }
1050            | Subcommand::Suggest { .. }
1051            | Subcommand::Vendor { .. } => flags_stage.unwrap_or(0),
1052        };
1053
1054        // CI should always run stage 2 builds, unless it specifically states otherwise
1055        #[cfg(not(test))]
1056        if flags_stage.is_none() && config.is_running_on_ci {
1057            match config.cmd {
1058                Subcommand::Test { .. }
1059                | Subcommand::Miri { .. }
1060                | Subcommand::Doc { .. }
1061                | Subcommand::Build
1062                | Subcommand::Bench { .. }
1063                | Subcommand::Dist
1064                | Subcommand::Install => {
1065                    assert_eq!(
1066                        config.stage, 2,
1067                        "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1068                        config.stage,
1069                    );
1070                }
1071                Subcommand::Clean { .. }
1072                | Subcommand::Check { .. }
1073                | Subcommand::Clippy { .. }
1074                | Subcommand::Fix
1075                | Subcommand::Run { .. }
1076                | Subcommand::Setup { .. }
1077                | Subcommand::Format { .. }
1078                | Subcommand::Suggest { .. }
1079                | Subcommand::Vendor { .. }
1080                | Subcommand::Perf { .. } => {}
1081            }
1082        }
1083
1084        config
1085    }
1086
1087    pub fn dry_run(&self) -> bool {
1088        self.exec_ctx.dry_run()
1089    }
1090
1091    pub fn is_explicit_stage(&self) -> bool {
1092        self.explicit_stage_from_cli || self.explicit_stage_from_config
1093    }
1094
1095    pub(crate) fn test_args(&self) -> Vec<&str> {
1096        let mut test_args = match self.cmd {
1097            Subcommand::Test { ref test_args, .. }
1098            | Subcommand::Bench { ref test_args, .. }
1099            | Subcommand::Miri { ref test_args, .. } => {
1100                test_args.iter().flat_map(|s| s.split_whitespace()).collect()
1101            }
1102            _ => vec![],
1103        };
1104        test_args.extend(self.free_args.iter().map(|s| s.as_str()));
1105        test_args
1106    }
1107
1108    pub(crate) fn args(&self) -> Vec<&str> {
1109        let mut args = match self.cmd {
1110            Subcommand::Run { ref args, .. } => {
1111                args.iter().flat_map(|s| s.split_whitespace()).collect()
1112            }
1113            _ => vec![],
1114        };
1115        args.extend(self.free_args.iter().map(|s| s.as_str()));
1116        args
1117    }
1118
1119    /// Returns the content of the given file at a specific commit.
1120    pub(crate) fn read_file_by_commit(&self, file: &Path, commit: &str) -> String {
1121        assert!(
1122            self.rust_info.is_managed_git_subrepository(),
1123            "`Config::read_file_by_commit` is not supported in non-git sources."
1124        );
1125
1126        let mut git = helpers::git(Some(&self.src));
1127        git.arg("show").arg(format!("{commit}:{}", file.to_str().unwrap()));
1128        git.run_capture_stdout(self).stdout()
1129    }
1130
1131    /// Bootstrap embeds a version number into the name of shared libraries it uploads in CI.
1132    /// Return the version it would have used for the given commit.
1133    pub(crate) fn artifact_version_part(&self, commit: &str) -> String {
1134        let (channel, version) = if self.rust_info.is_managed_git_subrepository() {
1135            let channel =
1136                self.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
1137            let version =
1138                self.read_file_by_commit(Path::new("src/version"), commit).trim().to_owned();
1139            (channel, version)
1140        } else {
1141            let channel = fs::read_to_string(self.src.join("src/ci/channel"));
1142            let version = fs::read_to_string(self.src.join("src/version"));
1143            match (channel, version) {
1144                (Ok(channel), Ok(version)) => {
1145                    (channel.trim().to_owned(), version.trim().to_owned())
1146                }
1147                (channel, version) => {
1148                    let src = self.src.display();
1149                    eprintln!("ERROR: failed to determine artifact channel and/or version");
1150                    eprintln!(
1151                        "HELP: consider using a git checkout or ensure these files are readable"
1152                    );
1153                    if let Err(channel) = channel {
1154                        eprintln!("reading {src}/src/ci/channel failed: {channel:?}");
1155                    }
1156                    if let Err(version) = version {
1157                        eprintln!("reading {src}/src/version failed: {version:?}");
1158                    }
1159                    panic!();
1160                }
1161            }
1162        };
1163
1164        match channel.as_str() {
1165            "stable" => version,
1166            "beta" => channel,
1167            "nightly" => channel,
1168            other => unreachable!("{:?} is not recognized as a valid channel", other),
1169        }
1170    }
1171
1172    /// Try to find the relative path of `bindir`, otherwise return it in full.
1173    pub fn bindir_relative(&self) -> &Path {
1174        let bindir = &self.bindir;
1175        if bindir.is_absolute() {
1176            // Try to make it relative to the prefix.
1177            if let Some(prefix) = &self.prefix
1178                && let Ok(stripped) = bindir.strip_prefix(prefix)
1179            {
1180                return stripped;
1181            }
1182        }
1183        bindir
1184    }
1185
1186    /// Try to find the relative path of `libdir`.
1187    pub fn libdir_relative(&self) -> Option<&Path> {
1188        let libdir = self.libdir.as_ref()?;
1189        if libdir.is_relative() {
1190            Some(libdir)
1191        } else {
1192            // Try to make it relative to the prefix.
1193            libdir.strip_prefix(self.prefix.as_ref()?).ok()
1194        }
1195    }
1196
1197    /// The absolute path to the downloaded LLVM artifacts.
1198    pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1199        assert!(self.llvm_from_ci);
1200        self.out.join(self.host_target).join("ci-llvm")
1201    }
1202
1203    /// Directory where the extracted `rustc-dev` component is stored.
1204    pub(crate) fn ci_rustc_dir(&self) -> PathBuf {
1205        assert!(self.download_rustc());
1206        self.out.join(self.host_target).join("ci-rustc")
1207    }
1208
1209    /// Determine whether llvm should be linked dynamically.
1210    ///
1211    /// If `false`, llvm should be linked statically.
1212    /// This is computed on demand since LLVM might have to first be downloaded from CI.
1213    pub(crate) fn llvm_link_shared(&self) -> bool {
1214        let mut opt = self.llvm_link_shared.get();
1215        if opt.is_none() && self.dry_run() {
1216            // just assume static for now - dynamic linking isn't supported on all platforms
1217            return false;
1218        }
1219
1220        let llvm_link_shared = *opt.get_or_insert_with(|| {
1221            if self.llvm_from_ci {
1222                self.maybe_download_ci_llvm();
1223                let ci_llvm = self.ci_llvm_root();
1224                let link_type = t!(
1225                    std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1226                    format!("CI llvm missing: {}", ci_llvm.display())
1227                );
1228                link_type == "dynamic"
1229            } else {
1230                // unclear how thought-through this default is, but it maintains compatibility with
1231                // previous behavior
1232                false
1233            }
1234        });
1235        self.llvm_link_shared.set(opt);
1236        llvm_link_shared
1237    }
1238
1239    /// Return whether we will use a downloaded, pre-compiled version of rustc, or just build from source.
1240    pub(crate) fn download_rustc(&self) -> bool {
1241        self.download_rustc_commit().is_some()
1242    }
1243
1244    pub(crate) fn download_rustc_commit(&self) -> Option<&str> {
1245        static DOWNLOAD_RUSTC: OnceLock<Option<String>> = OnceLock::new();
1246        if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
1247            // avoid trying to actually download the commit
1248            return self.download_rustc_commit.as_deref();
1249        }
1250
1251        DOWNLOAD_RUSTC
1252            .get_or_init(|| match &self.download_rustc_commit {
1253                None => None,
1254                Some(commit) => {
1255                    self.download_ci_rustc(commit);
1256
1257                    // CI-rustc can't be used without CI-LLVM. If `self.llvm_from_ci` is false, it means the "if-unchanged"
1258                    // logic has detected some changes in the LLVM submodule (download-ci-llvm=false can't happen here as
1259                    // we don't allow it while parsing the configuration).
1260                    if !self.llvm_from_ci {
1261                        // This happens when LLVM submodule is updated in CI, we should disable ci-rustc without an error
1262                        // to not break CI. For non-CI environments, we should return an error.
1263                        if self.is_running_on_ci {
1264                            println!("WARNING: LLVM submodule has changes, `download-rustc` will be disabled.");
1265                            return None;
1266                        } else {
1267                            panic!("ERROR: LLVM submodule has changes, `download-rustc` can't be used.");
1268                        }
1269                    }
1270
1271                    if let Some(config_path) = &self.config {
1272                        let ci_config_toml = match self.get_builder_toml("ci-rustc") {
1273                            Ok(ci_config_toml) => ci_config_toml,
1274                            Err(e) if e.to_string().contains("unknown field") => {
1275                                println!("WARNING: CI rustc has some fields that are no longer supported in bootstrap; download-rustc will be disabled.");
1276                                println!("HELP: Consider rebasing to a newer commit if available.");
1277                                return None;
1278                            },
1279                            Err(e) => {
1280                                eprintln!("ERROR: Failed to parse CI rustc bootstrap.toml: {e}");
1281                                exit!(2);
1282                            },
1283                        };
1284
1285                        let current_config_toml = Self::get_toml(config_path).unwrap();
1286
1287                        // Check the config compatibility
1288                        // FIXME: this doesn't cover `--set` flags yet.
1289                        let res = check_incompatible_options_for_ci_rustc(
1290                            self.host_target,
1291                            current_config_toml,
1292                            ci_config_toml,
1293                        );
1294
1295                        // Primarily used by CI runners to avoid handling download-rustc incompatible
1296                        // options one by one on shell scripts.
1297                        let disable_ci_rustc_if_incompatible = env::var_os("DISABLE_CI_RUSTC_IF_INCOMPATIBLE")
1298                            .is_some_and(|s| s == "1" || s == "true");
1299
1300                        if disable_ci_rustc_if_incompatible && res.is_err() {
1301                            println!("WARNING: download-rustc is disabled with `DISABLE_CI_RUSTC_IF_INCOMPATIBLE` env.");
1302                            return None;
1303                        }
1304
1305                        res.unwrap();
1306                    }
1307
1308                    Some(commit.clone())
1309                }
1310            })
1311            .as_deref()
1312    }
1313
1314    /// Runs a function if verbosity is greater than 0
1315    pub fn verbose(&self, f: impl Fn()) {
1316        self.exec_ctx.verbose(f);
1317    }
1318
1319    pub fn any_sanitizers_to_build(&self) -> bool {
1320        self.target_config
1321            .iter()
1322            .any(|(ts, t)| !ts.is_msvc() && t.sanitizers.unwrap_or(self.sanitizers))
1323    }
1324
1325    pub fn any_profiler_enabled(&self) -> bool {
1326        self.target_config.values().any(|t| matches!(&t.profiler, Some(p) if p.is_string_or_true()))
1327            || self.profiler
1328    }
1329
1330    /// Returns whether or not submodules should be managed by bootstrap.
1331    pub fn submodules(&self) -> bool {
1332        // If not specified in config, the default is to only manage
1333        // submodules if we're currently inside a git repository.
1334        self.submodules.unwrap_or(self.rust_info.is_managed_git_subrepository())
1335    }
1336
1337    pub fn git_config(&self) -> GitConfig<'_> {
1338        GitConfig {
1339            nightly_branch: &self.stage0_metadata.config.nightly_branch,
1340            git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
1341        }
1342    }
1343
1344    /// Given a path to the directory of a submodule, update it.
1345    ///
1346    /// `relative_path` should be relative to the root of the git repository, not an absolute path.
1347    ///
1348    /// This *does not* update the submodule if `bootstrap.toml` explicitly says
1349    /// not to, or if we're not in a git repository (like a plain source
1350    /// tarball). Typically [`crate::Build::require_submodule`] should be
1351    /// used instead to provide a nice error to the user if the submodule is
1352    /// missing.
1353    #[cfg_attr(
1354        feature = "tracing",
1355        instrument(
1356            level = "trace",
1357            name = "Config::update_submodule",
1358            skip_all,
1359            fields(relative_path = ?relative_path),
1360        ),
1361    )]
1362    pub(crate) fn update_submodule(&self, relative_path: &str) {
1363        if self.rust_info.is_from_tarball() || !self.submodules() {
1364            return;
1365        }
1366
1367        let absolute_path = self.src.join(relative_path);
1368
1369        // NOTE: This check is required because `jj git clone` doesn't create directories for
1370        // submodules, they are completely ignored. The code below assumes this directory exists,
1371        // so create it here.
1372        if !absolute_path.exists() {
1373            t!(fs::create_dir_all(&absolute_path));
1374        }
1375
1376        // NOTE: The check for the empty directory is here because when running x.py the first time,
1377        // the submodule won't be checked out. Check it out now so we can build it.
1378        if !self.git_info(false, &absolute_path).is_managed_git_subrepository()
1379            && !helpers::dir_is_empty(&absolute_path)
1380        {
1381            return;
1382        }
1383
1384        // Submodule updating actually happens during in the dry run mode. We need to make sure that
1385        // all the git commands below are actually executed, because some follow-up code
1386        // in bootstrap might depend on the submodules being checked out. Furthermore, not all
1387        // the command executions below work with an empty output (produced during dry run).
1388        // Therefore, all commands below are marked with `run_always()`, so that they also run in
1389        // dry run mode.
1390        let submodule_git = || {
1391            let mut cmd = helpers::git(Some(&absolute_path));
1392            cmd.run_always();
1393            cmd
1394        };
1395
1396        // Determine commit checked out in submodule.
1397        let checked_out_hash =
1398            submodule_git().args(["rev-parse", "HEAD"]).run_capture_stdout(self).stdout();
1399        let checked_out_hash = checked_out_hash.trim_end();
1400        // Determine commit that the submodule *should* have.
1401        let recorded = helpers::git(Some(&self.src))
1402            .run_always()
1403            .args(["ls-tree", "HEAD"])
1404            .arg(relative_path)
1405            .run_capture_stdout(self)
1406            .stdout();
1407
1408        let actual_hash = recorded
1409            .split_whitespace()
1410            .nth(2)
1411            .unwrap_or_else(|| panic!("unexpected output `{recorded}`"));
1412
1413        if actual_hash == checked_out_hash {
1414            // already checked out
1415            return;
1416        }
1417
1418        println!("Updating submodule {relative_path}");
1419
1420        helpers::git(Some(&self.src))
1421            .allow_failure()
1422            .run_always()
1423            .args(["submodule", "-q", "sync"])
1424            .arg(relative_path)
1425            .run(self);
1426
1427        // Try passing `--progress` to start, then run git again without if that fails.
1428        let update = |progress: bool| {
1429            // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository,
1430            // even though that has no relation to the upstream for the submodule.
1431            let current_branch = helpers::git(Some(&self.src))
1432                .allow_failure()
1433                .run_always()
1434                .args(["symbolic-ref", "--short", "HEAD"])
1435                .run_capture(self);
1436
1437            let mut git = helpers::git(Some(&self.src)).allow_failure();
1438            git.run_always();
1439            if current_branch.is_success() {
1440                // If there is a tag named after the current branch, git will try to disambiguate by prepending `heads/` to the branch name.
1441                // This syntax isn't accepted by `branch.{branch}`. Strip it.
1442                let branch = current_branch.stdout();
1443                let branch = branch.trim();
1444                let branch = branch.strip_prefix("heads/").unwrap_or(branch);
1445                git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
1446            }
1447            git.args(["submodule", "update", "--init", "--recursive", "--depth=1"]);
1448            if progress {
1449                git.arg("--progress");
1450            }
1451            git.arg(relative_path);
1452            git
1453        };
1454        if !update(true).allow_failure().run(self) {
1455            update(false).allow_failure().run(self);
1456        }
1457
1458        // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error).
1459        // diff-index reports the modifications through the exit status
1460        let has_local_modifications =
1461            !submodule_git().allow_failure().args(["diff-index", "--quiet", "HEAD"]).run(self);
1462        if has_local_modifications {
1463            submodule_git().allow_failure().args(["stash", "push"]).run(self);
1464        }
1465
1466        submodule_git().allow_failure().args(["reset", "-q", "--hard"]).run(self);
1467        submodule_git().allow_failure().args(["clean", "-qdfx"]).run(self);
1468
1469        if has_local_modifications {
1470            submodule_git().allow_failure().args(["stash", "pop"]).run(self);
1471        }
1472    }
1473
1474    #[cfg(test)]
1475    pub fn check_stage0_version(&self, _program_path: &Path, _component_name: &'static str) {}
1476
1477    /// check rustc/cargo version is same or lower with 1 apart from the building one
1478    #[cfg(not(test))]
1479    pub fn check_stage0_version(&self, program_path: &Path, component_name: &'static str) {
1480        use build_helper::util::fail;
1481
1482        if self.dry_run() {
1483            return;
1484        }
1485
1486        let stage0_output =
1487            command(program_path).arg("--version").run_capture_stdout(self).stdout();
1488        let mut stage0_output = stage0_output.lines().next().unwrap().split(' ');
1489
1490        let stage0_name = stage0_output.next().unwrap();
1491        if stage0_name != component_name {
1492            fail(&format!(
1493                "Expected to find {component_name} at {} but it claims to be {stage0_name}",
1494                program_path.display()
1495            ));
1496        }
1497
1498        let stage0_version =
1499            semver::Version::parse(stage0_output.next().unwrap().split('-').next().unwrap().trim())
1500                .unwrap();
1501        let source_version = semver::Version::parse(
1502            fs::read_to_string(self.src.join("src/version")).unwrap().trim(),
1503        )
1504        .unwrap();
1505        if !(source_version == stage0_version
1506            || (source_version.major == stage0_version.major
1507                && (source_version.minor == stage0_version.minor
1508                    || source_version.minor == stage0_version.minor + 1)))
1509        {
1510            let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1);
1511            fail(&format!(
1512                "Unexpected {component_name} version: {stage0_version}, we should use {prev_version}/{source_version} to build source with {source_version}"
1513            ));
1514        }
1515    }
1516
1517    /// Returns the commit to download, or `None` if we shouldn't download CI artifacts.
1518    pub fn download_ci_rustc_commit(
1519        &self,
1520        download_rustc: Option<StringOrBool>,
1521        debug_assertions_requested: bool,
1522        llvm_assertions: bool,
1523    ) -> Option<String> {
1524        if !is_download_ci_available(&self.host_target.triple, llvm_assertions) {
1525            return None;
1526        }
1527
1528        // If `download-rustc` is not set, default to rebuilding.
1529        let if_unchanged = match download_rustc {
1530            // Globally default `download-rustc` to `false`, because some contributors don't use
1531            // profiles for reasons such as:
1532            // - They need to seamlessly switch between compiler/library work.
1533            // - They don't want to use compiler profile because they need to override too many
1534            //   things and it's easier to not use a profile.
1535            None | Some(StringOrBool::Bool(false)) => return None,
1536            Some(StringOrBool::Bool(true)) => false,
1537            Some(StringOrBool::String(s)) if s == "if-unchanged" => {
1538                if !self.rust_info.is_managed_git_subrepository() {
1539                    println!(
1540                        "ERROR: `download-rustc=if-unchanged` is only compatible with Git managed sources."
1541                    );
1542                    crate::exit!(1);
1543                }
1544
1545                true
1546            }
1547            Some(StringOrBool::String(other)) => {
1548                panic!("unrecognized option for download-rustc: {other}")
1549            }
1550        };
1551
1552        let commit = if self.rust_info.is_managed_git_subrepository() {
1553            // Look for a version to compare to based on the current commit.
1554            // Only commits merged by bors will have CI artifacts.
1555            let freshness = self.check_path_modifications(RUSTC_IF_UNCHANGED_ALLOWED_PATHS);
1556            self.verbose(|| {
1557                eprintln!("rustc freshness: {freshness:?}");
1558            });
1559            match freshness {
1560                PathFreshness::LastModifiedUpstream { upstream } => upstream,
1561                PathFreshness::HasLocalModifications { upstream } => {
1562                    if if_unchanged {
1563                        return None;
1564                    }
1565
1566                    if self.is_running_on_ci {
1567                        eprintln!("CI rustc commit matches with HEAD and we are in CI.");
1568                        eprintln!(
1569                            "`rustc.download-ci` functionality will be skipped as artifacts are not available."
1570                        );
1571                        return None;
1572                    }
1573
1574                    upstream
1575                }
1576                PathFreshness::MissingUpstream => {
1577                    eprintln!("No upstream commit found");
1578                    return None;
1579                }
1580            }
1581        } else {
1582            channel::read_commit_info_file(&self.src)
1583                .map(|info| info.sha.trim().to_owned())
1584                .expect("git-commit-info is missing in the project root")
1585        };
1586
1587        if debug_assertions_requested {
1588            eprintln!(
1589                "WARN: `rust.debug-assertions = true` will prevent downloading CI rustc as alt CI \
1590                rustc is not currently built with debug assertions."
1591            );
1592            return None;
1593        }
1594
1595        Some(commit)
1596    }
1597
1598    pub fn parse_download_ci_llvm(
1599        &self,
1600        download_ci_llvm: Option<StringOrBool>,
1601        asserts: bool,
1602    ) -> bool {
1603        // We don't ever want to use `true` on CI, as we should not
1604        // download upstream artifacts if there are any local modifications.
1605        let default = if self.is_running_on_ci {
1606            StringOrBool::String("if-unchanged".to_string())
1607        } else {
1608            StringOrBool::Bool(true)
1609        };
1610        let download_ci_llvm = download_ci_llvm.unwrap_or(default);
1611
1612        let if_unchanged = || {
1613            if self.rust_info.is_from_tarball() {
1614                // Git is needed for running "if-unchanged" logic.
1615                println!("ERROR: 'if-unchanged' is only compatible with Git managed sources.");
1616                crate::exit!(1);
1617            }
1618
1619            // Fetching the LLVM submodule is unnecessary for self-tests.
1620            #[cfg(not(test))]
1621            self.update_submodule("src/llvm-project");
1622
1623            // Check for untracked changes in `src/llvm-project` and other important places.
1624            let has_changes = self.has_changes_from_upstream(LLVM_INVALIDATION_PATHS);
1625
1626            // Return false if there are untracked changes, otherwise check if CI LLVM is available.
1627            if has_changes { false } else { llvm::is_ci_llvm_available_for_target(self, asserts) }
1628        };
1629
1630        match download_ci_llvm {
1631            StringOrBool::Bool(b) => {
1632                if !b && self.download_rustc_commit.is_some() {
1633                    panic!(
1634                        "`llvm.download-ci-llvm` cannot be set to `false` if `rust.download-rustc` is set to `true` or `if-unchanged`."
1635                    );
1636                }
1637
1638                if b && self.is_running_on_ci {
1639                    // On CI, we must always rebuild LLVM if there were any modifications to it
1640                    panic!(
1641                        "`llvm.download-ci-llvm` cannot be set to `true` on CI. Use `if-unchanged` instead."
1642                    );
1643                }
1644
1645                // If download-ci-llvm=true we also want to check that CI llvm is available
1646                b && llvm::is_ci_llvm_available_for_target(self, asserts)
1647            }
1648            StringOrBool::String(s) if s == "if-unchanged" => if_unchanged(),
1649            StringOrBool::String(other) => {
1650                panic!("unrecognized option for download-ci-llvm: {other:?}")
1651            }
1652        }
1653    }
1654
1655    /// Returns true if any of the `paths` have been modified locally.
1656    pub fn has_changes_from_upstream(&self, paths: &[&'static str]) -> bool {
1657        match self.check_path_modifications(paths) {
1658            PathFreshness::LastModifiedUpstream { .. } => false,
1659            PathFreshness::HasLocalModifications { .. } | PathFreshness::MissingUpstream => true,
1660        }
1661    }
1662
1663    /// Checks whether any of the given paths have been modified w.r.t. upstream.
1664    pub fn check_path_modifications(&self, paths: &[&'static str]) -> PathFreshness {
1665        // Checking path modifications through git can be relatively expensive (>100ms).
1666        // We do not assume that the sources would change during bootstrap's execution,
1667        // so we can cache the results here.
1668        // Note that we do not use a static variable for the cache, because it would cause problems
1669        // in tests that create separate `Config` instsances.
1670        self.path_modification_cache
1671            .lock()
1672            .unwrap()
1673            .entry(paths.to_vec())
1674            .or_insert_with(|| {
1675                check_path_modifications(&self.src, &self.git_config(), paths, CiEnv::current())
1676                    .unwrap()
1677            })
1678            .clone()
1679    }
1680
1681    pub fn ci_env(&self) -> CiEnv {
1682        if self.is_running_on_ci { CiEnv::GitHubActions } else { CiEnv::None }
1683    }
1684
1685    pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1686        self.target_config.get(&target).and_then(|t| t.sanitizers).unwrap_or(self.sanitizers)
1687    }
1688
1689    pub fn needs_sanitizer_runtime_built(&self, target: TargetSelection) -> bool {
1690        // MSVC uses the Microsoft-provided sanitizer runtime, but all other runtimes we build.
1691        !target.is_msvc() && self.sanitizers_enabled(target)
1692    }
1693
1694    pub fn profiler_path(&self, target: TargetSelection) -> Option<&str> {
1695        match self.target_config.get(&target)?.profiler.as_ref()? {
1696            StringOrBool::String(s) => Some(s),
1697            StringOrBool::Bool(_) => None,
1698        }
1699    }
1700
1701    pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1702        self.target_config
1703            .get(&target)
1704            .and_then(|t| t.profiler.as_ref())
1705            .map(StringOrBool::is_string_or_true)
1706            .unwrap_or(self.profiler)
1707    }
1708
1709    pub fn codegen_backends(&self, target: TargetSelection) -> &[String] {
1710        self.target_config
1711            .get(&target)
1712            .and_then(|cfg| cfg.codegen_backends.as_deref())
1713            .unwrap_or(&self.rust_codegen_backends)
1714    }
1715
1716    pub fn jemalloc(&self, target: TargetSelection) -> bool {
1717        self.target_config.get(&target).and_then(|cfg| cfg.jemalloc).unwrap_or(self.jemalloc)
1718    }
1719
1720    pub fn default_codegen_backend(&self, target: TargetSelection) -> Option<String> {
1721        self.codegen_backends(target).first().cloned()
1722    }
1723
1724    pub fn rpath_enabled(&self, target: TargetSelection) -> bool {
1725        self.target_config.get(&target).and_then(|t| t.rpath).unwrap_or(self.rust_rpath)
1726    }
1727
1728    pub fn optimized_compiler_builtins(&self, target: TargetSelection) -> bool {
1729        self.target_config
1730            .get(&target)
1731            .and_then(|t| t.optimized_compiler_builtins)
1732            .unwrap_or(self.optimized_compiler_builtins)
1733    }
1734
1735    pub fn llvm_enabled(&self, target: TargetSelection) -> bool {
1736        self.codegen_backends(target).contains(&"llvm".to_owned())
1737    }
1738
1739    pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1740        self.target_config
1741            .get(&target)
1742            .and_then(|t| t.llvm_libunwind)
1743            .or(self.llvm_libunwind_default)
1744            .unwrap_or(if target.contains("fuchsia") {
1745                LlvmLibunwind::InTree
1746            } else {
1747                LlvmLibunwind::No
1748            })
1749    }
1750
1751    pub fn split_debuginfo(&self, target: TargetSelection) -> SplitDebuginfo {
1752        self.target_config
1753            .get(&target)
1754            .and_then(|t| t.split_debuginfo)
1755            .unwrap_or_else(|| SplitDebuginfo::default_for_platform(target))
1756    }
1757
1758    /// Checks if the given target is the same as the host target.
1759    pub fn is_host_target(&self, target: TargetSelection) -> bool {
1760        self.host_target == target
1761    }
1762
1763    /// Returns `true` if this is an external version of LLVM not managed by bootstrap.
1764    /// In particular, we expect llvm sources to be available when this is false.
1765    ///
1766    /// NOTE: this is not the same as `!is_rust_llvm` when `llvm_has_patches` is set.
1767    pub fn is_system_llvm(&self, target: TargetSelection) -> bool {
1768        match self.target_config.get(&target) {
1769            Some(Target { llvm_config: Some(_), .. }) => {
1770                let ci_llvm = self.llvm_from_ci && self.is_host_target(target);
1771                !ci_llvm
1772            }
1773            // We're building from the in-tree src/llvm-project sources.
1774            Some(Target { llvm_config: None, .. }) => false,
1775            None => false,
1776        }
1777    }
1778
1779    /// Returns `true` if this is our custom, patched, version of LLVM.
1780    ///
1781    /// This does not necessarily imply that we're managing the `llvm-project` submodule.
1782    pub fn is_rust_llvm(&self, target: TargetSelection) -> bool {
1783        match self.target_config.get(&target) {
1784            // We're using a user-controlled version of LLVM. The user has explicitly told us whether the version has our patches.
1785            // (They might be wrong, but that's not a supported use-case.)
1786            // In particular, this tries to support `submodules = false` and `patches = false`, for using a newer version of LLVM that's not through `rust-lang/llvm-project`.
1787            Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
1788            // The user hasn't promised the patches match.
1789            // This only has our patches if it's downloaded from CI or built from source.
1790            _ => !self.is_system_llvm(target),
1791        }
1792    }
1793
1794    pub fn exec_ctx(&self) -> &ExecutionContext {
1795        &self.exec_ctx
1796    }
1797
1798    pub fn git_info(&self, omit_git_hash: bool, dir: &Path) -> GitInfo {
1799        GitInfo::new(omit_git_hash, dir, self)
1800    }
1801}
1802
1803impl AsRef<ExecutionContext> for Config {
1804    fn as_ref(&self) -> &ExecutionContext {
1805        &self.exec_ctx
1806    }
1807}