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