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