Skip to main content

bootstrap/core/config/
config.rs

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