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