Skip to main content

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.
16use std::collections::{BTreeSet, HashMap, HashSet};
17use std::io::IsTerminal;
18use std::path::{Path, PathBuf, absolute};
19use std::str::FromStr;
20use std::sync::{Arc, Mutex, OnceLock};
21use std::{cmp, env, fs};
22
23use build_helper::ci::CiEnv;
24use build_helper::git::{GitConfig, PathFreshness, check_path_modifications};
25use serde::Deserialize;
26#[cfg(feature = "tracing")]
27use tracing::{instrument, span};
28
29use crate::core::backend::CodegenBackendKind;
30use crate::core::build_steps::llvm::{LLVM_INVALIDATION_PATHS, LlvmKind, LlvmOutput};
31use crate::core::build_steps::test::failed_tests::collect_previously_failed_tests;
32use crate::core::config::flags::{Color, Flags, Subcommand, Warnings};
33use crate::core::config::target_selection::TargetSelectionList;
34use crate::core::config::toml::TomlConfig;
35use crate::core::config::toml::build::{Build, Tool};
36use crate::core::config::toml::change_id::ChangeId;
37use crate::core::config::toml::dist::Dist;
38use crate::core::config::toml::gcc::Gcc;
39use crate::core::config::toml::install::Install;
40use crate::core::config::toml::llvm::Llvm;
41use crate::core::config::toml::pgo::{Pgo, PgoConfig};
42use crate::core::config::toml::rust::{
43    BootstrapOverrideLld, Rust, RustOptimize, check_incompatible_options_for_ci_rustc,
44    parse_codegen_backends,
45};
46use crate::core::config::toml::target::{
47    DefaultLinuxLinkerOverride, Target, TomlTarget, default_linux_linker_overrides,
48};
49use crate::core::config::{
50    Allocator, CompilerBuiltins, CompressDebuginfo, DebuggerPath, DebuginfoLevel, DryRun,
51    GccCiMode, LlvmCiMode, LlvmLibunwind, Merge, ReplaceOpt, RustcLto, SplitDebuginfo,
52    StringOrBool, TargetSelection, threads_from_config,
53};
54use crate::core::download::{DownloadContext, is_download_ci_available};
55use crate::utils::channel::{self, GitInfo};
56use crate::utils::exec::{ExecutionContext, command};
57use crate::utils::helpers::{self, exe, fail, get_host_target, t};
58
59/// Each path in this list is considered "allowed" in the `download-rustc="if-unchanged"` logic.
60/// This means they can be modified and changes to these paths should never trigger a compiler build
61/// when "if-unchanged" is set.
62///
63/// NOTE: Paths must have the ":!" prefix to tell git to ignore changes in those paths during
64/// the diff check.
65///
66/// WARNING: Be cautious when adding paths to this list. If a path that influences the compiler build
67/// is added here, it will cause bootstrap to skip necessary rebuilds, which may lead to risky results.
68/// For example, "src/bootstrap" should never be included in this list as it plays a crucial role in the
69/// final output/compiler, which can be significantly affected by changes made to the bootstrap sources.
70#[rustfmt::skip] // We don't want rustfmt to oneline this list
71pub const RUSTC_IF_UNCHANGED_ALLOWED_PATHS: &[&str] = &[
72    ":!library",
73    ":!src/tools",
74    ":!src/librustdoc",
75    ":!src/rustdoc-json-types",
76    ":!tests",
77    ":!triagebot.toml",
78    ":!src/bootstrap/defaults",
79];
80
81/// Global configuration for the entire build and/or bootstrap.
82///
83/// This structure is parsed from `bootstrap.toml`, and some of the fields are inferred from `git` or build-time parameters.
84///
85/// Note that this structure is not decoded directly into, but rather it is
86/// filled out from the decoded forms of the structs below. For documentation
87/// on each field, see the corresponding fields in
88/// `bootstrap.example.toml`.
89#[derive(Clone)]
90pub(crate) struct Config {
91    pub change_id: Option<ChangeId>,
92    pub bypass_bootstrap_lock: bool,
93    pub ccache: Option<String>,
94    pub sde: Option<PathBuf>,
95    /// Call `Session::ninja` instead of this.
96    pub ninja_in_file: bool,
97    pub submodules: Option<bool>,
98    pub compiler_docs: bool,
99    pub library_docs_private_items: bool,
100    pub docs_minification: bool,
101    pub docs: bool,
102    pub locked_deps: bool,
103    pub vendor: bool,
104    pub target_config: HashMap<TargetSelection, Target>,
105    pub full_bootstrap: bool,
106    pub bootstrap_cache_path: Option<PathBuf>,
107    pub extended: bool,
108    pub tools: Option<HashSet<String>>,
109    /// Specify build configuration specific for some tool, such as enabled features, see [Tool].
110    /// The key in the map is the name of the tool, and the value is tool-specific configuration.
111    pub tool: HashMap<String, Tool>,
112    pub sanitizers: bool,
113    pub profiler: bool,
114    pub omit_git_hash: bool,
115    pub skip: Vec<PathBuf>,
116    pub include_default_paths: bool,
117    pub rustc_error_format: Option<String>,
118    pub json_output: bool,
119    pub compile_time_deps: bool,
120    pub test_compare_mode: bool,
121    pub color: Color,
122    pub patch_binaries_for_nix: Option<bool>,
123    pub stage0_metadata: build_helper::stage0_parser::Stage0,
124    pub android_ndk: Option<PathBuf>,
125    pub optimized_compiler_builtins: CompilerBuiltins,
126    pub record_failed_tests_path: PathBuf,
127    /// Path to an external checkout of rustc-perf, for running custom benchmarks.
128    pub rustc_perf_path: Option<PathBuf>,
129
130    pub stdout_is_tty: bool,
131    pub stderr_is_tty: bool,
132
133    pub on_fail: Option<String>,
134    pub explicit_stage_from_cli: bool,
135    pub explicit_stage_from_config: bool,
136    pub stage: u32,
137    pub keep_stage: Vec<u32>,
138    pub keep_stage_std: Vec<u32>,
139    pub src: PathBuf,
140    /// defaults to `bootstrap.toml`
141    pub config: Option<PathBuf>,
142    pub jobs: Option<u32>,
143    pub cmd: Subcommand,
144    pub quiet: bool,
145    pub incremental: bool,
146    pub dump_bootstrap_shims: bool,
147    /// Arguments appearing after `--` to be forwarded to tools,
148    /// e.g. `--fix-broken` or test arguments.
149    pub free_args: Vec<String>,
150
151    /// `None` if we shouldn't download CI compiler artifacts, or the commit to download if we should.
152    pub download_rustc_commit: Option<String>,
153
154    pub deny_warnings: bool,
155    pub backtrace_on_ice: bool,
156
157    // llvm codegen options
158    pub llvm_assertions: bool,
159    pub llvm_tests: bool,
160    pub llvm_enzyme: bool,
161    pub llvm_offload: bool,
162    pub llvm_plugins: bool,
163    pub llvm_optimize: bool,
164    pub llvm_thin_lto: bool,
165    pub llvm_release_debuginfo: bool,
166    pub llvm_static_stdcpp: bool,
167    pub llvm_libzstd: bool,
168    pub llvm_link_shared: Option<bool>,
169    pub llvm_clang_cl: Option<String>,
170    pub llvm_targets: Option<String>,
171    pub llvm_experimental_targets: Option<String>,
172    pub llvm_link_jobs: Option<u32>,
173    pub llvm_version_suffix: Option<String>,
174    pub llvm_use_linker: Option<String>,
175    pub offload_clang_dir: Option<PathBuf>,
176    pub llvm_allow_old_toolchain: bool,
177    pub llvm_polly: bool,
178    pub llvm_clang: bool,
179    pub llvm_enable_warnings: bool,
180    pub llvm_ci_mode: LlvmCiMode,
181    pub llvm_build_config: HashMap<String, String>,
182    pub llvm_tpde: bool,
183
184    pub bootstrap_override_lld: BootstrapOverrideLld,
185    pub lld_enabled: bool,
186    pub llvm_tools_enabled: bool,
187    pub llvm_bitcode_linker_enabled: bool,
188
189    pub llvm_cflags: Option<String>,
190    pub llvm_cxxflags: Option<String>,
191    pub llvm_ldflags: Option<String>,
192    pub llvm_use_libcxx: bool,
193    pub llvm_pgo: LlvmPgoConfig,
194
195    // gcc codegen options
196    pub gcc_ci_mode: GccCiMode,
197    pub libgccjit_libs_dir: Option<PathBuf>,
198
199    // rust codegen options
200    pub rust_optimize: RustOptimize,
201    pub rust_codegen_units: Option<u32>,
202    pub rust_codegen_units_std: Option<u32>,
203    pub rustc_debug_assertions: bool,
204    pub std_debug_assertions: bool,
205    pub tools_debug_assertions: bool,
206
207    pub rust_overflow_checks: bool,
208    pub rust_overflow_checks_std: bool,
209    pub rust_debug_logging: bool,
210    pub rust_debuginfo_level_rustc: DebuginfoLevel,
211    pub rust_debuginfo_level_std: DebuginfoLevel,
212    pub rust_debuginfo_level_tools: DebuginfoLevel,
213    pub rust_debuginfo_level_tests: DebuginfoLevel,
214    pub rust_compress_debuginfo: CompressDebuginfo,
215    pub rust_rpath: bool,
216    pub rust_strip: bool,
217    pub rust_frame_pointers: bool,
218    pub rust_stack_protector: Option<String>,
219    pub rustc_default_linker: Option<String>,
220    pub rust_optimize_tests: bool,
221    pub rust_dist_src: bool,
222    pub rust_codegen_backends: Vec<CodegenBackendKind>,
223    pub rust_verify_llvm_ir: bool,
224    pub rust_thin_lto_import_instr_limit: Option<u32>,
225    pub rust_randomize_layout: bool,
226    pub rust_remap_debuginfo: bool,
227    pub rust_new_symbol_mangling: Option<bool>,
228    pub rust_annotate_moves_size_limit: Option<u64>,
229    pub rust_lto: RustcLto,
230    pub rust_validate_mir_opts: Option<u32>,
231    pub rust_std_features: BTreeSet<String>,
232    pub rust_break_on_ice: bool,
233    pub rust_parallel_frontend_threads: Option<u32>,
234    pub rust_rustflags: Vec<String>,
235
236    // Note: modify the ReproducibleArtifacts step when adding new PGO configs here!
237    pub rust_pgo: PgoConfig,
238    pub rustdoc_pgo: PgoConfig,
239    pub cargo_pgo: PgoConfig,
240    pub clippy_pgo: PgoConfig,
241    pub cranelift_pgo: PgoConfig,
242
243    pub stdlib_semver_baseline: Option<String>,
244
245    pub llvm_libunwind_default: Option<LlvmLibunwind>,
246    pub enable_bolt_settings: bool,
247
248    pub reproducible_artifacts: Vec<String>,
249
250    /// Build triple for the pre-compiled snapshot compiler.
251    pub host_target: TargetSelection,
252    /// Which triples to produce a compiler toolchain for.
253    pub hosts: Vec<TargetSelection>,
254    /// Which triples to build libraries (core/alloc/std/test/proc_macro) for.
255    pub targets: Vec<TargetSelection>,
256
257    pub local_rebuild: bool,
258    pub allocator: Option<Allocator>,
259    pub control_flow_guard: bool,
260    pub ehcont_guard: bool,
261
262    // dist misc
263    pub dist_sign_folder: Option<PathBuf>,
264    pub dist_upload_addr: Option<String>,
265    pub dist_compression_formats: Option<Vec<String>>,
266    pub dist_compression_profile: String,
267    pub dist_include_mingw_linker: bool,
268    pub dist_vendor: bool,
269
270    // libstd features
271    pub backtrace: bool, // support for RUST_BACKTRACE
272
273    // misc
274    pub low_priority: bool,
275    pub channel: String,
276    pub description: Option<String>,
277    pub verbose_tests: bool,
278    pub save_toolstates: Option<PathBuf>,
279    pub print_step_timings: bool,
280    pub print_step_rusage: bool,
281
282    // Fallback musl-root for all targets
283    pub musl_root: Option<PathBuf>,
284    pub prefix: Option<PathBuf>,
285    pub sysconfdir: Option<PathBuf>,
286    pub datadir: Option<PathBuf>,
287    pub docdir: Option<PathBuf>,
288    pub bindir: PathBuf,
289    pub libdir: Option<PathBuf>,
290    pub mandir: Option<PathBuf>,
291    pub codegen_tests: bool,
292    pub nodejs: Option<PathBuf>,
293    pub yarn: Option<PathBuf>,
294    pub gdb: Option<DebuggerPath>,
295    pub lldb: Option<DebuggerPath>,
296    pub python: Option<PathBuf>,
297    pub windows_rc: Option<PathBuf>,
298    pub reuse: Option<PathBuf>,
299    pub cargo_native_static: bool,
300    pub out: PathBuf,
301    pub rust_info: channel::GitInfo,
302
303    pub cargo_info: channel::GitInfo,
304    pub rust_analyzer_info: channel::GitInfo,
305    pub clippy_info: channel::GitInfo,
306    pub miri_info: channel::GitInfo,
307    pub rustfmt_info: channel::GitInfo,
308    pub enzyme_info: channel::GitInfo,
309    pub in_tree_llvm_info: channel::GitInfo,
310    pub in_tree_gcc_info: channel::GitInfo,
311    pub in_tree_tpde_info: channel::GitInfo,
312
313    /// rustc/cargo/rustdoc/clippy paths specified in the config file
314    /// Access the `initial_` fields from `Session` to use either the externally configured
315    /// or downloaded (stage0) binaries.
316    pub external_cargo: Option<PathBuf>,
317    pub external_rustc: Option<PathBuf>,
318    pub external_rustdoc: Option<PathBuf>,
319    pub external_cargo_clippy: Option<PathBuf>,
320
321    /// Externally configured `rustfmt` binary for formatting in-tree source code.
322    /// If you want to use rustfmt for formatting, use the `InternalRustfmt` step, instead of
323    /// accessing this directly.
324    pub external_rustfmt: Option<PathBuf>,
325
326    /// The paths to work with. For example: with `./x check foo bar` we get
327    /// `paths=["foo", "bar"]`.
328    pub paths: Vec<PathBuf>,
329
330    /// Command for visual diff display, e.g. `diff-tool --color=always`.
331    pub compiletest_diff_tool: Option<String>,
332
333    /// Whether to allow running both `compiletest` self-tests and `compiletest`-managed test suites
334    /// against the stage 0 (rustc, std).
335    ///
336    /// This is only intended to be used when the stage 0 compiler is actually built from in-tree
337    /// sources.
338    pub compiletest_allow_stage0: bool,
339
340    /// Default value for `--extra-checks`
341    pub tidy_extra_checks: Option<String>,
342    pub ci_env: CiEnv,
343
344    /// Cache for determining path modifications
345    pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
346
347    /// Skip checking the standard library if `rust.download-rustc` isn't available.
348    /// This is mostly for RA as building the stage1 compiler to check the library tree
349    /// on each code change might be too much for some computers.
350    pub skip_std_check_if_no_download_rustc: bool,
351
352    pub exec_ctx: ExecutionContext,
353
354    pub wasm_proc_macros: bool,
355
356    pub wasm_panic_unwind_default: bool,
357}
358
359impl Config {
360    pub fn set_dry_run(&mut self, dry_run: DryRun) {
361        self.exec_ctx.set_dry_run(dry_run);
362    }
363
364    pub fn get_dry_run(&self) -> &DryRun {
365        self.exec_ctx.get_dry_run()
366    }
367
368    #[cfg_attr(
369        feature = "tracing",
370        instrument(target = "CONFIG_HANDLING", level = "trace", name = "Config::parse", skip_all)
371    )]
372    pub fn parse(flags: Flags) -> Config {
373        Self::parse_inner(flags, Self::get_toml)
374    }
375
376    #[cfg_attr(
377        feature = "tracing",
378        instrument(
379            target = "CONFIG_HANDLING",
380            level = "trace",
381            name = "Config::parse_inner",
382            skip_all
383        )
384    )]
385    pub(crate) fn parse_inner(
386        flags: Flags,
387        get_toml: impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
388    ) -> Config {
389        // Destructure flags to ensure that we use all its fields
390        // The field variables are prefixed with `flags_` to avoid clashes
391        // with values from TOML config files with same names.
392        let Flags {
393            cmd: flags_cmd,
394            verbose: flags_verbose,
395            quiet: flags_quiet,
396            incremental: flags_incremental,
397            config: flags_config,
398            build_dir: flags_build_dir,
399            build: flags_build,
400            host: flags_host,
401            target: flags_target,
402            exclude: flags_exclude,
403            skip: flags_skip,
404            include_default_paths: flags_include_default_paths,
405            rustc_error_format: flags_rustc_error_format,
406            on_fail: flags_on_fail,
407            dry_run: flags_dry_run,
408            dump_bootstrap_shims: flags_dump_bootstrap_shims,
409            stage: flags_stage,
410            keep_stage: flags_keep_stage,
411            keep_stage_std: flags_keep_stage_std,
412            src: flags_src,
413            jobs: flags_jobs,
414            warnings: flags_warnings,
415            json_output: flags_json_output,
416            compile_time_deps: flags_compile_time_deps,
417            color: flags_color,
418            bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
419            rust_profile_generate: flags_rust_profile_generate,
420            rust_profile_use: flags_rust_profile_use,
421            llvm_profile_use: flags_llvm_profile_use,
422            llvm_profile_generate: flags_llvm_profile_generate,
423            enable_bolt_settings: flags_enable_bolt_settings,
424            skip_stage0_validation: flags_skip_stage0_validation,
425            reproducible_artifact: flags_reproducible_artifact,
426            paths: flags_paths,
427            set: flags_set,
428            free_args: flags_free_args,
429            ci: flags_ci,
430            skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
431        } = flags;
432
433        #[cfg(feature = "tracing")]
434        span!(
435            target: "CONFIG_HANDLING",
436            tracing::Level::TRACE,
437            "collecting paths and path exclusions",
438            "flags.paths" = ?flags_paths,
439            "flags.skip" = ?flags_skip,
440            "flags.exclude" = ?flags_exclude
441        );
442
443        if flags_cmd.no_doc() {
444            eprintln!(
445                "WARN: `x.py test --no-doc` is renamed to `--all-targets`. `--no-doc` will be removed in the near future. Additionally `--tests` is added which only executes unit and integration tests."
446            )
447        }
448
449        // Set config values based on flags.
450        let mut exec_ctx = ExecutionContext::new(flags_verbose, flags_cmd.fail_fast());
451        exec_ctx.set_dry_run(if flags_dry_run { DryRun::UserSelected } else { DryRun::Disabled });
452
453        let default_src_dir = {
454            let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
455            // Undo `src/bootstrap`
456            manifest_dir.parent().unwrap().parent().unwrap().to_owned()
457        };
458
459        // Determine the root of the `rust-lang/rust` source directory from one of:
460        // - An explicit command-line argument `--src=PATH`.
461        // - Running git to find a checkout directory from the current working directory.
462        // - The source directory that this bootstrap executable was built from.
463        let src = flags_src
464            .or_else(|| compute_src_directory_via_git(&exec_ctx))
465            .unwrap_or_else(|| default_src_dir.clone());
466
467        if cfg!(test) {
468            match flags_config.as_deref() {
469                Some(config_path) => assert!(
470                    !config_path.starts_with(&src),
471                    "Path {config_path:?} should not be inside or equal to src dir {src:?}"
472                ),
473                None => panic!("During test the config should be explicitly added"),
474            }
475        }
476
477        // Now load the TOML config, as soon as possible
478        let (mut toml, toml_path) = load_toml_config(&src, flags_config, &get_toml);
479        postprocess_toml(&mut toml, &src, toml_path.clone(), &exec_ctx, &flags_set, &get_toml);
480        let TomlConfig {
481            change_id: toml_change_id,
482            build: toml_build,
483            install: toml_install,
484            llvm: toml_llvm,
485            gcc: toml_gcc,
486            rust: toml_rust,
487            target: toml_target,
488            dist: toml_dist,
489            pgo: toml_pgo,
490            profile: _,
491            include: _,
492        } = toml;
493
494        // Now override TOML values with flags, to make sure that we won't later override flags with
495        // TOML values by accident instead, because flags have higher priority.
496        let Build {
497            description: build_description,
498            build: build_build,
499            host: build_host,
500            target: build_target,
501            build_dir: build_build_dir,
502            cargo: mut build_cargo,
503            rustc: mut build_rustc,
504            rustdoc: build_rustdoc,
505            rustfmt: build_rustfmt,
506            cargo_clippy: build_cargo_clippy,
507            docs: build_docs,
508            compiler_docs: build_compiler_docs,
509            library_docs_private_items: build_library_docs_private_items,
510            docs_minification: build_docs_minification,
511            submodules: build_submodules,
512            gdb: build_gdb,
513            lldb: build_lldb,
514            nodejs: build_nodejs,
515            yarn: build_yarn,
516            npm: build_npm,
517            python: build_python,
518            windows_rc: build_windows_rc,
519            reuse: build_reuse,
520            locked_deps: build_locked_deps,
521            vendor: build_vendor,
522            full_bootstrap: build_full_bootstrap,
523            bootstrap_cache_path: build_bootstrap_cache_path,
524            extended: build_extended,
525            tools: build_tools,
526            tool: build_tool,
527            verbose: build_verbose,
528            sanitizers: build_sanitizers,
529            profiler: build_profiler,
530            cargo_native_static: build_cargo_native_static,
531            low_priority: build_low_priority,
532            // Our `./configure` script saves a copy of its command-line arguments as
533            // `build.configure-args` when generating `bootstrap.toml`.
534            // This is for debugging only, and bootstrap itself doesn't use these values.
535            configure_args: _,
536            local_rebuild: build_local_rebuild,
537            print_step_timings: build_print_step_timings,
538            print_step_rusage: build_print_step_rusage,
539            check_stage: build_check_stage,
540            doc_stage: build_doc_stage,
541            build_stage: build_build_stage,
542            test_stage: build_test_stage,
543            install_stage: build_install_stage,
544            dist_stage: build_dist_stage,
545            bench_stage: build_bench_stage,
546            patch_binaries_for_nix: build_patch_binaries_for_nix,
547            record_failed_tests_path: build_record_failed_tests_path,
548            // This field is only used by bootstrap.py
549            metrics: _,
550            android_ndk: build_android_ndk,
551            optimized_compiler_builtins: build_optimized_compiler_builtins,
552            jobs: build_jobs,
553            compiletest_diff_tool: build_compiletest_diff_tool,
554            tidy_extra_checks: build_tidy_extra_checks,
555            ccache: build_ccache,
556            exclude: build_exclude,
557            compiletest_allow_stage0: build_compiletest_allow_stage0,
558            sde: build_sde,
559            allocator: build_allocator,
560            rustc_perf_path: build_rustc_perf_path,
561        } = toml_build.unwrap_or_default();
562
563        let Install {
564            prefix: install_prefix,
565            sysconfdir: install_sysconfdir,
566            docdir: install_docdir,
567            bindir: install_bindir,
568            libdir: install_libdir,
569            mandir: install_mandir,
570            datadir: install_datadir,
571        } = toml_install.unwrap_or_default();
572
573        let Rust {
574            optimize: rust_optimize,
575            debug: rust_debug,
576            codegen_units: rust_codegen_units,
577            codegen_units_std: rust_codegen_units_std,
578            rustc_debug_assertions: rust_rustc_debug_assertions,
579            std_debug_assertions: rust_std_debug_assertions,
580            tools_debug_assertions: rust_tools_debug_assertions,
581            overflow_checks: rust_overflow_checks,
582            overflow_checks_std: rust_overflow_checks_std,
583            debug_logging: rust_debug_logging,
584            debuginfo_level: rust_debuginfo_level,
585            debuginfo_level_rustc: rust_debuginfo_level_rustc,
586            debuginfo_level_std: rust_debuginfo_level_std,
587            debuginfo_level_tools: rust_debuginfo_level_tools,
588            debuginfo_level_tests: rust_debuginfo_level_tests,
589            compress_debuginfo: rust_compress_debuginfo,
590            backtrace: rust_backtrace,
591            incremental: rust_incremental,
592            randomize_layout: rust_randomize_layout,
593            default_linker: rust_default_linker,
594            channel: rust_channel,
595            musl_root: rust_musl_root,
596            rpath: rust_rpath,
597            verbose_tests: rust_verbose_tests,
598            optimize_tests: rust_optimize_tests,
599            codegen_tests: rust_codegen_tests,
600            omit_git_hash: rust_omit_git_hash,
601            dist_src: rust_dist_src,
602            save_toolstates: rust_save_toolstates,
603            codegen_backends: rust_codegen_backends,
604            lld: rust_lld_enabled,
605            llvm_tools: rust_llvm_tools,
606            llvm_bitcode_linker: rust_llvm_bitcode_linker,
607            deny_warnings: rust_deny_warnings,
608            backtrace_on_ice: rust_backtrace_on_ice,
609            verify_llvm_ir: rust_verify_llvm_ir,
610            thin_lto_import_instr_limit: rust_thin_lto_import_instr_limit,
611            parallel_frontend_threads: rust_parallel_frontend_threads,
612            remap_debuginfo: rust_remap_debuginfo,
613            jemalloc: rust_jemalloc,
614            test_compare_mode: rust_test_compare_mode,
615            llvm_libunwind: rust_llvm_libunwind,
616            control_flow_guard: rust_control_flow_guard,
617            ehcont_guard: rust_ehcont_guard,
618            new_symbol_mangling: rust_new_symbol_mangling,
619            annotate_moves_size_limit: rust_annotate_moves_size_limit,
620            profile_generate: rust_profile_generate,
621            profile_use: rust_profile_use,
622            download_rustc: rust_download_rustc,
623            lto: rust_lto,
624            validate_mir_opts: rust_validate_mir_opts,
625            frame_pointers: rust_frame_pointers,
626            stack_protector: rust_stack_protector,
627            strip: rust_strip,
628            bootstrap_override_lld: rust_bootstrap_override_lld,
629            std_features: rust_std_features,
630            break_on_ice: rust_break_on_ice,
631            rustflags: rust_rustflags,
632            stdlib_semver_baseline: rust_stdlib_semver_baseline,
633            wasm_proc_macros,
634            wasm_panic_unwind_default,
635        } = toml_rust.unwrap_or_default();
636
637        let Llvm {
638            optimize: llvm_optimize,
639            thin_lto: llvm_thin_lto,
640            release_debuginfo: llvm_release_debuginfo,
641            assertions: llvm_assertions,
642            tests: llvm_tests,
643            enzyme: llvm_enzyme,
644            plugins: llvm_plugin,
645            static_libstdcpp: llvm_static_libstdcpp,
646            libzstd: llvm_libzstd,
647            ninja: llvm_ninja,
648            targets: llvm_targets,
649            experimental_targets: llvm_experimental_targets,
650            link_jobs: llvm_link_jobs,
651            link_shared: llvm_link_shared,
652            version_suffix: llvm_version_suffix,
653            clang_cl: llvm_clang_cl,
654            cflags: llvm_cflags,
655            cxxflags: llvm_cxxflags,
656            ldflags: llvm_ldflags,
657            use_libcxx: llvm_use_libcxx,
658            use_linker: llvm_use_linker,
659            allow_old_toolchain: llvm_allow_old_toolchain,
660            offload: llvm_offload,
661            offload_clang_dir,
662            polly: llvm_polly,
663            clang: llvm_clang,
664            enable_warnings: llvm_enable_warnings,
665            download_ci_llvm: llvm_download_ci_llvm,
666            build_config: llvm_build_config,
667            tpde: llvm_tpde,
668        } = toml_llvm.unwrap_or_default();
669
670        let Dist {
671            sign_folder: dist_sign_folder,
672            upload_addr: dist_upload_addr,
673            src_tarball: dist_src_tarball,
674            compression_formats: dist_compression_formats,
675            compression_profile: dist_compression_profile,
676            include_mingw_linker: dist_include_mingw_linker,
677            vendor: dist_vendor,
678        } = toml_dist.unwrap_or_default();
679
680        let Gcc {
681            download_ci_gcc: gcc_download_ci_gcc,
682            libgccjit_libs_dir: gcc_libgccjit_libs_dir,
683        } = toml_gcc.unwrap_or_default();
684
685        let Pgo {
686            rustc: pgo_rustc,
687            rustdoc: pgo_rustdoc,
688            cargo: pgo_cargo,
689            clippy: pgo_clippy,
690            cranelift: pgo_cranelift,
691            llvm: pgo_llvm,
692        } = toml_pgo.unwrap_or_default();
693
694        // Backcompat: flags have priority over config
695        if flags_rust_profile_use.is_some() || flags_rust_profile_generate.is_some() {
696            eprintln!(
697                "WARNING: the `--rust-profile-generate` and `--rust-profile-use` flags have been deprecated. Configure PGO through the config file instead, in the [pgo.rustc] section."
698            );
699        }
700        if rust_profile_use.is_some() || rust_profile_generate.is_some() {
701            eprintln!(
702                "WARNING: the `rust.profile-generate` and `rust.profile-use` config options have been deprecated. Configure PGO through the config file instead, in the [pgo.rustc] section."
703            );
704        }
705        if flags_llvm_profile_use.is_some() || flags_llvm_profile_generate {
706            eprintln!(
707                "WARNING: the `--llvm-profile-generate` and `--llvm-profile-use` flags have been deprecated. Configure PGO through the config file instead, in the [pgo.llvm] section."
708            );
709        }
710
711        let mut pgo_rustc = pgo_rustc.unwrap_or_default();
712        pgo_rustc.use_profile =
713            flags_rust_profile_use.or(pgo_rustc.use_profile).or(rust_profile_use);
714        pgo_rustc.generate_profile =
715            flags_rust_profile_generate.or(pgo_rustc.generate_profile).or(rust_profile_generate);
716        if pgo_rustc.use_profile.is_some() && pgo_rustc.generate_profile.is_some() {
717            panic!("Cannot use and generate rust PGO profiles at the same time");
718        }
719
720        let pgo_llvm = pgo_llvm.unwrap_or_default();
721        let pgo_llvm = LlvmPgoConfig {
722            use_profile: flags_llvm_profile_use.or(pgo_llvm.use_profile),
723            generate_profile: if flags_llvm_profile_generate {
724                Some(if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
725                    LlvmPgoGenerationMode::Directory(PathBuf::from(llvm_profile_dir))
726                } else {
727                    LlvmPgoGenerationMode::Implicit
728                })
729            } else {
730                pgo_llvm.generate_profile.map(LlvmPgoGenerationMode::Directory)
731            },
732        };
733        if pgo_llvm.use_profile.is_some() && pgo_llvm.generate_profile.is_some() {
734            panic!("Cannot use and generate LLVM PGO profiles at the same time");
735        }
736
737        let init_pgo = |pgo: Option<PgoConfig>, name: &str| -> PgoConfig {
738            let pgo_config = pgo.unwrap_or_default();
739            if pgo_config.use_profile.is_some() && pgo_config.generate_profile.is_some() {
740                panic!("Cannot use and generate {name} PGO profiles at the same time");
741            }
742            pgo_config
743        };
744
745        let pgo_rustdoc = init_pgo(pgo_rustdoc, "rustdoc");
746        let pgo_cargo = init_pgo(pgo_cargo, "cargo");
747        let pgo_clippy = init_pgo(pgo_clippy, "clippy");
748        let pgo_cranelift = init_pgo(pgo_cranelift, "cranelift");
749
750        let bootstrap_override_lld = rust_bootstrap_override_lld.unwrap_or_default();
751
752        if rust_optimize.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) {
753            eprintln!(
754                "WARNING: setting `optimize` to `false` is known to cause errors and \
755                should be considered unsupported. Refer to `bootstrap.example.toml` \
756                for more details."
757            );
758        }
759
760        // Prefer CLI verbosity flags if set (`flags_verbose` > 0), otherwise take the value from
761        // TOML.
762        exec_ctx.set_verbosity(cmp::max(build_verbose.unwrap_or_default() as u8, flags_verbose));
763
764        let stage0_metadata = build_helper::stage0_parser::parse_stage0_file();
765        let path_modification_cache = Arc::new(Mutex::new(HashMap::new()));
766
767        let host_target = flags_build
768            .or(build_build)
769            .map(|build| TargetSelection::from_user(&build))
770            .unwrap_or_else(get_host_target);
771        let hosts = flags_host
772            .map(|TargetSelectionList(hosts)| hosts)
773            .or_else(|| {
774                build_host.map(|h| h.iter().map(|t| TargetSelection::from_user(t)).collect())
775            })
776            .unwrap_or_else(|| vec![host_target]);
777
778        let llvm_assertions = llvm_assertions.unwrap_or(false);
779        let mut target_config = HashMap::new();
780        let mut channel = "dev".to_string();
781
782        let out = flags_build_dir.or_else(|| build_build_dir.map(PathBuf::from));
783        let out = if cfg!(test) {
784            out.expect("--build-dir has to be specified in tests")
785        } else {
786            out.unwrap_or_else(|| PathBuf::from("build"))
787        };
788
789        // NOTE: Bootstrap spawns various commands with different working directories.
790        // To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
791        let out = if !out.is_absolute() {
792            // `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
793            absolute(&out).expect("can't make empty path absolute")
794        } else {
795            out
796        };
797
798        let default_stage0_rustc_path = |dir: &Path| {
799            dir.join(host_target).join("stage0").join("bin").join(exe("rustc", host_target))
800        };
801
802        if cfg!(test) {
803            // When configuring bootstrap for tests, make sure to set the rustc and Cargo to the
804            // same ones used to call the tests (if custom ones are not defined in the toml). If we
805            // don't do that, bootstrap will use its own detection logic to find a suitable rustc
806            // and Cargo, which doesn't work when the caller is specìfying a custom local rustc or
807            // Cargo in their bootstrap.toml.
808            build_rustc = build_rustc.take().or(std::env::var_os("RUSTC").map(|p| p.into()));
809            build_cargo = build_cargo.take().or(std::env::var_os("CARGO").map(|p| p.into()));
810
811            // If we are running only `cargo test` (and not `x test bootstrap`), which is useful
812            // e.g. for debugging bootstrap itself, then we won't have RUSTC and CARGO set to the
813            // proper paths.
814            // We thus "guess" that the build directory is located at <src>/build, and try to load
815            // rustc and cargo from there
816            let is_test_outside_x = std::env::var("CARGO_TARGET_DIR").is_err();
817            if is_test_outside_x && build_rustc.is_none() {
818                let stage0_rustc = default_stage0_rustc_path(&default_src_dir.join("build"));
819                assert!(
820                    stage0_rustc.exists(),
821                    "Trying to run cargo test without having a stage0 rustc available in {}",
822                    stage0_rustc.display()
823                );
824                build_rustc = Some(stage0_rustc);
825            }
826        }
827
828        if !flags_skip_stage0_validation {
829            if let Some(rustc) = &build_rustc {
830                check_external_binary_version(rustc, "rustc", &src, &exec_ctx);
831            }
832            if let Some(cargo) = &build_cargo {
833                check_external_binary_version(cargo, "cargo", &src, &exec_ctx);
834            }
835        }
836
837        if build_cargo_clippy.is_some() && build_rustc.is_none() {
838            println!(
839                "WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict."
840            );
841        }
842
843        let ci_env = match flags_ci {
844            Some(true) => CiEnv::GitHubActions,
845            Some(false) => CiEnv::None,
846            None => CiEnv::current(),
847        };
848        let dwn_ctx = DownloadContext {
849            path_modification_cache: path_modification_cache.clone(),
850            src: &src,
851            submodules: &build_submodules,
852            host_target,
853            patch_binaries_for_nix: build_patch_binaries_for_nix,
854            exec_ctx: &exec_ctx,
855            stage0_metadata: &stage0_metadata,
856            llvm_assertions,
857            bootstrap_cache_path: &build_bootstrap_cache_path,
858            ci_env,
859        };
860
861        let file_content = t!(fs::read_to_string(src.join("src/ci/channel")));
862        let ci_channel = file_content.trim_end();
863
864        let is_user_configured_rust_channel = match rust_channel {
865            Some(channel_) if channel_ == "auto-detect" => {
866                channel = ci_channel.into();
867                true
868            }
869            Some(channel_) => {
870                channel = channel_;
871                true
872            }
873            None => false,
874        };
875
876        let omit_git_hash = rust_omit_git_hash.unwrap_or(channel == "dev");
877
878        let rust_info = git_info(&exec_ctx, omit_git_hash, &src);
879
880        if !is_user_configured_rust_channel && rust_info.is_from_tarball() {
881            channel = ci_channel.into();
882        }
883
884        // FIXME(#133381): alt rustc builds currently do *not* have rustc debug assertions
885        // enabled. We should not download a CI alt rustc if we need rustc to have debug
886        // assertions (e.g. for crashes test suite). This can be changed once something like
887        // [Enable debug assertions on alt
888        // builds](https://github.com/rust-lang/rust/pull/131077) lands.
889        //
890        // Note that `rust.debug = true` currently implies `rust.debug-assertions = true`!
891        //
892        // This relies also on the fact that the global default for `download-rustc` will be
893        // `false` if it's not explicitly set.
894        let debug_assertions_requested = matches!(rust_rustc_debug_assertions, Some(true))
895            || (matches!(rust_debug, Some(true))
896                && !matches!(rust_rustc_debug_assertions, Some(false)));
897
898        if debug_assertions_requested
899            && let Some(ref opt) = rust_download_rustc
900            && opt.is_string_or_true()
901        {
902            eprintln!(
903                "WARN: currently no CI rustc builds have rustc debug assertions \
904                        enabled. Please either set `rust.debug-assertions` to `false` if you \
905                        want to use download CI rustc or set `rust.download-rustc` to `false`."
906            );
907        }
908
909        let mut download_rustc_commit =
910            download_ci_rustc_commit(&dwn_ctx, &rust_info, rust_download_rustc, llvm_assertions);
911
912        if debug_assertions_requested && download_rustc_commit.is_some() {
913            eprintln!(
914                "WARN: `rust.debug-assertions = true` will prevent downloading CI rustc as alt CI \
915                rustc is not currently built with debug assertions."
916            );
917            // We need to put this later down_ci_rustc_commit.
918            download_rustc_commit = None;
919        }
920
921        // We need to override `rust.channel` if it's manually specified when using the CI rustc.
922        // This is because if the compiler uses a different channel than the one specified in bootstrap.toml,
923        // tests may fail due to using a different channel than the one used by the compiler during tests.
924        if let Some(commit) = &download_rustc_commit
925            && is_user_configured_rust_channel
926        {
927            println!(
928                "WARNING: `rust.download-rustc` is enabled. The `rust.channel` option will be overridden by the CI rustc's channel."
929            );
930
931            channel =
932                read_file_by_commit(&dwn_ctx, &rust_info, Path::new("src/ci/channel"), commit)
933                    .trim()
934                    .to_owned();
935        }
936
937        if build_npm.is_some() {
938            println!(
939                "WARNING: `build.npm` set in bootstrap.toml, this option no longer has any effect. . Use `build.yarn` instead to provide a path to a `yarn` binary."
940            );
941        }
942
943        let mut lld_enabled = rust_lld_enabled.unwrap_or(false);
944
945        // Linux targets for which the user explicitly overrode the used linker
946        let mut targets_with_user_linker_override = HashSet::new();
947
948        if let Some(t) = toml_target {
949            for (triple, cfg) in t {
950                let TomlTarget {
951                    cc: target_cc,
952                    cxx: target_cxx,
953                    ar: target_ar,
954                    ranlib: target_ranlib,
955                    default_linker: target_default_linker,
956                    default_linker_linux_override: target_default_linker_linux_override,
957                    linker: target_linker,
958                    split_debuginfo: target_split_debuginfo,
959                    llvm_config: target_llvm_config,
960                    llvm_has_rust_patches: target_llvm_has_rust_patches,
961                    llvm_filecheck: target_llvm_filecheck,
962                    llvm_libunwind: target_llvm_libunwind,
963                    sanitizers: target_sanitizers,
964                    profiler: target_profiler,
965                    rpath: target_rpath,
966                    rustflags: target_rustflags,
967                    crt_static: target_crt_static,
968                    musl_root: target_musl_root,
969                    musl_libdir: target_musl_libdir,
970                    wasi_root: target_wasi_root,
971                    qemu_rootfs: target_qemu_rootfs,
972                    no_std: target_no_std,
973                    codegen_backends: target_codegen_backends,
974                    runner: target_runner,
975                    optimized_compiler_builtins: target_optimized_compiler_builtins,
976                    allocator: target_allocator,
977                    jemalloc: target_jemalloc,
978                } = cfg;
979
980                let mut target = Target::from_triple(&triple);
981
982                if target_default_linker_linux_override.is_some() {
983                    targets_with_user_linker_override.insert(triple.clone());
984                }
985
986                let default_linker_linux_override = match target_default_linker_linux_override {
987                    Some(DefaultLinuxLinkerOverride::SelfContainedLldCc) => {
988                        if rust_default_linker.is_some() {
989                            panic!(
990                                "cannot set both `default-linker` and `default-linker-linux` for target `{triple}`"
991                            );
992                        }
993                        if !triple.contains("linux-gnu") {
994                            panic!(
995                                "`default-linker-linux` can only be set for Linux GNU targets, not for `{triple}`"
996                            );
997                        }
998                        if !lld_enabled {
999                            panic!(
1000                                "Trying to override the default Linux linker for `{triple}` to be self-contained LLD, but LLD is not being built. Enable it with rust.lld = true."
1001                            );
1002                        }
1003                        DefaultLinuxLinkerOverride::SelfContainedLldCc
1004                    }
1005                    Some(DefaultLinuxLinkerOverride::Off) => DefaultLinuxLinkerOverride::Off,
1006                    None => DefaultLinuxLinkerOverride::default(),
1007                };
1008
1009                if let Some(ref s) = target_llvm_config {
1010                    if download_rustc_commit.is_some() && triple == *host_target.triple {
1011                        panic!(
1012                            "setting llvm_config for the host is incompatible with download-rustc"
1013                        );
1014                    }
1015                    target.llvm_config = Some(src.join(s));
1016                }
1017                if let Some(patches) = target_llvm_has_rust_patches {
1018                    assert!(
1019                        build_submodules == Some(false) || target_llvm_config.is_some(),
1020                        "use of `llvm-has-rust-patches` is restricted to cases where either submodules are disabled or llvm-config been provided"
1021                    );
1022                    target.llvm_has_rust_patches = Some(patches);
1023                }
1024                if let Some(ref s) = target_llvm_filecheck {
1025                    target.llvm_filecheck = Some(src.join(s));
1026                }
1027                target.llvm_libunwind = target_llvm_libunwind.as_ref().map(|v| {
1028                    v.parse().unwrap_or_else(|_| {
1029                        panic!("failed to parse target.{triple}.llvm-libunwind")
1030                    })
1031                });
1032                if let Some(s) = target_no_std {
1033                    target.no_std = s;
1034                }
1035                target.cc = target_cc.map(PathBuf::from);
1036                target.cxx = target_cxx.map(PathBuf::from);
1037                target.ar = target_ar.map(PathBuf::from);
1038                target.ranlib = target_ranlib.map(PathBuf::from);
1039                target.linker = target_linker.map(PathBuf::from);
1040                target.crt_static = target_crt_static;
1041                target.default_linker = target_default_linker;
1042                target.default_linker_linux_override = default_linker_linux_override;
1043                target.musl_root = target_musl_root.map(PathBuf::from);
1044                target.musl_libdir = target_musl_libdir.map(PathBuf::from);
1045                target.wasi_root = target_wasi_root.map(PathBuf::from);
1046                target.qemu_rootfs = target_qemu_rootfs.map(PathBuf::from);
1047                target.runner = target_runner;
1048                target.sanitizers = target_sanitizers;
1049                target.profiler = target_profiler;
1050                target.rpath = target_rpath;
1051                target.rustflags = target_rustflags.unwrap_or_default();
1052                target.optimized_compiler_builtins = target_optimized_compiler_builtins;
1053                target.allocator = reconcile_jemalloc(
1054                    target_jemalloc,
1055                    target_allocator,
1056                    &format!("target.{triple}"),
1057                    &format!("target.{triple}"),
1058                );
1059                if let Some(backends) = target_codegen_backends {
1060                    target.codegen_backends =
1061                        Some(parse_codegen_backends(backends, &format!("target.{triple}")))
1062                }
1063
1064                target.split_debuginfo = target_split_debuginfo.as_ref().map(|v| {
1065                    v.parse().unwrap_or_else(|_| {
1066                        panic!("invalid value for target.{triple}.split-debuginfo")
1067                    })
1068                });
1069
1070                target_config.insert(TargetSelection::from_user(&triple), target);
1071            }
1072        }
1073
1074        let llvm_ci_mode = parse_download_ci_llvm(llvm_download_ci_llvm);
1075
1076        // Sanity checks
1077        match llvm_ci_mode {
1078            LlvmCiMode::DownloadIfUnchanged => {
1079                if rust_info.is_from_tarball() {
1080                    // Git is needed for running "if-unchanged" logic.
1081                    panic!("ERROR: 'if-unchanged' is only compatible with Git managed sources.");
1082                }
1083            }
1084            LlvmCiMode::Download => {
1085                if cfg!(not(test))
1086                    && ci_env.is_running_in_ci()
1087                    && CiEnv::is_rust_lang_managed_ci_job()
1088                {
1089                    // On rust-lang CI, we must always rebuild LLVM if there were any modifications to it
1090                    panic!(
1091                        "`llvm.download-ci-llvm` cannot be set to `true` on CI. Use `if-unchanged` instead."
1092                    );
1093                }
1094            }
1095            LlvmCiMode::BuildLocally => {
1096                if download_rustc_commit.is_some() {
1097                    panic!(
1098                        "`llvm.download-ci-llvm` cannot be set to `false` if `rust.download-rustc` is set to `true` or `if-unchanged`."
1099                    );
1100                }
1101            }
1102        }
1103
1104        if llvm_ci_mode.requests_download_from_ci() {
1105            let warn = |option: &str| {
1106                println!(
1107                    "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build."
1108                );
1109                println!(
1110                    "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false."
1111                );
1112            };
1113
1114            if llvm_static_libstdcpp.is_some() {
1115                warn("static-libstdcpp");
1116            }
1117
1118            if llvm_link_shared.is_some() {
1119                warn("link-shared");
1120            }
1121
1122            // FIXME(#129153): instead of all the ad-hoc `download-ci-llvm` checks that follow,
1123            // use the `builder-config` present in tarballs since #128822 to compare the local
1124            // config to the ones used to build the LLVM artifacts on CI, and only notify users
1125            // if they've chosen a different value.
1126
1127            if llvm_libzstd.is_some() {
1128                println!(
1129                    "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \
1130                    like almost all `llvm.*` options, will be ignored and set by the LLVM CI \
1131                    artifacts builder config."
1132                );
1133                println!(
1134                    "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false."
1135                );
1136            }
1137        }
1138
1139        let is_host_system_llvm =
1140            target_config.get(&host_target).and_then(|c| c.llvm_config.as_ref()).is_some();
1141
1142        for (target, linker_override) in default_linux_linker_overrides(&channel) {
1143            // If the user overrode the default Linux linker, do not apply bootstrap defaults
1144            if targets_with_user_linker_override.contains(&target) {
1145                continue;
1146            }
1147
1148            // The rust.lld option is global, and not target specific, so if we enable it, it will
1149            // be applied to all targets being built.
1150            // So we only apply an override if we're building a compiler/host code for the given
1151            // override target.
1152            // Note: we could also make the LLD config per-target, but that would complicate things
1153            if !hosts.contains(&TargetSelection::from_user(&target)) {
1154                continue;
1155            }
1156
1157            let default_linux_linker_override = match linker_override {
1158                DefaultLinuxLinkerOverride::Off => continue,
1159                DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1160                    // If we automatically default to the self-contained LLD linker,
1161                    // we also need to handle the rust.lld option.
1162                    match rust_lld_enabled {
1163                        // If LLD was not enabled explicitly, we enable it, unless LLVM config has
1164                        // been set
1165                        None if !is_host_system_llvm => {
1166                            lld_enabled = true;
1167                            Some(DefaultLinuxLinkerOverride::SelfContainedLldCc)
1168                        }
1169                        None => None,
1170                        // If it was enabled already, we don't need to do anything
1171                        Some(true) => Some(DefaultLinuxLinkerOverride::SelfContainedLldCc),
1172                        // If it was explicitly disabled, we do not apply the
1173                        // linker override
1174                        Some(false) => None,
1175                    }
1176                }
1177            };
1178            if let Some(linker_override) = default_linux_linker_override {
1179                target_config
1180                    .entry(TargetSelection::from_user(&target))
1181                    .or_default()
1182                    .default_linker_linux_override = linker_override;
1183            }
1184        }
1185
1186        if matches!(bootstrap_override_lld, BootstrapOverrideLld::SelfContained)
1187            && !lld_enabled
1188            && flags_stage.unwrap_or(0) > 0
1189        {
1190            panic!(
1191                "Trying to use self-contained lld as a linker, but LLD is not being added to the sysroot. Enable it with rust.lld = true."
1192            );
1193        }
1194
1195        if lld_enabled && is_host_system_llvm {
1196            panic!("Cannot enable LLD with `rust.lld = true` when using external llvm-config.");
1197        }
1198
1199        let download_rustc = download_rustc_commit.is_some();
1200
1201        let stage = match flags_cmd {
1202            Subcommand::Check { .. } | Subcommand::Clippy { .. } | Subcommand::Fix { .. } => {
1203                flags_stage.or(build_check_stage).unwrap_or(1)
1204            }
1205            // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1206            Subcommand::Doc { .. } => {
1207                flags_stage.or(build_doc_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1208            }
1209            Subcommand::Build { .. } => {
1210                flags_stage.or(build_build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1211            }
1212            Subcommand::Test { .. } | Subcommand::Miri { .. } => {
1213                flags_stage.or(build_test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1214            }
1215            Subcommand::Bench { .. } => flags_stage.or(build_bench_stage).unwrap_or(2),
1216            Subcommand::Dist => flags_stage.or(build_dist_stage).unwrap_or(2),
1217            Subcommand::Install => flags_stage.or(build_install_stage).unwrap_or(2),
1218            Subcommand::Perf { .. } => flags_stage.unwrap_or(1),
1219            // Most of the run commands execute bootstrap tools, which don't depend on the compiler.
1220            // Other commands listed here should always use bootstrap tools.
1221            Subcommand::Clean { .. }
1222            | Subcommand::Run { .. }
1223            | Subcommand::Setup { .. }
1224            | Subcommand::Format { .. }
1225            | Subcommand::Vendor { .. } => flags_stage.unwrap_or(0),
1226        };
1227
1228        let local_rebuild = build_local_rebuild.unwrap_or(false);
1229
1230        let check_stage0 = |kind: &str| {
1231            if local_rebuild {
1232                eprintln!("WARNING: running {kind} in stage 0. This might not work as expected.");
1233            } else {
1234                eprintln!(
1235                    "ERROR: cannot {kind} anything on stage 0. Use at least stage 1 or set build.local-rebuild=true and use a stage0 compiler built from in-tree sources."
1236                );
1237                helpers::exit_process(1);
1238            }
1239        };
1240
1241        // Now check that the selected stage makes sense, and if not, print an error and end
1242        match (stage, &flags_cmd) {
1243            (0, Subcommand::Build { .. }) => {
1244                check_stage0("build");
1245            }
1246            (0, Subcommand::Check { .. }) => {
1247                check_stage0("check");
1248            }
1249            (0, Subcommand::Doc { .. }) => {
1250                check_stage0("doc");
1251            }
1252            (0, Subcommand::Clippy { .. }) => {
1253                check_stage0("clippy");
1254            }
1255            (0, Subcommand::Dist) => {
1256                check_stage0("dist");
1257            }
1258            (0, Subcommand::Install) => {
1259                check_stage0("install");
1260            }
1261            (0, Subcommand::Test { .. }) if build_compiletest_allow_stage0 != Some(true) => {
1262                eprintln!(
1263                    "ERROR: cannot test anything on stage 0. Use at least stage 1. If you want to run compiletest with an external stage0 toolchain, enable `build.compiletest-allow-stage0`."
1264                );
1265                helpers::exit_process(1);
1266            }
1267            _ => {}
1268        }
1269
1270        if flags_compile_time_deps && !matches!(flags_cmd, Subcommand::Check { .. }) {
1271            eprintln!("ERROR: Can't use --compile-time-deps with any subcommand other than check.");
1272            helpers::exit_process(1);
1273        }
1274
1275        if matches!(flags_cmd, Subcommand::Fix { .. }) {
1276            eprintln!(
1277                "WARNING: `x fix` is provided on a best-effort basis and does not support all `cargo fix` options correctly."
1278            );
1279        }
1280
1281        // CI should always run stage 2 builds, unless it specifically states otherwise
1282        if cfg!(not(test)) && flags_stage.is_none() && ci_env.is_running_in_ci() {
1283            match flags_cmd {
1284                Subcommand::Test { .. }
1285                | Subcommand::Miri { .. }
1286                | Subcommand::Doc { .. }
1287                | Subcommand::Build { .. }
1288                | Subcommand::Bench { .. }
1289                | Subcommand::Dist
1290                | Subcommand::Install => {
1291                    assert_eq!(
1292                        stage, 2,
1293                        "\
1294x.py was run under CI with an implicit `--stage {stage}`. This is probably wrong and you want stage 2.
1295NOTE: Please add `--stage 2` to your command line, or if you're sure you want to run stage {stage} then add `--stage {stage}` explicitly"
1296                    );
1297                }
1298                Subcommand::Clean { .. }
1299                | Subcommand::Check { .. }
1300                | Subcommand::Clippy { .. }
1301                | Subcommand::Fix { .. }
1302                | Subcommand::Run { .. }
1303                | Subcommand::Setup { .. }
1304                | Subcommand::Format { .. }
1305                | Subcommand::Vendor { .. }
1306                | Subcommand::Perf { .. } => {}
1307            }
1308        }
1309
1310        let with_defaults = |debuginfo_level_specific: Option<_>| {
1311            debuginfo_level_specific.or(rust_debuginfo_level).unwrap_or(
1312                if rust_debug == Some(true) {
1313                    DebuginfoLevel::Limited
1314                } else {
1315                    DebuginfoLevel::None
1316                },
1317            )
1318        };
1319
1320        let ccache = match build_ccache {
1321            Some(StringOrBool::String(s)) => Some(s),
1322            Some(StringOrBool::Bool(true)) => Some("ccache".to_string()),
1323            _ => None,
1324        };
1325
1326        let explicit_stage_from_config = build_test_stage.is_some()
1327            || build_build_stage.is_some()
1328            || build_doc_stage.is_some()
1329            || build_dist_stage.is_some()
1330            || build_install_stage.is_some()
1331            || build_check_stage.is_some()
1332            || build_bench_stage.is_some();
1333
1334        let deny_warnings = match flags_warnings {
1335            Warnings::Deny => true,
1336            Warnings::Warn => false,
1337            Warnings::Default => rust_deny_warnings.unwrap_or(true),
1338        };
1339
1340        let gcc_ci_mode = match gcc_download_ci_gcc {
1341            Some(value) => match value {
1342                true => GccCiMode::DownloadFromCi,
1343                false => GccCiMode::BuildLocally,
1344            },
1345            None => GccCiMode::default(),
1346        };
1347
1348        let targets = flags_target
1349            .map(|TargetSelectionList(targets)| targets)
1350            .or_else(|| {
1351                build_target.map(|t| t.iter().map(|t| TargetSelection::from_user(t)).collect())
1352            })
1353            .unwrap_or_else(|| hosts.clone());
1354
1355        #[allow(clippy::map_identity)]
1356        let skip = flags_skip
1357            .into_iter()
1358            .chain(flags_exclude)
1359            .chain(build_exclude.unwrap_or_default())
1360            .map(|p| {
1361                // Never return top-level path here as it would break `--skip`
1362                // logic on rustc's internal test framework which is utilized by compiletest.
1363                #[cfg(windows)]
1364                {
1365                    PathBuf::from(p.to_string_lossy().replace('/', "\\"))
1366                }
1367                #[cfg(not(windows))]
1368                {
1369                    p
1370                }
1371            })
1372            .collect();
1373
1374        let cargo_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/cargo"));
1375        let clippy_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/clippy"));
1376        let in_tree_gcc_info = git_info(&exec_ctx, false, &src.join("src/gcc"));
1377        let in_tree_llvm_info = git_info(&exec_ctx, false, &src.join("src/llvm-project"));
1378        let in_tree_tpde_info = git_info(&exec_ctx, false, &src.join("src/tpde"));
1379        let enzyme_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/enzyme"));
1380        let miri_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/miri"));
1381        let rust_analyzer_info =
1382            git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rust-analyzer"));
1383        let rustfmt_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rustfmt"));
1384
1385        let optimized_compiler_builtins =
1386            build_optimized_compiler_builtins.unwrap_or(if channel == "dev" {
1387                CompilerBuiltins::BuildRustOnly
1388            } else {
1389                CompilerBuiltins::BuildLLVMFuncs
1390            });
1391        let vendor = build_vendor.unwrap_or(
1392            rust_info.is_from_tarball()
1393                && src.join("vendor").exists()
1394                && src.join(".cargo/config.toml").exists(),
1395        );
1396        let verbose_tests = rust_verbose_tests.unwrap_or(exec_ctx.is_verbose());
1397
1398        let record_failed_tests_path =
1399            out.join(build_record_failed_tests_path.unwrap_or_else(|| "failed-tests".to_string()));
1400
1401        let paths = {
1402            let mut paths = Vec::new();
1403            if flags_cmd.rerun() {
1404                paths = collect_previously_failed_tests(&record_failed_tests_path);
1405            } else {
1406                paths.extend(flags_paths);
1407            }
1408            paths
1409        };
1410
1411        // If we're building with ThinLTO on, by default we want to link
1412        // to LLVM shared, to avoid re-doing ThinLTO (which happens in
1413        // the link step) with each stage.
1414        let llvm_link_shared = llvm_link_shared.or(llvm_thin_lto.unwrap_or(false).then_some(true));
1415
1416        Config {
1417            // tidy-alphabetical-start
1418            allocator: reconcile_jemalloc(rust_jemalloc, build_allocator, "rust", "build"),
1419            android_ndk: build_android_ndk,
1420            backtrace: rust_backtrace.unwrap_or(true),
1421            backtrace_on_ice: rust_backtrace_on_ice.unwrap_or(false),
1422            bindir: install_bindir.map(PathBuf::from).unwrap_or("bin".into()),
1423            bootstrap_cache_path: build_bootstrap_cache_path,
1424            bootstrap_override_lld,
1425            bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
1426            cargo_info,
1427            cargo_native_static: build_cargo_native_static.unwrap_or(false),
1428            cargo_pgo: pgo_cargo,
1429            ccache,
1430            change_id: toml_change_id.inner,
1431            channel,
1432            ci_env,
1433            clippy_info,
1434            clippy_pgo: pgo_clippy,
1435            cmd: flags_cmd,
1436            codegen_tests: rust_codegen_tests.unwrap_or(true),
1437            color: flags_color,
1438            compile_time_deps: flags_compile_time_deps,
1439            compiler_docs: build_compiler_docs.unwrap_or(false),
1440            compiletest_allow_stage0: build_compiletest_allow_stage0.unwrap_or(false),
1441            compiletest_diff_tool: build_compiletest_diff_tool,
1442            config: toml_path,
1443            control_flow_guard: rust_control_flow_guard.unwrap_or(false),
1444            cranelift_pgo: pgo_cranelift,
1445            datadir: install_datadir.map(PathBuf::from),
1446            deny_warnings,
1447            description: build_description,
1448            dist_compression_formats,
1449            dist_compression_profile: dist_compression_profile.unwrap_or("fast".into()),
1450            dist_include_mingw_linker: dist_include_mingw_linker.unwrap_or(true),
1451            dist_sign_folder: dist_sign_folder.map(PathBuf::from),
1452            dist_upload_addr,
1453            dist_vendor: dist_vendor.unwrap_or_else(|| {
1454                // If we're building from git or tarball sources, enable it by default.
1455                rust_info.is_managed_git_subrepository() || rust_info.is_from_tarball()
1456            }),
1457            docdir: install_docdir.map(PathBuf::from),
1458            docs: build_docs.unwrap_or(true),
1459            docs_minification: build_docs_minification.unwrap_or(true),
1460            download_rustc_commit,
1461            dump_bootstrap_shims: flags_dump_bootstrap_shims,
1462            ehcont_guard: rust_ehcont_guard.unwrap_or(false),
1463            enable_bolt_settings: flags_enable_bolt_settings,
1464            enzyme_info,
1465            exec_ctx,
1466            explicit_stage_from_cli: flags_stage.is_some(),
1467            explicit_stage_from_config,
1468            extended: build_extended.unwrap_or(false),
1469            external_cargo: build_cargo,
1470            external_cargo_clippy: build_cargo_clippy,
1471            external_rustc: build_rustc,
1472            external_rustdoc: build_rustdoc,
1473            external_rustfmt: build_rustfmt,
1474            free_args: flags_free_args,
1475            full_bootstrap: build_full_bootstrap.unwrap_or(false),
1476            gcc_ci_mode,
1477            gdb: build_gdb,
1478            host_target,
1479            hosts,
1480            in_tree_gcc_info,
1481            in_tree_llvm_info,
1482            in_tree_tpde_info,
1483            include_default_paths: flags_include_default_paths,
1484            incremental: flags_incremental || rust_incremental == Some(true),
1485            jobs: Some(threads_from_config(flags_jobs.or(build_jobs).unwrap_or(0))),
1486            json_output: flags_json_output,
1487            keep_stage: flags_keep_stage,
1488            keep_stage_std: flags_keep_stage_std,
1489            libdir: install_libdir.map(PathBuf::from),
1490            libgccjit_libs_dir: gcc_libgccjit_libs_dir,
1491            library_docs_private_items: build_library_docs_private_items.unwrap_or(false),
1492            lld_enabled,
1493            lldb: build_lldb,
1494            llvm_allow_old_toolchain: llvm_allow_old_toolchain.unwrap_or(false),
1495            llvm_assertions,
1496            llvm_bitcode_linker_enabled: rust_llvm_bitcode_linker.unwrap_or(false),
1497            llvm_build_config: llvm_build_config.clone().unwrap_or(Default::default()),
1498            llvm_cflags,
1499            llvm_ci_mode,
1500            llvm_clang: llvm_clang.unwrap_or(false),
1501            llvm_clang_cl,
1502            llvm_cxxflags,
1503            llvm_enable_warnings: llvm_enable_warnings.unwrap_or(false),
1504            llvm_enzyme: llvm_enzyme.unwrap_or(false),
1505            llvm_experimental_targets,
1506            llvm_ldflags,
1507            llvm_libunwind_default: rust_llvm_libunwind
1508                .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")),
1509            llvm_libzstd: llvm_libzstd.unwrap_or(false),
1510            llvm_link_jobs,
1511            llvm_link_shared,
1512            llvm_offload: llvm_offload.unwrap_or(false),
1513            llvm_optimize: llvm_optimize.unwrap_or(true),
1514            llvm_pgo: pgo_llvm,
1515            llvm_plugins: llvm_plugin.unwrap_or(false),
1516            llvm_polly: llvm_polly.unwrap_or(false),
1517            llvm_release_debuginfo: llvm_release_debuginfo.unwrap_or(false),
1518            llvm_static_stdcpp: llvm_static_libstdcpp.unwrap_or(false),
1519            llvm_targets,
1520            llvm_tests: llvm_tests.unwrap_or(false),
1521            llvm_thin_lto: llvm_thin_lto.unwrap_or(false),
1522            llvm_tools_enabled: rust_llvm_tools.unwrap_or(true),
1523            llvm_tpde: llvm_tpde.unwrap_or(false),
1524            llvm_use_libcxx: llvm_use_libcxx.unwrap_or(false),
1525            llvm_use_linker,
1526            llvm_version_suffix,
1527            local_rebuild,
1528            locked_deps: build_locked_deps.unwrap_or(false),
1529            low_priority: build_low_priority.unwrap_or(true),
1530            mandir: install_mandir.map(PathBuf::from),
1531            miri_info,
1532            musl_root: rust_musl_root.map(PathBuf::from),
1533            ninja_in_file: llvm_ninja.unwrap_or(true),
1534            nodejs: build_nodejs.map(PathBuf::from),
1535            offload_clang_dir: offload_clang_dir.map(PathBuf::from),
1536            omit_git_hash,
1537            on_fail: flags_on_fail,
1538            optimized_compiler_builtins,
1539            out,
1540            patch_binaries_for_nix: build_patch_binaries_for_nix,
1541            path_modification_cache,
1542            paths,
1543            prefix: install_prefix.map(PathBuf::from),
1544            print_step_rusage: build_print_step_rusage.unwrap_or(false),
1545            print_step_timings: build_print_step_timings.unwrap_or(false),
1546            profiler: build_profiler.unwrap_or(false),
1547            python: build_python.map(PathBuf::from),
1548            quiet: flags_quiet,
1549            record_failed_tests_path,
1550            reproducible_artifacts: flags_reproducible_artifact,
1551            reuse: build_reuse.map(PathBuf::from),
1552            rust_analyzer_info,
1553            rust_annotate_moves_size_limit,
1554            rust_break_on_ice: rust_break_on_ice.unwrap_or(true),
1555            rust_codegen_backends: rust_codegen_backends
1556                .map(|backends| parse_codegen_backends(backends, "rust"))
1557                .unwrap_or(vec![CodegenBackendKind::Llvm]),
1558            rust_codegen_units: rust_codegen_units.map(threads_from_config),
1559            rust_codegen_units_std: rust_codegen_units_std.map(threads_from_config),
1560            rust_compress_debuginfo: rust_compress_debuginfo.unwrap_or_default(),
1561            rust_debug_logging: rust_debug_logging
1562                .or(rust_rustc_debug_assertions)
1563                .unwrap_or(rust_debug == Some(true)),
1564            rust_debuginfo_level_rustc: with_defaults(rust_debuginfo_level_rustc),
1565            rust_debuginfo_level_std: with_defaults(rust_debuginfo_level_std),
1566            rust_debuginfo_level_tests: rust_debuginfo_level_tests.unwrap_or(DebuginfoLevel::None),
1567            rust_debuginfo_level_tools: with_defaults(rust_debuginfo_level_tools),
1568            rust_dist_src: dist_src_tarball.unwrap_or_else(|| rust_dist_src.unwrap_or(true)),
1569            rust_frame_pointers: rust_frame_pointers.unwrap_or(false),
1570            rust_info,
1571            rust_lto: rust_lto
1572                .as_deref()
1573                .map(|value| RustcLto::from_str(value).unwrap())
1574                .unwrap_or_default(),
1575            rust_new_symbol_mangling,
1576            rust_optimize: rust_optimize.unwrap_or(RustOptimize::Bool(true)),
1577            rust_optimize_tests: rust_optimize_tests.unwrap_or(true),
1578            rust_overflow_checks: rust_overflow_checks.unwrap_or(rust_debug == Some(true)),
1579            rust_overflow_checks_std: rust_overflow_checks_std
1580                .or(rust_overflow_checks)
1581                .unwrap_or(rust_debug == Some(true)),
1582            rust_parallel_frontend_threads: rust_parallel_frontend_threads.map(threads_from_config),
1583            rust_pgo: pgo_rustc,
1584            rust_randomize_layout: rust_randomize_layout.unwrap_or(false),
1585            rust_remap_debuginfo: rust_remap_debuginfo.unwrap_or(false),
1586            rust_rpath: rust_rpath.unwrap_or(true),
1587            rust_rustflags: rust_rustflags.unwrap_or_default(),
1588            rust_stack_protector,
1589            rust_std_features: rust_std_features
1590                .unwrap_or(BTreeSet::from([String::from("panic-unwind")])),
1591            rust_strip: rust_strip.unwrap_or(false),
1592            rust_thin_lto_import_instr_limit,
1593            rust_validate_mir_opts,
1594            rust_verify_llvm_ir: rust_verify_llvm_ir.unwrap_or(false),
1595            rustc_debug_assertions: rust_rustc_debug_assertions.unwrap_or(rust_debug == Some(true)),
1596            rustc_default_linker: rust_default_linker,
1597            rustc_error_format: flags_rustc_error_format,
1598            rustc_perf_path: build_rustc_perf_path,
1599            rustdoc_pgo: pgo_rustdoc,
1600            rustfmt_info,
1601            sanitizers: build_sanitizers.unwrap_or(false),
1602            save_toolstates: rust_save_toolstates.map(PathBuf::from),
1603            sde: build_sde.map(PathBuf::from),
1604            skip,
1605            skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
1606            src,
1607            stage,
1608            stage0_metadata,
1609            std_debug_assertions: rust_std_debug_assertions
1610                .or(rust_rustc_debug_assertions)
1611                .unwrap_or(rust_debug == Some(true)),
1612            stderr_is_tty: std::io::stderr().is_terminal(),
1613            stdlib_semver_baseline: rust_stdlib_semver_baseline,
1614            stdout_is_tty: std::io::stdout().is_terminal(),
1615            submodules: build_submodules,
1616            sysconfdir: install_sysconfdir.map(PathBuf::from),
1617            target_config,
1618            targets,
1619            test_compare_mode: rust_test_compare_mode.unwrap_or(false),
1620            tidy_extra_checks: build_tidy_extra_checks,
1621            tool: build_tool.unwrap_or_default(),
1622            tools: build_tools,
1623            tools_debug_assertions: rust_tools_debug_assertions
1624                .or(rust_rustc_debug_assertions)
1625                .unwrap_or(rust_debug == Some(true)),
1626            vendor,
1627            verbose_tests,
1628            wasm_panic_unwind_default: wasm_panic_unwind_default.unwrap_or(false),
1629            wasm_proc_macros: wasm_proc_macros.unwrap_or(false),
1630            windows_rc: build_windows_rc.map(PathBuf::from),
1631            yarn: build_yarn.map(PathBuf::from),
1632            // tidy-alphabetical-end
1633        }
1634    }
1635
1636    pub fn dry_run(&self) -> bool {
1637        self.exec_ctx.dry_run()
1638    }
1639
1640    pub fn is_running_on_ci(&self) -> bool {
1641        self.ci_env.is_running_in_ci()
1642    }
1643
1644    pub fn is_explicit_stage(&self) -> bool {
1645        self.explicit_stage_from_cli || self.explicit_stage_from_config
1646    }
1647
1648    pub(crate) fn test_args(&self) -> Vec<&str> {
1649        let mut test_args = match self.cmd {
1650            Subcommand::Test { ref test_args, .. }
1651            | Subcommand::Bench { ref test_args, .. }
1652            | Subcommand::Miri { ref test_args, .. } => {
1653                test_args.iter().flat_map(|s| s.split_whitespace()).collect()
1654            }
1655            _ => vec![],
1656        };
1657        test_args.extend(self.free_args.iter().map(|s| s.as_str()));
1658        test_args
1659    }
1660
1661    pub(crate) fn args(&self) -> Vec<&str> {
1662        let mut args = match self.cmd {
1663            Subcommand::Run { ref args, .. } => {
1664                args.iter().flat_map(|s| s.split_whitespace()).collect()
1665            }
1666            _ => vec![],
1667        };
1668        args.extend(self.free_args.iter().map(|s| s.as_str()));
1669        args
1670    }
1671
1672    /// Returns the content of the given file at a specific commit.
1673    pub(crate) fn read_file_by_commit(&self, file: &Path, commit: &str) -> String {
1674        let dwn_ctx = DownloadContext::from(self);
1675        read_file_by_commit(dwn_ctx, &self.rust_info, file, commit)
1676    }
1677
1678    /// Bootstrap embeds a version number into the name of shared libraries it uploads in CI.
1679    /// Return the version it would have used for the given commit.
1680    pub(crate) fn artifact_version_part(&self, commit: &str) -> String {
1681        let (channel, version) = if self.rust_info.is_managed_git_subrepository() {
1682            let channel =
1683                self.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
1684            let version =
1685                self.read_file_by_commit(Path::new("src/version"), commit).trim().to_owned();
1686            (channel, version)
1687        } else {
1688            let channel = fs::read_to_string(self.src.join("src/ci/channel"));
1689            let version = fs::read_to_string(self.src.join("src/version"));
1690            match (channel, version) {
1691                (Ok(channel), Ok(version)) => {
1692                    (channel.trim().to_owned(), version.trim().to_owned())
1693                }
1694                (channel, version) => {
1695                    let src = self.src.display();
1696                    eprintln!("ERROR: failed to determine artifact channel and/or version");
1697                    eprintln!(
1698                        "HELP: consider using a git checkout or ensure these files are readable"
1699                    );
1700                    if let Err(channel) = channel {
1701                        eprintln!("reading {src}/src/ci/channel failed: {channel:?}");
1702                    }
1703                    if let Err(version) = version {
1704                        eprintln!("reading {src}/src/version failed: {version:?}");
1705                    }
1706                    panic!();
1707                }
1708            }
1709        };
1710
1711        match channel.as_str() {
1712            "stable" => version,
1713            "beta" => channel,
1714            "nightly" => channel,
1715            other => unreachable!("{:?} is not recognized as a valid channel", other),
1716        }
1717    }
1718
1719    /// Try to find the relative path of `bindir`, otherwise return it in full.
1720    pub fn bindir_relative(&self) -> &Path {
1721        let bindir = &self.bindir;
1722        if bindir.is_absolute() {
1723            // Try to make it relative to the prefix.
1724            if let Some(prefix) = &self.prefix
1725                && let Ok(stripped) = bindir.strip_prefix(prefix)
1726            {
1727                return stripped;
1728            }
1729        }
1730        bindir
1731    }
1732
1733    /// Try to find the relative path of `libdir`.
1734    pub fn libdir_relative(&self) -> Option<&Path> {
1735        let libdir = self.libdir.as_ref()?;
1736        if libdir.is_relative() {
1737            Some(libdir)
1738        } else {
1739            // Try to make it relative to the prefix.
1740            libdir.strip_prefix(self.prefix.as_ref()?).ok()
1741        }
1742    }
1743
1744    /// Directory where the extracted `rustc-dev` component is stored.
1745    pub(crate) fn ci_rustc_dir(&self) -> PathBuf {
1746        assert!(self.download_rustc());
1747        self.out.join(self.host_target).join("ci-rustc")
1748    }
1749
1750    /// Return whether we will use a downloaded, pre-compiled version of rustc, or just build from source.
1751    pub(crate) fn download_rustc(&self) -> bool {
1752        self.download_rustc_commit().is_some()
1753    }
1754
1755    pub(crate) fn download_rustc_commit(&self) -> Option<&str> {
1756        static DOWNLOAD_RUSTC: OnceLock<Option<String>> = OnceLock::new();
1757        if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
1758            // avoid trying to actually download the commit
1759            return self.download_rustc_commit.as_deref();
1760        }
1761
1762        DOWNLOAD_RUSTC
1763            .get_or_init(|| match &self.download_rustc_commit {
1764                None => None,
1765                Some(commit) => {
1766                    self.download_ci_rustc(commit);
1767
1768                    let llvm_ci_requested = self.llvm_ci_mode.requests_download_from_ci();
1769                    // CI-rustc can't be used without CI-LLVM. If CI LLVM is requested, but the
1770                    // LLVM submodule has changes, it is an error.
1771                    // FIXME: this whole logic should be refactored to not use
1772                    // `has_changes_from_upstream` explicitly
1773                    if llvm_ci_requested && self.has_changes_from_upstream(LLVM_INVALIDATION_PATHS) {
1774                        // download-ci-rustc should not be used on CI at the moment
1775                        assert!(!self.is_running_on_ci());
1776                        panic!("ERROR: LLVM submodule has changes, `download-rustc` can't be used.");
1777                    }
1778
1779                    if let Some(config_path) = &self.config {
1780                        let ci_config_toml = match self.get_builder_toml("ci-rustc") {
1781                            Ok(ci_config_toml) => ci_config_toml,
1782                            Err(e) if e.to_string().contains("unknown field") => {
1783                                println!("WARNING: CI rustc has some fields that are no longer supported in bootstrap; download-rustc will be disabled.");
1784                                println!("HELP: Consider rebasing to a newer commit if available.");
1785                                return None;
1786                            }
1787                            Err(e) => {
1788                                eprintln!("ERROR: Failed to parse CI rustc bootstrap.toml: {e}");
1789                                helpers::exit_process(2);
1790                            }
1791                        };
1792
1793                        let current_config_toml = Self::get_toml(config_path).unwrap();
1794
1795                        // Check the config compatibility
1796                        // FIXME: this doesn't cover `--set` flags yet.
1797                        let res = check_incompatible_options_for_ci_rustc(
1798                            self.host_target,
1799                            current_config_toml,
1800                            ci_config_toml,
1801                        );
1802
1803                        // Primarily used by CI runners to avoid handling download-rustc incompatible
1804                        // options one by one on shell scripts.
1805                        let disable_ci_rustc_if_incompatible = env::var_os("DISABLE_CI_RUSTC_IF_INCOMPATIBLE")
1806                            .is_some_and(|s| s == "1" || s == "true");
1807
1808                        if disable_ci_rustc_if_incompatible && res.is_err() {
1809                            println!("WARNING: download-rustc is disabled with `DISABLE_CI_RUSTC_IF_INCOMPATIBLE` env.");
1810                            return None;
1811                        }
1812
1813                        res.unwrap();
1814                    }
1815
1816                    Some(commit.clone())
1817                }
1818            })
1819            .as_deref()
1820    }
1821
1822    /// Runs a function if verbosity is greater than 0
1823    pub fn do_if_verbose(&self, f: impl Fn()) {
1824        self.exec_ctx.do_if_verbose(f);
1825    }
1826
1827    pub fn any_sanitizers_to_build(&self) -> bool {
1828        self.target_config
1829            .iter()
1830            .any(|(ts, t)| !ts.is_msvc() && t.sanitizers.unwrap_or(self.sanitizers))
1831    }
1832
1833    pub fn any_profiler_enabled(&self) -> bool {
1834        self.target_config.values().any(|t| matches!(&t.profiler, Some(p) if p.is_string_or_true()))
1835            || self.profiler
1836    }
1837
1838    /// Returns whether or not submodules should be managed by bootstrap.
1839    pub fn submodules(&self) -> bool {
1840        // If not specified in config, the default is to only manage
1841        // submodules if we're currently inside a git repository.
1842        self.submodules.unwrap_or(self.rust_info.is_managed_git_subrepository())
1843    }
1844
1845    pub fn git_config(&self) -> GitConfig<'_> {
1846        GitConfig {
1847            nightly_branch: &self.stage0_metadata.config.nightly_branch,
1848            git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
1849        }
1850    }
1851
1852    /// Given a path to the directory of a submodule, update it.
1853    ///
1854    /// `relative_path` should be relative to the root of the git repository, not an absolute path.
1855    ///
1856    /// This *does not* update the submodule if `bootstrap.toml` explicitly says
1857    /// not to, or if we're not in a git repository (like a plain source
1858    /// tarball). Typically [`crate::core::session::Session::require_submodule`] should be
1859    /// used instead to provide a nice error to the user if the submodule is
1860    /// missing.
1861    #[cfg_attr(
1862        feature = "tracing",
1863        instrument(
1864            level = "trace",
1865            name = "Config::update_submodule",
1866            skip_all,
1867            fields(relative_path = ?relative_path),
1868        ),
1869    )]
1870    pub(crate) fn update_submodule(&self, relative_path: &str) {
1871        let dwn_ctx = DownloadContext::from(self);
1872        update_submodule(dwn_ctx, &self.rust_info, relative_path);
1873    }
1874
1875    /// Returns true if any of the `paths` have been modified locally.
1876    pub fn has_changes_from_upstream(&self, paths: &[&'static str]) -> bool {
1877        let dwn_ctx = DownloadContext::from(self);
1878        has_changes_from_upstream(dwn_ctx, paths)
1879    }
1880
1881    /// Checks whether any of the given paths have been modified w.r.t. upstream.
1882    pub fn check_path_modifications(&self, paths: &[&'static str]) -> PathFreshness {
1883        // Checking path modifications through git can be relatively expensive (>100ms).
1884        // We do not assume that the sources would change during bootstrap's execution,
1885        // so we can cache the results here.
1886        // Note that we do not use a static variable for the cache, because it would cause problems
1887        // in tests that create separate `Config` instances.
1888        self.path_modification_cache
1889            .lock()
1890            .unwrap()
1891            .entry(paths.to_vec())
1892            .or_insert_with(|| {
1893                check_path_modifications(&self.src, &self.git_config(), paths, self.ci_env).unwrap()
1894            })
1895            .clone()
1896    }
1897
1898    pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1899        self.target_config.get(&target).and_then(|t| t.sanitizers).unwrap_or(self.sanitizers)
1900    }
1901
1902    pub fn needs_sanitizer_runtime_built(&self, target: TargetSelection) -> bool {
1903        // MSVC uses the Microsoft-provided sanitizer runtime, but all other runtimes we build.
1904        !target.is_msvc() && self.sanitizers_enabled(target)
1905    }
1906
1907    pub fn profiler_path(&self, target: TargetSelection) -> Option<&str> {
1908        match self.target_config.get(&target)?.profiler.as_ref()? {
1909            StringOrBool::String(s) => Some(s),
1910            StringOrBool::Bool(_) => None,
1911        }
1912    }
1913
1914    pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1915        self.target_config
1916            .get(&target)
1917            .and_then(|t| t.profiler.as_ref())
1918            .map(StringOrBool::is_string_or_true)
1919            .unwrap_or(self.profiler)
1920    }
1921
1922    /// Returns codegen backends that should be:
1923    /// - Built and added to the sysroot when we build the compiler.
1924    /// - Distributed when `x dist` is executed (if the codegen backend has a dist step).
1925    pub fn enabled_codegen_backends(&self, target: TargetSelection) -> &[CodegenBackendKind] {
1926        self.target_config
1927            .get(&target)
1928            .and_then(|cfg| cfg.codegen_backends.as_deref())
1929            .unwrap_or(&self.rust_codegen_backends)
1930    }
1931
1932    /// Returns the codegen backend that should be configured as the *default* codegen backend
1933    /// for a rustc compiled by bootstrap.
1934    pub fn default_codegen_backend(&self, target: TargetSelection) -> &CodegenBackendKind {
1935        // We're guaranteed to have always at least one codegen backend listed.
1936        self.enabled_codegen_backends(target).first().unwrap()
1937    }
1938
1939    pub fn allocator(&self, target: TargetSelection) -> Allocator {
1940        self.target_config
1941            .get(&target)
1942            .and_then(|cfg| cfg.allocator)
1943            .or(self.allocator)
1944            .unwrap_or(Allocator::System)
1945    }
1946
1947    pub fn rpath_enabled(&self, target: TargetSelection) -> bool {
1948        self.target_config.get(&target).and_then(|t| t.rpath).unwrap_or(self.rust_rpath)
1949    }
1950
1951    pub fn optimized_compiler_builtins(&self, target: TargetSelection) -> &CompilerBuiltins {
1952        self.target_config
1953            .get(&target)
1954            .and_then(|t| t.optimized_compiler_builtins.as_ref())
1955            .unwrap_or(&self.optimized_compiler_builtins)
1956    }
1957
1958    pub fn llvm_enabled(&self, target: TargetSelection) -> bool {
1959        self.enabled_codegen_backends(target).contains(&CodegenBackendKind::Llvm)
1960    }
1961
1962    pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1963        self.target_config
1964            .get(&target)
1965            .and_then(|t| t.llvm_libunwind)
1966            .or(self.llvm_libunwind_default)
1967            .unwrap_or(
1968                if target.contains("fuchsia")
1969                    || (target.contains("hexagon") && !target.contains("qurt"))
1970                {
1971                    // Fuchsia and Hexagon Linux use in-tree llvm-libunwind.
1972                    // Hexagon QuRT uses libc_eh from the Hexagon SDK instead.
1973                    LlvmLibunwind::InTree
1974                } else {
1975                    LlvmLibunwind::No
1976                },
1977            )
1978    }
1979
1980    pub fn split_debuginfo(&self, target: TargetSelection) -> SplitDebuginfo {
1981        self.target_config
1982            .get(&target)
1983            .and_then(|t| t.split_debuginfo)
1984            .unwrap_or_else(|| SplitDebuginfo::default_for_platform(target))
1985    }
1986
1987    pub fn compress_debuginfo(&self, target: TargetSelection) -> CompressDebuginfo {
1988        self.target_config
1989            .get(&target)
1990            .and_then(|t| t.compress_debuginfo)
1991            .unwrap_or(self.rust_compress_debuginfo)
1992    }
1993
1994    /// Checks if the given target is the same as the host target.
1995    pub fn is_host_target(&self, target: TargetSelection) -> bool {
1996        self.host_target == target
1997    }
1998
1999    /// Returns `true` if this is our custom, patched, version of LLVM.
2000    ///
2001    /// This does not necessarily imply that we're managing the `llvm-project` submodule.
2002    pub fn is_rust_llvm(&self, llvm: &LlvmOutput, target: TargetSelection) -> bool {
2003        match self.target_config.get(&target) {
2004            // We're using a user-controlled version of LLVM. The user has explicitly told us whether the version has our patches.
2005            // (They might be wrong, but that's not a supported use-case.)
2006            // 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`.
2007            Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
2008            // The user hasn't promised the patches match.
2009            // This only has our patches if it's downloaded from CI or built from source.
2010            _ => match llvm.kind() {
2011                LlvmKind::BuiltLocally | LlvmKind::DownloadedFromCi => true,
2012                LlvmKind::External => false,
2013            },
2014        }
2015    }
2016
2017    pub fn exec_ctx(&self) -> &ExecutionContext {
2018        &self.exec_ctx
2019    }
2020
2021    pub fn git_info(&self, omit_git_hash: bool, dir: &Path) -> GitInfo {
2022        GitInfo::new(omit_git_hash, dir, self)
2023    }
2024}
2025
2026impl AsRef<ExecutionContext> for Config {
2027    fn as_ref(&self) -> &ExecutionContext {
2028        &self.exec_ctx
2029    }
2030}
2031
2032/// Reconciles the deprecated `jemalloc` boolean option with the new
2033/// `allocator` option.
2034///
2035/// Emits a warning if `jemalloc` is set, and an error if *both* `jemalloc` and `allocator` are set.
2036fn reconcile_jemalloc(
2037    jemalloc: Option<bool>,
2038    allocator: Option<Allocator>,
2039    jemalloc_section: &str,
2040    allocator_section: &str,
2041) -> Option<Allocator> {
2042    match (jemalloc, allocator) {
2043        (None, None) => None,
2044        (None, Some(allocator)) => Some(allocator),
2045        (Some(true), None) => {
2046            println!(
2047                "WARNING: The `jemalloc` option is deprecated. \
2048                 Please use `{allocator_section}.allocator = \"jemalloc\"` instead of `{jemalloc_section}.jemalloc = true`",
2049            );
2050            Some(Allocator::Jemalloc)
2051        }
2052        (Some(false), None) => {
2053            println!(
2054                "WARNING: The `jemalloc` option is deprecated. \
2055                 Please use `{allocator_section}.allocator = \"system\"` instead of `{jemalloc_section}.jemalloc = false`",
2056            );
2057            Some(Allocator::System)
2058        }
2059        _ => {
2060            panic!(
2061                "ERROR: `{jemalloc_section}.jemalloc` and `{allocator_section}.allocator` are both set. \
2062                 Please remove the outdated `{jemalloc_section}.jemalloc` directive."
2063            )
2064        }
2065    }
2066}
2067
2068fn compute_src_directory_via_git(exec_ctx: &ExecutionContext) -> Option<PathBuf> {
2069    // Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary,
2070    // running on a completely different machine from where it was compiled.
2071    // NOTE: we cannot support running from outside the repository because the only other path we have available
2072    // is set at compile time, which can be wrong if bootstrap was downloaded rather than compiled locally.
2073    // We still support running outside the repository if we find we aren't in a git directory.
2074
2075    // NOTE: We get a relative path from git (`--show-cdup`) to work around an issue on MSYS/mingw.
2076    // If we used an absolute path, and end up using MSYS's git rather than git-for-windows, we would
2077    // get a unix-y MSYS path. But as bootstrap has already been (kinda-cross-)compiled to Windows land,
2078    // we require a normal Windows path.
2079
2080    // Ask git to print the path of the repository root, relative to the working directory.
2081    // If the working directory is the repo root, the output will be empty, which is fine.
2082    let mut cmd = helpers::git(None);
2083    cmd.arg("rev-parse").arg("--show-cdup");
2084    // Discard stderr because we expect this to fail when building from a tarball.
2085    let output = cmd.allow_failure().run_capture_stdout(exec_ctx);
2086    if output.is_failure() {
2087        // We're building from a tarball, not git sources.
2088        // We don't support pre-downloaded bootstrap in this case.
2089        return None;
2090    }
2091
2092    // We need to canonicalize this path to make sure it uses backslashes instead of forward slashes,
2093    // and to resolve any relative components.
2094    let stdout = output.stdout();
2095    let relative_root = stdout.trim();
2096    let git_root = env::current_dir().unwrap().join(relative_root).canonicalize().unwrap();
2097
2098    // Bootstrap is quite bad at handling /? in front of paths
2099    let git_root = match git_root.to_str().unwrap().strip_prefix("\\\\?\\") {
2100        Some(p) => PathBuf::from(p),
2101        None => git_root,
2102    };
2103
2104    // If this doesn't have at least `./src/stage0`, we guessed wrong. This can happen when,
2105    // for example, the build directory is inside of another unrelated git directory.
2106    // In that case keep the original `CARGO_MANIFEST_DIR` handling.
2107    //
2108    // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside
2109    // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1.
2110    if git_root.join("src").join("stage0").exists() { Some(git_root) } else { None }
2111}
2112
2113#[derive(Clone)]
2114pub enum LlvmPgoGenerationMode {
2115    /// Enable PGO instrumentation that will write profiles into a default path.
2116    Implicit,
2117    /// Enable PGO instrumentation that will write profiles into the specified directory.
2118    Directory(PathBuf),
2119}
2120
2121#[derive(Clone)]
2122pub struct LlvmPgoConfig {
2123    pub use_profile: Option<PathBuf>,
2124    pub generate_profile: Option<LlvmPgoGenerationMode>,
2125}
2126
2127/// Loads bootstrap TOML config and returns the config together with a path from where
2128/// it was loaded.
2129/// `src` is the source root directory, and `config_path` is an optionally provided path to the
2130/// config.
2131fn load_toml_config(
2132    src: &Path,
2133    config_path: Option<PathBuf>,
2134    get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2135) -> (TomlConfig, Option<PathBuf>) {
2136    // Locate the configuration file using the following priority (first match wins):
2137    // 1. `--config <path>` (explicit flag)
2138    // 2. `RUST_BOOTSTRAP_CONFIG` environment variable
2139    // 3. `./bootstrap.toml` (local file)
2140    // 4. `<root>/bootstrap.toml`
2141    // 5. `./config.toml` (fallback for backward compatibility)
2142    // 6. `<root>/config.toml`
2143    let toml_path = config_path.or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
2144    let using_default_path = toml_path.is_none();
2145    let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml"));
2146
2147    if using_default_path && !toml_path.exists() {
2148        toml_path = src.join(PathBuf::from("bootstrap.toml"));
2149        if !toml_path.exists() {
2150            toml_path = PathBuf::from("config.toml");
2151            if !toml_path.exists() {
2152                toml_path = src.join(PathBuf::from("config.toml"));
2153            }
2154        }
2155    }
2156
2157    // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
2158    // but not if `bootstrap.toml` hasn't been created.
2159    if !using_default_path || toml_path.exists() {
2160        let path = Some(if cfg!(not(test)) {
2161            toml_path = toml_path.canonicalize().unwrap();
2162            toml_path.clone()
2163        } else {
2164            toml_path.clone()
2165        });
2166        (get_toml(&toml_path).unwrap_or_else(|e| bad_config(&toml_path, e)), path)
2167    } else {
2168        (TomlConfig::default(), None)
2169    }
2170}
2171
2172fn postprocess_toml(
2173    toml: &mut TomlConfig,
2174    src_dir: &Path,
2175    toml_path: Option<PathBuf>,
2176    exec_ctx: &ExecutionContext,
2177    override_set: &[String],
2178    get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2179) {
2180    let git_info = GitInfo::new(false, src_dir, exec_ctx);
2181
2182    if git_info.is_from_tarball() && toml.profile.is_none() {
2183        toml.profile = Some("dist".into());
2184    }
2185
2186    // Reverse the list to ensure the last added config extension remains the most dominant.
2187    // For example, given ["a.toml", "b.toml"], "b.toml" should take precedence over "a.toml".
2188    //
2189    // This must be handled before applying the `profile` since `include`s should always take
2190    // precedence over `profile`s.
2191    for include_path in toml.include.clone().unwrap_or_default().iter().rev() {
2192        let include_path = toml_path
2193            .as_ref()
2194            .expect("include found in default TOML config")
2195            .parent()
2196            .unwrap()
2197            .join(include_path);
2198
2199        let included_toml =
2200            get_toml(&include_path).unwrap_or_else(|e| bad_config(&include_path, e));
2201        toml.merge(
2202            Some(include_path),
2203            &mut Default::default(),
2204            included_toml,
2205            ReplaceOpt::IgnoreDuplicate,
2206        );
2207    }
2208
2209    if let Some(include) = &toml.profile {
2210        // Allows creating alias for profile names, allowing
2211        // profiles to be renamed while maintaining back compatibility
2212        // Keep in sync with `profile_aliases` in bootstrap.py
2213        let profile_aliases = HashMap::from([("user", "dist")]);
2214        let include = match profile_aliases.get(include.as_str()) {
2215            Some(alias) => alias,
2216            None => include.as_str(),
2217        };
2218        let mut include_path = PathBuf::from(src_dir);
2219        include_path.push("src");
2220        include_path.push("bootstrap");
2221        include_path.push("defaults");
2222        include_path.push(format!("bootstrap.{include}.toml"));
2223        let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
2224            eprintln!(
2225                "ERROR: Failed to parse default config profile at '{}': {e}",
2226                include_path.display()
2227            );
2228            helpers::exit_process(2);
2229        });
2230        toml.merge(
2231            Some(include_path),
2232            &mut Default::default(),
2233            included_toml,
2234            ReplaceOpt::IgnoreDuplicate,
2235        );
2236    }
2237
2238    let mut override_toml = TomlConfig::default();
2239    for option in override_set.iter() {
2240        fn get_table(option: &str) -> Result<TomlConfig, toml::de::Error> {
2241            toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table))
2242        }
2243
2244        let mut err = match get_table(option) {
2245            Ok(v) => {
2246                override_toml.merge(None, &mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate);
2247                continue;
2248            }
2249            Err(e) => e,
2250        };
2251        // We want to be able to set string values without quotes,
2252        // like in `configure.py`. Try adding quotes around the right hand side
2253        if let Some((key, value)) = option.split_once('=')
2254            && !value.contains('"')
2255        {
2256            match get_table(&format!(r#"{key}="{value}""#)) {
2257                Ok(v) => {
2258                    override_toml.merge(
2259                        None,
2260                        &mut Default::default(),
2261                        v,
2262                        ReplaceOpt::ErrorOnDuplicate,
2263                    );
2264                    continue;
2265                }
2266                Err(e) => err = e,
2267            }
2268        }
2269        eprintln!("failed to parse override `{option}`: `{err}");
2270        helpers::exit_process(2);
2271    }
2272    toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override);
2273}
2274
2275/// Check that the version of an externally provided rustc/cargo is either the same or 1 version
2276/// older than the in-tree version.
2277fn check_external_binary_version(
2278    program_path: &Path,
2279    component_name: &'static str,
2280    src_dir: &Path,
2281    exec_ctx: &ExecutionContext,
2282) {
2283    if cfg!(test) || exec_ctx.dry_run() {
2284        return;
2285    }
2286
2287    let output = command(program_path).arg("--version").run_capture_stdout(exec_ctx).stdout();
2288    let mut output = output.lines().next().unwrap().split(' ');
2289
2290    let name = output.next().unwrap();
2291    if name != component_name {
2292        fail(&format!(
2293            "Expected to find {component_name} at {} but it claims to be {name}",
2294            program_path.display()
2295        ));
2296    }
2297
2298    let binary_version =
2299        semver::Version::parse(output.next().unwrap().split('-').next().unwrap().trim()).unwrap();
2300    let source_version =
2301        semver::Version::parse(fs::read_to_string(src_dir.join("src/version")).unwrap().trim())
2302            .unwrap();
2303    if !(source_version == binary_version
2304        || (source_version.major == binary_version.major
2305            && (source_version.minor == binary_version.minor
2306                || source_version.minor == binary_version.minor + 1)))
2307    {
2308        let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1);
2309        fail(&format!(
2310            "Unexpected {component_name} version: {binary_version}, we should use {prev_version}/{source_version} to build source with {source_version}"
2311        ));
2312    }
2313}
2314
2315fn print_rustc_modifications(
2316    dwn_ctx: &DownloadContext<'_>,
2317    if_unchanged: bool,
2318    mut modifications: Vec<PathBuf>,
2319) -> Option<()> {
2320    if !dwn_ctx.exec_ctx.is_verbose() {
2321        modifications.retain(|path| !path.starts_with("compiler"));
2322    }
2323    if modifications.is_empty() {
2324        // only compiler changes; still force a rebuild but don't say why.
2325        eprintln!(
2326            "skipping rustc download with `download-rustc = 'if-unchanged'` due to local changes"
2327        );
2328        return None;
2329    }
2330
2331    eprintln!(
2332        "NOTE: detected {} modifications that could affect a build of rustc",
2333        modifications.len()
2334    );
2335    for file in modifications.iter().take(10) {
2336        eprintln!("- {}", file.display());
2337    }
2338    if modifications.len() > 10 {
2339        eprintln!("- ... and {} more", modifications.len() - 10);
2340    }
2341
2342    if if_unchanged {
2343        eprintln!("skipping rustc download due to `download-rustc = 'if-unchanged'`");
2344        None
2345    } else {
2346        eprintln!("downloading unconditionally due to `download-rustc = true`");
2347        Some(())
2348    }
2349}
2350
2351pub fn download_ci_rustc_commit<'a>(
2352    dwn_ctx: impl AsRef<DownloadContext<'a>>,
2353    rust_info: &channel::GitInfo,
2354    download_rustc: Option<StringOrBool>,
2355    llvm_assertions: bool,
2356) -> Option<String> {
2357    let dwn_ctx = dwn_ctx.as_ref();
2358
2359    if !is_download_ci_available(&dwn_ctx.host_target.triple, llvm_assertions) {
2360        return None;
2361    }
2362
2363    // If `download-rustc` is not set, default to rebuilding.
2364    let if_unchanged = match download_rustc {
2365        // Globally default `download-rustc` to `false`, because some contributors don't use
2366        // profiles for reasons such as:
2367        // - They need to seamlessly switch between compiler/library work.
2368        // - They don't want to use compiler profile because they need to override too many
2369        //   things and it's easier to not use a profile.
2370        None | Some(StringOrBool::Bool(false)) => return None,
2371        Some(StringOrBool::Bool(true)) => false,
2372        Some(StringOrBool::String(s)) if s == "if-unchanged" => {
2373            if !rust_info.is_managed_git_subrepository() {
2374                println!(
2375                    "ERROR: `download-rustc=if-unchanged` is only compatible with Git managed sources."
2376                );
2377                helpers::exit_process(1);
2378            }
2379
2380            true
2381        }
2382        Some(StringOrBool::String(other)) => {
2383            panic!("unrecognized option for download-rustc: {other}")
2384        }
2385    };
2386
2387    let commit = if rust_info.is_managed_git_subrepository() {
2388        // Look for a version to compare to based on the current commit.
2389        // Only commits merged by bors will have CI artifacts.
2390        let freshness = check_path_modifications_(dwn_ctx, RUSTC_IF_UNCHANGED_ALLOWED_PATHS);
2391        dwn_ctx.exec_ctx.do_if_verbose(|| {
2392            eprintln!("rustc freshness: {freshness:?}");
2393        });
2394        match freshness {
2395            PathFreshness::LastModifiedUpstream { upstream } => upstream,
2396            PathFreshness::HasLocalModifications { upstream, modifications } => {
2397                if dwn_ctx.is_running_on_ci() {
2398                    eprintln!("CI rustc commit matches with HEAD and we are in CI.");
2399                    eprintln!(
2400                        "`rustc.download-ci` functionality will be skipped as artifacts are not available."
2401                    );
2402                    return None;
2403                }
2404
2405                print_rustc_modifications(dwn_ctx, if_unchanged, modifications)?;
2406                upstream
2407            }
2408            PathFreshness::MissingUpstream => {
2409                eprintln!("No upstream commit found");
2410                return None;
2411            }
2412        }
2413    } else {
2414        channel::read_commit_info_file(dwn_ctx.src)
2415            .map(|info| info.sha.trim().to_owned())
2416            .expect("git-commit-info is missing in the project root")
2417    };
2418
2419    Some(commit)
2420}
2421
2422pub fn check_path_modifications_<'a>(
2423    dwn_ctx: impl AsRef<DownloadContext<'a>>,
2424    paths: &[&'static str],
2425) -> PathFreshness {
2426    let dwn_ctx = dwn_ctx.as_ref();
2427    // Checking path modifications through git can be relatively expensive (>100ms).
2428    // We do not assume that the sources would change during bootstrap's execution,
2429    // so we can cache the results here.
2430    // Note that we do not use a static variable for the cache, because it would cause problems
2431    // in tests that create separate `Config` instances.
2432    dwn_ctx
2433        .path_modification_cache
2434        .lock()
2435        .unwrap()
2436        .entry(paths.to_vec())
2437        .or_insert_with(|| {
2438            check_path_modifications(
2439                dwn_ctx.src,
2440                &git_config(dwn_ctx.stage0_metadata),
2441                paths,
2442                dwn_ctx.ci_env,
2443            )
2444            .unwrap()
2445        })
2446        .clone()
2447}
2448
2449pub fn git_config(stage0_metadata: &build_helper::stage0_parser::Stage0) -> GitConfig<'_> {
2450    GitConfig {
2451        nightly_branch: &stage0_metadata.config.nightly_branch,
2452        git_merge_commit_email: &stage0_metadata.config.git_merge_commit_email,
2453    }
2454}
2455
2456pub fn parse_download_ci_llvm(download_ci_llvm: Option<StringOrBool>) -> LlvmCiMode {
2457    let download_ci_llvm = download_ci_llvm.unwrap_or(StringOrBool::Bool(true));
2458    match download_ci_llvm {
2459        StringOrBool::Bool(b) => {
2460            if b {
2461                LlvmCiMode::Download
2462            } else {
2463                LlvmCiMode::BuildLocally
2464            }
2465        }
2466        StringOrBool::String(s) if s == "if-unchanged" => LlvmCiMode::DownloadIfUnchanged,
2467        StringOrBool::String(other) => {
2468            panic!("unrecognized option for download-ci-llvm: {other:?}")
2469        }
2470    }
2471}
2472
2473pub fn has_changes_from_upstream<'a>(
2474    dwn_ctx: impl AsRef<DownloadContext<'a>>,
2475    paths: &[&'static str],
2476) -> bool {
2477    let dwn_ctx = dwn_ctx.as_ref();
2478    match check_path_modifications_(dwn_ctx, paths) {
2479        PathFreshness::LastModifiedUpstream { .. } => false,
2480        PathFreshness::HasLocalModifications { .. } | PathFreshness::MissingUpstream => true,
2481    }
2482}
2483
2484#[cfg_attr(
2485    feature = "tracing",
2486    instrument(
2487        level = "trace",
2488        name = "Config::update_submodule",
2489        skip_all,
2490        fields(relative_path = ?relative_path),
2491    ),
2492)]
2493pub(crate) fn update_submodule<'a>(
2494    dwn_ctx: impl AsRef<DownloadContext<'a>>,
2495    rust_info: &channel::GitInfo,
2496    relative_path: &str,
2497) {
2498    let dwn_ctx = dwn_ctx.as_ref();
2499    if rust_info.is_from_tarball() || !submodules_(dwn_ctx.submodules, rust_info) {
2500        return;
2501    }
2502
2503    let absolute_path = dwn_ctx.src.join(relative_path);
2504
2505    // NOTE: This check is required because `jj git clone` doesn't create directories for
2506    // submodules, they are completely ignored. The code below assumes this directory exists,
2507    // so create it here.
2508    if !absolute_path.exists() {
2509        t!(fs::create_dir_all(&absolute_path));
2510    }
2511
2512    // NOTE: The check for the empty directory is here because when running x.py the first time,
2513    // the submodule won't be checked out. Check it out now so we can build it.
2514    if !git_info(dwn_ctx.exec_ctx, false, &absolute_path).is_managed_git_subrepository()
2515        && !helpers::dir_is_empty(&absolute_path)
2516    {
2517        return;
2518    }
2519
2520    let submodule_git = || helpers::git(Some(&absolute_path));
2521
2522    // Determine commit checked out in submodule.
2523    let checked_out_hash =
2524        submodule_git().args(["rev-parse", "HEAD"]).run_capture_stdout(dwn_ctx.exec_ctx).stdout();
2525    let checked_out_hash = checked_out_hash.trim_end();
2526    // Determine commit that the submodule *should* have.
2527    let recorded = helpers::git(Some(dwn_ctx.src))
2528        .run_in_dry_run() // otherwise parsing `actual_hash` fails
2529        .args(["ls-tree", "HEAD"])
2530        .arg(relative_path)
2531        .run_capture_stdout(dwn_ctx.exec_ctx)
2532        .stdout();
2533
2534    let actual_hash = recorded
2535        .split_whitespace()
2536        .nth(2)
2537        .unwrap_or_else(|| panic!("unexpected output `{recorded}` when updating {relative_path}"));
2538
2539    if actual_hash == checked_out_hash {
2540        // already checked out
2541        return;
2542    }
2543
2544    if !dwn_ctx.exec_ctx.dry_run() {
2545        println!("Updating submodule {relative_path}");
2546    };
2547
2548    helpers::git(Some(dwn_ctx.src))
2549        .allow_failure()
2550        .args(["submodule", "-q", "sync"])
2551        .arg(relative_path)
2552        .run(dwn_ctx.exec_ctx);
2553
2554    // Try passing `--progress` to start, then run git again without if that fails.
2555    let update = |progress: bool| {
2556        // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository,
2557        // even though that has no relation to the upstream for the submodule.
2558        let current_branch = helpers::git(Some(dwn_ctx.src))
2559            .allow_failure()
2560            .args(["symbolic-ref", "--short", "HEAD"])
2561            .run_capture(dwn_ctx.exec_ctx);
2562
2563        let mut git = helpers::git(Some(dwn_ctx.src)).allow_failure();
2564        if current_branch.is_success() {
2565            // If there is a tag named after the current branch, git will try to disambiguate by prepending `heads/` to the branch name.
2566            // This syntax isn't accepted by `branch.{branch}`. Strip it.
2567            let branch = current_branch.stdout();
2568            let branch = branch.trim();
2569            let branch = branch.trim_prefix("heads/");
2570            git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
2571        }
2572        git.args(["submodule", "update", "--init", "--recursive", "--depth=1"]);
2573        if progress {
2574            git.arg("--progress");
2575        }
2576        git.arg(relative_path);
2577        git
2578    };
2579    if !update(true).allow_failure().run(dwn_ctx.exec_ctx) {
2580        update(false).allow_failure().run(dwn_ctx.exec_ctx);
2581    }
2582
2583    // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error).
2584    // diff-index reports the modifications through the exit status
2585    let has_local_modifications = !submodule_git()
2586        .allow_failure()
2587        .args(["diff-index", "--quiet", "HEAD"])
2588        .run(dwn_ctx.exec_ctx);
2589    if has_local_modifications {
2590        submodule_git().allow_failure().args(["stash", "push"]).run(dwn_ctx.exec_ctx);
2591    }
2592
2593    submodule_git().allow_failure().args(["reset", "-q", "--hard"]).run(dwn_ctx.exec_ctx);
2594    submodule_git().allow_failure().args(["clean", "-qdfx"]).run(dwn_ctx.exec_ctx);
2595
2596    if has_local_modifications {
2597        submodule_git().allow_failure().args(["stash", "pop"]).run(dwn_ctx.exec_ctx);
2598    }
2599}
2600
2601pub fn git_info(exec_ctx: &ExecutionContext, omit_git_hash: bool, dir: &Path) -> GitInfo {
2602    GitInfo::new(omit_git_hash, dir, exec_ctx)
2603}
2604
2605pub fn submodules_(submodules: &Option<bool>, rust_info: &channel::GitInfo) -> bool {
2606    // If not specified in config, the default is to only manage
2607    // submodules if we're currently inside a git repository.
2608    submodules.unwrap_or(rust_info.is_managed_git_subrepository())
2609}
2610
2611/// Returns the content of the given file at a specific commit.
2612pub(crate) fn read_file_by_commit<'a>(
2613    dwn_ctx: impl AsRef<DownloadContext<'a>>,
2614    rust_info: &channel::GitInfo,
2615    file: &Path,
2616    commit: &str,
2617) -> String {
2618    let dwn_ctx = dwn_ctx.as_ref();
2619    assert!(
2620        rust_info.is_managed_git_subrepository(),
2621        "`Config::read_file_by_commit` is not supported in non-git sources."
2622    );
2623
2624    let mut git = helpers::git(Some(dwn_ctx.src));
2625    git.arg("show").arg(format!("{commit}:{}", file.to_str().unwrap()));
2626    git.run_capture_stdout(dwn_ctx.exec_ctx).stdout()
2627}
2628
2629fn bad_config(toml_path: &Path, e: toml::de::Error) -> ! {
2630    eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display());
2631    let e_s = e.to_string();
2632    if e_s.contains("unknown field")
2633        && let Some(field_name) = e_s.split("`").nth(1)
2634        && let sections = find_correct_section_for_field(field_name)
2635        && !sections.is_empty()
2636    {
2637        if sections.len() == 1 {
2638            match sections[0] {
2639                WouldBeValidFor::TopLevel { is_section } => {
2640                    if is_section {
2641                        eprintln!(
2642                            "hint: section name `{field_name}` used as a key within a section"
2643                        );
2644                    } else {
2645                        eprintln!("hint: try using `{field_name}` as a top level key");
2646                    }
2647                }
2648                WouldBeValidFor::Section(section) => {
2649                    eprintln!("hint: try moving `{field_name}` to the `{section}` section")
2650                }
2651            }
2652        } else {
2653            eprintln!(
2654                "hint: `{field_name}` would be valid {}",
2655                join_oxford_comma(sections.iter(), "or"),
2656            );
2657        }
2658    }
2659
2660    helpers::exit_process(2);
2661}
2662
2663#[derive(Copy, Clone, Debug)]
2664enum WouldBeValidFor {
2665    TopLevel { is_section: bool },
2666    Section(&'static str),
2667}
2668
2669fn join_oxford_comma(
2670    mut parts: impl ExactSizeIterator<Item = impl std::fmt::Display>,
2671    conj: &str,
2672) -> String {
2673    use std::fmt::Write;
2674    let mut out = String::new();
2675
2676    assert!(parts.len() > 1);
2677    while let Some(part) = parts.next() {
2678        if parts.len() == 0 {
2679            write!(&mut out, "{conj} {part}")
2680        } else {
2681            write!(&mut out, "{part}, ")
2682        }
2683        .unwrap();
2684    }
2685    out
2686}
2687
2688impl std::fmt::Display for WouldBeValidFor {
2689    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2690        match self {
2691            Self::TopLevel { .. } => write!(f, "at top level"),
2692            Self::Section(section_name) => write!(f, "in section `{section_name}`"),
2693        }
2694    }
2695}
2696
2697fn find_correct_section_for_field(field_name: &str) -> Vec<WouldBeValidFor> {
2698    let sections = ["build", "install", "llvm", "gcc", "rust", "dist"];
2699    sections
2700        .iter()
2701        .map(Some)
2702        .chain([None])
2703        .filter_map(|section_name| {
2704            let dummy_config_str = if let Some(section_name) = section_name {
2705                format!("{section_name}.{field_name} = 0\n")
2706            } else {
2707                format!("{field_name} = 0\n")
2708            };
2709            let is_unknown_field = toml::from_str::<toml::Value>(&dummy_config_str)
2710                .and_then(TomlConfig::deserialize)
2711                .err()
2712                .is_some_and(|e| e.to_string().contains("unknown field"));
2713            if is_unknown_field {
2714                None
2715            } else {
2716                Some(section_name.copied().map(WouldBeValidFor::Section).unwrap_or_else(|| {
2717                    WouldBeValidFor::TopLevel { is_section: sections.contains(&field_name) }
2718                }))
2719            }
2720        })
2721        .collect()
2722}