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