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