Skip to main content

bootstrap/core/config/
config.rs

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