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