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