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