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