1use std::cell::Cell;
17use std::collections::{BTreeSet, HashMap, HashSet};
18use std::io::IsTerminal;
19use std::path::{Path, PathBuf, absolute};
20use std::str::FromStr;
21use std::sync::{Arc, Mutex};
22use std::{cmp, env, fs};
23
24use build_helper::ci::CiEnv;
25use build_helper::exit;
26use build_helper::git::{GitConfig, PathFreshness, check_path_modifications};
27use serde::Deserialize;
28#[cfg(feature = "tracing")]
29use tracing::{instrument, span};
30
31use crate::core::build_steps::llvm;
32use crate::core::build_steps::llvm::LLVM_INVALIDATION_PATHS;
33use crate::core::build_steps::test::failed_tests::collect_previously_failed_tests;
34pub use crate::core::config::flags::Subcommand;
35use crate::core::config::flags::{Color, Flags, Warnings};
36use crate::core::config::target_selection::TargetSelectionList;
37use crate::core::config::toml::TomlConfig;
38use crate::core::config::toml::build::{Build, Tool};
39use crate::core::config::toml::change_id::ChangeId;
40use crate::core::config::toml::dist::Dist;
41use crate::core::config::toml::gcc::Gcc;
42use crate::core::config::toml::install::Install;
43use crate::core::config::toml::llvm::Llvm;
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, DebuginfoLevel, DryRun, GccCiMode, LlvmLibunwind, Merge, ReplaceOpt,
53 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, get_host_target};
61use crate::{CodegenBackendKind, GitInfo, OnceLock, TargetSelection, check_ci_llvm, helpers, t};
62
63#[rustfmt::skip] pub const RUSTC_IF_UNCHANGED_ALLOWED_PATHS: &[&str] = &[
76 ":!library",
77 ":!src/tools",
78 ":!src/librustdoc",
79 ":!src/rustdoc-json-types",
80 ":!tests",
81 ":!triagebot.toml",
82 ":!src/bootstrap/defaults",
83];
84
85#[derive(Clone)]
94pub struct Config {
95 pub change_id: Option<ChangeId>,
96 pub bypass_bootstrap_lock: bool,
97 pub ccache: Option<String>,
98 pub ninja_in_file: bool,
100 pub submodules: Option<bool>,
101 pub compiler_docs: bool,
102 pub library_docs_private_items: bool,
103 pub docs_minification: bool,
104 pub docs: bool,
105 pub locked_deps: bool,
106 pub vendor: bool,
107 pub target_config: HashMap<TargetSelection, Target>,
108 pub full_bootstrap: bool,
109 pub bootstrap_cache_path: Option<PathBuf>,
110 pub extended: bool,
111 pub tools: Option<HashSet<String>>,
112 pub tool: HashMap<String, Tool>,
115 pub sanitizers: bool,
116 pub profiler: bool,
117 pub omit_git_hash: bool,
118 pub skip: Vec<PathBuf>,
119 pub include_default_paths: bool,
120 pub rustc_error_format: Option<String>,
121 pub json_output: bool,
122 pub compile_time_deps: bool,
123 pub test_compare_mode: bool,
124 pub color: Color,
125 pub patch_binaries_for_nix: Option<bool>,
126 pub stage0_metadata: build_helper::stage0_parser::Stage0,
127 pub android_ndk: Option<PathBuf>,
128 pub optimized_compiler_builtins: CompilerBuiltins,
129 pub record_failed_tests_path: PathBuf,
130
131 pub stdout_is_tty: bool,
132 pub stderr_is_tty: bool,
133
134 pub on_fail: Option<String>,
135 pub explicit_stage_from_cli: bool,
136 pub explicit_stage_from_config: bool,
137 pub stage: u32,
138 pub keep_stage: Vec<u32>,
139 pub keep_stage_std: Vec<u32>,
140 pub src: PathBuf,
141 pub config: Option<PathBuf>,
143 pub jobs: Option<u32>,
144 pub cmd: Subcommand,
145 pub quiet: bool,
146 pub incremental: bool,
147 pub dump_bootstrap_shims: bool,
148 pub free_args: Vec<String>,
151
152 pub download_rustc_commit: Option<String>,
154
155 pub deny_warnings: bool,
156 pub backtrace_on_ice: bool,
157
158 pub llvm_assertions: bool,
160 pub llvm_tests: bool,
161 pub llvm_enzyme: bool,
162 pub llvm_offload: bool,
163 pub llvm_plugins: bool,
164 pub llvm_optimize: bool,
165 pub llvm_thin_lto: bool,
166 pub llvm_release_debuginfo: bool,
167 pub llvm_static_stdcpp: bool,
168 pub llvm_libzstd: bool,
169 pub llvm_link_shared: Cell<Option<bool>>,
170 pub llvm_clang_cl: Option<String>,
171 pub llvm_targets: Option<String>,
172 pub llvm_experimental_targets: Option<String>,
173 pub llvm_link_jobs: Option<u32>,
174 pub llvm_version_suffix: Option<String>,
175 pub llvm_use_linker: Option<String>,
176 pub llvm_clang_dir: Option<PathBuf>,
177 pub llvm_allow_old_toolchain: bool,
178 pub llvm_polly: bool,
179 pub llvm_clang: bool,
180 pub llvm_enable_warnings: bool,
181 pub llvm_from_ci: bool,
182 pub llvm_build_config: HashMap<String, String>,
183
184 pub bootstrap_override_lld: BootstrapOverrideLld,
185 pub lld_enabled: bool,
186 pub llvm_tools_enabled: bool,
187 pub llvm_bitcode_linker_enabled: bool,
188
189 pub llvm_cflags: Option<String>,
190 pub llvm_cxxflags: Option<String>,
191 pub llvm_ldflags: Option<String>,
192 pub llvm_use_libcxx: bool,
193
194 pub gcc_ci_mode: GccCiMode,
196 pub libgccjit_libs_dir: Option<PathBuf>,
197
198 pub rust_optimize: RustOptimize,
200 pub rust_codegen_units: Option<u32>,
201 pub rust_codegen_units_std: Option<u32>,
202 pub rustc_debug_assertions: bool,
203 pub std_debug_assertions: bool,
204 pub tools_debug_assertions: bool,
205
206 pub rust_overflow_checks: bool,
207 pub rust_overflow_checks_std: bool,
208 pub rust_debug_logging: bool,
209 pub rust_debuginfo_level_rustc: DebuginfoLevel,
210 pub rust_debuginfo_level_std: DebuginfoLevel,
211 pub rust_debuginfo_level_tools: DebuginfoLevel,
212 pub rust_debuginfo_level_tests: DebuginfoLevel,
213 pub rust_rpath: bool,
214 pub rust_strip: bool,
215 pub rust_frame_pointers: bool,
216 pub rust_stack_protector: Option<String>,
217 pub rustc_default_linker: Option<String>,
218 pub rust_optimize_tests: bool,
219 pub rust_dist_src: bool,
220 pub rust_codegen_backends: Vec<CodegenBackendKind>,
221 pub rust_verify_llvm_ir: bool,
222 pub rust_thin_lto_import_instr_limit: Option<u32>,
223 pub rust_randomize_layout: bool,
224 pub rust_remap_debuginfo: bool,
225 pub rust_new_symbol_mangling: Option<bool>,
226 pub rust_annotate_moves_size_limit: Option<u64>,
227 pub rust_profile_use: Option<String>,
228 pub rust_profile_generate: Option<String>,
229 pub rust_lto: RustcLto,
230 pub rust_validate_mir_opts: Option<u32>,
231 pub rust_std_features: BTreeSet<String>,
232 pub rust_break_on_ice: bool,
233 pub rust_parallel_frontend_threads: Option<u32>,
234 pub rust_rustflags: Vec<String>,
235
236 pub llvm_profile_use: Option<String>,
237 pub llvm_profile_generate: bool,
238 pub llvm_libunwind_default: Option<LlvmLibunwind>,
239 pub enable_bolt_settings: bool,
240
241 pub reproducible_artifacts: Vec<String>,
242
243 pub host_target: TargetSelection,
244 pub hosts: Vec<TargetSelection>,
245 pub targets: Vec<TargetSelection>,
246 pub local_rebuild: bool,
247 pub jemalloc: bool,
248 pub control_flow_guard: bool,
249 pub ehcont_guard: bool,
250
251 pub dist_sign_folder: Option<PathBuf>,
253 pub dist_upload_addr: Option<String>,
254 pub dist_compression_formats: Option<Vec<String>>,
255 pub dist_compression_profile: String,
256 pub dist_include_mingw_linker: bool,
257 pub dist_vendor: bool,
258
259 pub backtrace: bool, pub low_priority: bool,
264 pub channel: String,
265 pub description: Option<String>,
266 pub verbose_tests: bool,
267 pub save_toolstates: Option<PathBuf>,
268 pub print_step_timings: bool,
269 pub print_step_rusage: bool,
270
271 pub musl_root: Option<PathBuf>,
273 pub prefix: Option<PathBuf>,
274 pub sysconfdir: Option<PathBuf>,
275 pub datadir: Option<PathBuf>,
276 pub docdir: Option<PathBuf>,
277 pub bindir: PathBuf,
278 pub libdir: Option<PathBuf>,
279 pub mandir: Option<PathBuf>,
280 pub codegen_tests: bool,
281 pub nodejs: Option<PathBuf>,
282 pub yarn: Option<PathBuf>,
283 pub gdb: Option<PathBuf>,
284 pub lldb: Option<PathBuf>,
285 pub python: Option<PathBuf>,
286 pub windows_rc: Option<PathBuf>,
287 pub reuse: Option<PathBuf>,
288 pub cargo_native_static: bool,
289 pub configure_args: Vec<String>,
290 pub out: PathBuf,
291 pub rust_info: channel::GitInfo,
292
293 pub cargo_info: channel::GitInfo,
294 pub rust_analyzer_info: channel::GitInfo,
295 pub clippy_info: channel::GitInfo,
296 pub miri_info: channel::GitInfo,
297 pub rustfmt_info: channel::GitInfo,
298 pub enzyme_info: channel::GitInfo,
299 pub in_tree_llvm_info: channel::GitInfo,
300 pub in_tree_gcc_info: channel::GitInfo,
301
302 pub initial_cargo: PathBuf,
304 pub initial_rustc: PathBuf,
305 pub initial_rustdoc: PathBuf,
306 pub initial_cargo_clippy: Option<PathBuf>,
307 pub initial_sysroot: PathBuf,
308 pub initial_rustfmt: Option<PathBuf>,
309
310 pub paths: Vec<PathBuf>,
313
314 pub compiletest_diff_tool: Option<String>,
316
317 pub compiletest_allow_stage0: bool,
323
324 pub tidy_extra_checks: Option<String>,
326 pub ci_env: CiEnv,
327
328 pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
330
331 pub skip_std_check_if_no_download_rustc: bool,
335
336 pub exec_ctx: ExecutionContext,
337}
338
339impl Config {
340 pub fn set_dry_run(&mut self, dry_run: DryRun) {
341 self.exec_ctx.set_dry_run(dry_run);
342 }
343
344 pub fn get_dry_run(&self) -> &DryRun {
345 self.exec_ctx.get_dry_run()
346 }
347
348 #[cfg_attr(
349 feature = "tracing",
350 instrument(target = "CONFIG_HANDLING", level = "trace", name = "Config::parse", skip_all)
351 )]
352 pub fn parse(flags: Flags) -> Config {
353 Self::parse_inner(flags, Self::get_toml)
354 }
355
356 #[cfg_attr(
357 feature = "tracing",
358 instrument(
359 target = "CONFIG_HANDLING",
360 level = "trace",
361 name = "Config::parse_inner",
362 skip_all
363 )
364 )]
365 pub(crate) fn parse_inner(
366 flags: Flags,
367 get_toml: impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
368 ) -> Config {
369 let Flags {
373 cmd: flags_cmd,
374 verbose: flags_verbose,
375 quiet: flags_quiet,
376 incremental: flags_incremental,
377 config: flags_config,
378 build_dir: flags_build_dir,
379 build: flags_build,
380 host: flags_host,
381 target: flags_target,
382 exclude: flags_exclude,
383 skip: flags_skip,
384 include_default_paths: flags_include_default_paths,
385 rustc_error_format: flags_rustc_error_format,
386 on_fail: flags_on_fail,
387 dry_run: flags_dry_run,
388 dump_bootstrap_shims: flags_dump_bootstrap_shims,
389 stage: flags_stage,
390 keep_stage: flags_keep_stage,
391 keep_stage_std: flags_keep_stage_std,
392 src: flags_src,
393 jobs: flags_jobs,
394 warnings: flags_warnings,
395 json_output: flags_json_output,
396 compile_time_deps: flags_compile_time_deps,
397 color: flags_color,
398 bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
399 rust_profile_generate: flags_rust_profile_generate,
400 rust_profile_use: flags_rust_profile_use,
401 llvm_profile_use: flags_llvm_profile_use,
402 llvm_profile_generate: flags_llvm_profile_generate,
403 enable_bolt_settings: flags_enable_bolt_settings,
404 skip_stage0_validation: flags_skip_stage0_validation,
405 reproducible_artifact: flags_reproducible_artifact,
406 paths: flags_paths,
407 set: flags_set,
408 free_args: flags_free_args,
409 ci: flags_ci,
410 skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
411 } = flags;
412
413 #[cfg(feature = "tracing")]
414 span!(
415 target: "CONFIG_HANDLING",
416 tracing::Level::TRACE,
417 "collecting paths and path exclusions",
418 "flags.paths" = ?flags_paths,
419 "flags.skip" = ?flags_skip,
420 "flags.exclude" = ?flags_exclude
421 );
422
423 if flags_cmd.no_doc() {
424 eprintln!(
425 "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."
426 )
427 }
428
429 let mut exec_ctx = ExecutionContext::new(flags_verbose, flags_cmd.fail_fast());
431 exec_ctx.set_dry_run(if flags_dry_run { DryRun::UserSelected } else { DryRun::Disabled });
432
433 let default_src_dir = {
434 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
435 manifest_dir.parent().unwrap().parent().unwrap().to_owned()
437 };
438 let src = if let Some(s) = compute_src_directory(flags_src, &exec_ctx) {
439 s
440 } else {
441 default_src_dir.clone()
442 };
443
444 #[cfg(test)]
445 {
446 if let Some(config_path) = flags_config.as_ref() {
447 assert!(
448 !config_path.starts_with(&src),
449 "Path {config_path:?} should not be inside or equal to src dir {src:?}"
450 );
451 } else {
452 panic!("During test the config should be explicitly added");
453 }
454 }
455
456 let (mut toml, toml_path) = load_toml_config(&src, flags_config, &get_toml);
458
459 postprocess_toml(&mut toml, &src, toml_path.clone(), &exec_ctx, &flags_set, &get_toml);
460
461 let Build {
464 description: build_description,
465 build: build_build,
466 host: build_host,
467 target: build_target,
468 build_dir: build_build_dir,
469 cargo: mut build_cargo,
470 rustc: mut build_rustc,
471 rustdoc: build_rustdoc,
472 rustfmt: build_rustfmt,
473 cargo_clippy: build_cargo_clippy,
474 docs: build_docs,
475 compiler_docs: build_compiler_docs,
476 library_docs_private_items: build_library_docs_private_items,
477 docs_minification: build_docs_minification,
478 submodules: build_submodules,
479 gdb: build_gdb,
480 lldb: build_lldb,
481 nodejs: build_nodejs,
482
483 yarn: build_yarn,
484 npm: build_npm,
485 python: build_python,
486 windows_rc: build_windows_rc,
487 reuse: build_reuse,
488 locked_deps: build_locked_deps,
489 vendor: build_vendor,
490 full_bootstrap: build_full_bootstrap,
491 bootstrap_cache_path: build_bootstrap_cache_path,
492 extended: build_extended,
493 tools: build_tools,
494 tool: build_tool,
495 verbose: build_verbose,
496 sanitizers: build_sanitizers,
497 profiler: build_profiler,
498 cargo_native_static: build_cargo_native_static,
499 low_priority: build_low_priority,
500 configure_args: build_configure_args,
501 local_rebuild: build_local_rebuild,
502 print_step_timings: build_print_step_timings,
503 print_step_rusage: build_print_step_rusage,
504 check_stage: build_check_stage,
505 doc_stage: build_doc_stage,
506 build_stage: build_build_stage,
507 test_stage: build_test_stage,
508 install_stage: build_install_stage,
509 dist_stage: build_dist_stage,
510 bench_stage: build_bench_stage,
511 patch_binaries_for_nix: build_patch_binaries_for_nix,
512 record_failed_tests_path: build_record_failed_tests_path,
513 metrics: _,
515 android_ndk: build_android_ndk,
516 optimized_compiler_builtins: build_optimized_compiler_builtins,
517 jobs: build_jobs,
518 compiletest_diff_tool: build_compiletest_diff_tool,
519 compiletest_use_stage0_libtest: _,
521 tidy_extra_checks: build_tidy_extra_checks,
522 ccache: build_ccache,
523 exclude: build_exclude,
524 compiletest_allow_stage0: build_compiletest_allow_stage0,
525 } = toml.build.unwrap_or_default();
526
527 let Install {
528 prefix: install_prefix,
529 sysconfdir: install_sysconfdir,
530 docdir: install_docdir,
531 bindir: install_bindir,
532 libdir: install_libdir,
533 mandir: install_mandir,
534 datadir: install_datadir,
535 } = toml.install.unwrap_or_default();
536
537 let Rust {
538 optimize: rust_optimize,
539 debug: rust_debug,
540 codegen_units: rust_codegen_units,
541 codegen_units_std: rust_codegen_units_std,
542 rustc_debug_assertions: rust_rustc_debug_assertions,
543 std_debug_assertions: rust_std_debug_assertions,
544 tools_debug_assertions: rust_tools_debug_assertions,
545 overflow_checks: rust_overflow_checks,
546 overflow_checks_std: rust_overflow_checks_std,
547 debug_logging: rust_debug_logging,
548 debuginfo_level: rust_debuginfo_level,
549 debuginfo_level_rustc: rust_debuginfo_level_rustc,
550 debuginfo_level_std: rust_debuginfo_level_std,
551 debuginfo_level_tools: rust_debuginfo_level_tools,
552 debuginfo_level_tests: rust_debuginfo_level_tests,
553 backtrace: rust_backtrace,
554 incremental: rust_incremental,
555 randomize_layout: rust_randomize_layout,
556 default_linker: rust_default_linker,
557 channel: rust_channel,
558 musl_root: rust_musl_root,
559 rpath: rust_rpath,
560 verbose_tests: rust_verbose_tests,
561 optimize_tests: rust_optimize_tests,
562 codegen_tests: rust_codegen_tests,
563 omit_git_hash: rust_omit_git_hash,
564 dist_src: rust_dist_src,
565 save_toolstates: rust_save_toolstates,
566 codegen_backends: rust_codegen_backends,
567 lld: rust_lld_enabled,
568 llvm_tools: rust_llvm_tools,
569 llvm_bitcode_linker: rust_llvm_bitcode_linker,
570 deny_warnings: rust_deny_warnings,
571 backtrace_on_ice: rust_backtrace_on_ice,
572 verify_llvm_ir: rust_verify_llvm_ir,
573 thin_lto_import_instr_limit: rust_thin_lto_import_instr_limit,
574 parallel_frontend_threads: rust_parallel_frontend_threads,
575 remap_debuginfo: rust_remap_debuginfo,
576 jemalloc: rust_jemalloc,
577 test_compare_mode: rust_test_compare_mode,
578 llvm_libunwind: rust_llvm_libunwind,
579 control_flow_guard: rust_control_flow_guard,
580 ehcont_guard: rust_ehcont_guard,
581 new_symbol_mangling: rust_new_symbol_mangling,
582 annotate_moves_size_limit: rust_annotate_moves_size_limit,
583 profile_generate: rust_profile_generate,
584 profile_use: rust_profile_use,
585 download_rustc: rust_download_rustc,
586 lto: rust_lto,
587 validate_mir_opts: rust_validate_mir_opts,
588 frame_pointers: rust_frame_pointers,
589 stack_protector: rust_stack_protector,
590 strip: rust_strip,
591 bootstrap_override_lld: rust_bootstrap_override_lld,
592 bootstrap_override_lld_legacy: rust_bootstrap_override_lld_legacy,
593 std_features: rust_std_features,
594 break_on_ice: rust_break_on_ice,
595 rustflags: rust_rustflags,
596 } = toml.rust.unwrap_or_default();
597
598 let Llvm {
599 optimize: llvm_optimize,
600 thin_lto: llvm_thin_lto,
601 release_debuginfo: llvm_release_debuginfo,
602 assertions: llvm_assertions,
603 tests: llvm_tests,
604 enzyme: llvm_enzyme,
605 plugins: llvm_plugin,
606 static_libstdcpp: llvm_static_libstdcpp,
607 libzstd: llvm_libzstd,
608 ninja: llvm_ninja,
609 targets: llvm_targets,
610 experimental_targets: llvm_experimental_targets,
611 link_jobs: llvm_link_jobs,
612 link_shared: llvm_link_shared,
613 version_suffix: llvm_version_suffix,
614 clang_cl: llvm_clang_cl,
615 cflags: llvm_cflags,
616 cxxflags: llvm_cxxflags,
617 ldflags: llvm_ldflags,
618 use_libcxx: llvm_use_libcxx,
619 use_linker: llvm_use_linker,
620 allow_old_toolchain: llvm_allow_old_toolchain,
621 offload: llvm_offload,
622 offload_clang_dir: llvm_clang_dir,
623 polly: llvm_polly,
624 clang: llvm_clang,
625 enable_warnings: llvm_enable_warnings,
626 download_ci_llvm: llvm_download_ci_llvm,
627 build_config: llvm_build_config,
628 } = toml.llvm.unwrap_or_default();
629
630 let Dist {
631 sign_folder: dist_sign_folder,
632 upload_addr: dist_upload_addr,
633 src_tarball: dist_src_tarball,
634 compression_formats: dist_compression_formats,
635 compression_profile: dist_compression_profile,
636 include_mingw_linker: dist_include_mingw_linker,
637 vendor: dist_vendor,
638 } = toml.dist.unwrap_or_default();
639
640 let Gcc {
641 download_ci_gcc: gcc_download_ci_gcc,
642 libgccjit_libs_dir: gcc_libgccjit_libs_dir,
643 } = toml.gcc.unwrap_or_default();
644
645 if rust_bootstrap_override_lld.is_some() && rust_bootstrap_override_lld_legacy.is_some() {
646 panic!(
647 "Cannot use both `rust.use-lld` and `rust.bootstrap-override-lld`. Please use only `rust.bootstrap-override-lld`"
648 );
649 }
650
651 let bootstrap_override_lld =
652 rust_bootstrap_override_lld.or(rust_bootstrap_override_lld_legacy).unwrap_or_default();
653
654 if rust_optimize.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) {
655 eprintln!(
656 "WARNING: setting `optimize` to `false` is known to cause errors and \
657 should be considered unsupported. Refer to `bootstrap.example.toml` \
658 for more details."
659 );
660 }
661
662 exec_ctx.set_verbosity(cmp::max(build_verbose.unwrap_or_default() as u8, flags_verbose));
665
666 let stage0_metadata = build_helper::stage0_parser::parse_stage0_file();
667 let path_modification_cache = Arc::new(Mutex::new(HashMap::new()));
668
669 let host_target = flags_build
670 .or(build_build)
671 .map(|build| TargetSelection::from_user(&build))
672 .unwrap_or_else(get_host_target);
673 let hosts = flags_host
674 .map(|TargetSelectionList(hosts)| hosts)
675 .or_else(|| {
676 build_host.map(|h| h.iter().map(|t| TargetSelection::from_user(t)).collect())
677 })
678 .unwrap_or_else(|| vec![host_target]);
679
680 let llvm_assertions = llvm_assertions.unwrap_or(false);
681 let mut target_config = HashMap::new();
682 let mut channel = "dev".to_string();
683
684 let out = flags_build_dir.or_else(|| build_build_dir.map(PathBuf::from));
685 let out = if cfg!(test) {
686 out.expect("--build-dir has to be specified in tests")
687 } else {
688 out.unwrap_or_else(|| PathBuf::from("build"))
689 };
690
691 let mut out = if !out.is_absolute() {
694 absolute(&out).expect("can't make empty path absolute")
696 } else {
697 out
698 };
699
700 let default_stage0_rustc_path = |dir: &Path| {
701 dir.join(host_target).join("stage0").join("bin").join(exe("rustc", host_target))
702 };
703
704 if cfg!(test) {
705 build_rustc = build_rustc.take().or(std::env::var_os("RUSTC").map(|p| p.into()));
711 build_cargo = build_cargo.take().or(std::env::var_os("CARGO").map(|p| p.into()));
712
713 let is_test_outside_x = std::env::var("CARGO_TARGET_DIR").is_err();
719 if is_test_outside_x && build_rustc.is_none() {
720 let stage0_rustc = default_stage0_rustc_path(&default_src_dir.join("build"));
721 assert!(
722 stage0_rustc.exists(),
723 "Trying to run cargo test without having a stage0 rustc available in {}",
724 stage0_rustc.display()
725 );
726 build_rustc = Some(stage0_rustc);
727 }
728 }
729
730 if !flags_skip_stage0_validation {
731 if let Some(rustc) = &build_rustc {
732 check_stage0_version(rustc, "rustc", &src, &exec_ctx);
733 }
734 if let Some(cargo) = &build_cargo {
735 check_stage0_version(cargo, "cargo", &src, &exec_ctx);
736 }
737 }
738
739 if build_cargo_clippy.is_some() && build_rustc.is_none() {
740 println!(
741 "WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict."
742 );
743 }
744
745 let ci_env = match flags_ci {
746 Some(true) => CiEnv::GitHubActions,
747 Some(false) => CiEnv::None,
748 None => CiEnv::current(),
749 };
750 let dwn_ctx = DownloadContext {
751 path_modification_cache: path_modification_cache.clone(),
752 src: &src,
753 submodules: &build_submodules,
754 host_target,
755 patch_binaries_for_nix: build_patch_binaries_for_nix,
756 exec_ctx: &exec_ctx,
757 stage0_metadata: &stage0_metadata,
758 llvm_assertions,
759 bootstrap_cache_path: &build_bootstrap_cache_path,
760 ci_env,
761 };
762
763 let initial_rustc = build_rustc.unwrap_or_else(|| {
764 download_beta_toolchain(&dwn_ctx, &out);
765 default_stage0_rustc_path(&out)
766 });
767
768 let initial_rustdoc = build_rustdoc
769 .unwrap_or_else(|| initial_rustc.with_file_name(exe("rustdoc", host_target)));
770
771 let initial_sysroot = t!(PathBuf::from_str(
772 command(&initial_rustc)
773 .args(["--print", "sysroot"])
774 .run_in_dry_run()
775 .run_capture_stdout(&exec_ctx)
776 .stdout()
777 .trim()
778 ));
779
780 let initial_cargo = build_cargo.unwrap_or_else(|| {
781 download_beta_toolchain(&dwn_ctx, &out);
782 initial_sysroot.join("bin").join(exe("cargo", host_target))
783 });
784
785 if exec_ctx.dry_run() {
787 out = out.join("tmp-dry-run");
788 fs::create_dir_all(&out).expect("Failed to create dry-run directory");
789 }
790
791 let file_content = t!(fs::read_to_string(src.join("src/ci/channel")));
792 let ci_channel = file_content.trim_end();
793
794 let is_user_configured_rust_channel = match rust_channel {
795 Some(channel_) if channel_ == "auto-detect" => {
796 channel = ci_channel.into();
797 true
798 }
799 Some(channel_) => {
800 channel = channel_;
801 true
802 }
803 None => false,
804 };
805
806 let omit_git_hash = rust_omit_git_hash.unwrap_or(channel == "dev");
807
808 let rust_info = git_info(&exec_ctx, omit_git_hash, &src);
809
810 if !is_user_configured_rust_channel && rust_info.is_from_tarball() {
811 channel = ci_channel.into();
812 }
813
814 let debug_assertions_requested = matches!(rust_rustc_debug_assertions, Some(true))
825 || (matches!(rust_debug, Some(true))
826 && !matches!(rust_rustc_debug_assertions, Some(false)));
827
828 if debug_assertions_requested
829 && let Some(ref opt) = rust_download_rustc
830 && opt.is_string_or_true()
831 {
832 eprintln!(
833 "WARN: currently no CI rustc builds have rustc debug assertions \
834 enabled. Please either set `rust.debug-assertions` to `false` if you \
835 want to use download CI rustc or set `rust.download-rustc` to `false`."
836 );
837 }
838
839 let mut download_rustc_commit =
840 download_ci_rustc_commit(&dwn_ctx, &rust_info, rust_download_rustc, llvm_assertions);
841
842 if debug_assertions_requested && download_rustc_commit.is_some() {
843 eprintln!(
844 "WARN: `rust.debug-assertions = true` will prevent downloading CI rustc as alt CI \
845 rustc is not currently built with debug assertions."
846 );
847 download_rustc_commit = None;
849 }
850
851 if let Some(commit) = &download_rustc_commit
855 && is_user_configured_rust_channel
856 {
857 println!(
858 "WARNING: `rust.download-rustc` is enabled. The `rust.channel` option will be overridden by the CI rustc's channel."
859 );
860
861 channel =
862 read_file_by_commit(&dwn_ctx, &rust_info, Path::new("src/ci/channel"), commit)
863 .trim()
864 .to_owned();
865 }
866
867 if build_npm.is_some() {
868 println!(
869 "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."
870 );
871 }
872
873 let mut lld_enabled = rust_lld_enabled.unwrap_or(false);
874
875 let mut targets_with_user_linker_override = HashSet::new();
877
878 if let Some(t) = toml.target {
879 for (triple, cfg) in t {
880 let TomlTarget {
881 cc: target_cc,
882 cxx: target_cxx,
883 ar: target_ar,
884 ranlib: target_ranlib,
885 default_linker: target_default_linker,
886 default_linker_linux_override: target_default_linker_linux_override,
887 linker: target_linker,
888 split_debuginfo: target_split_debuginfo,
889 llvm_config: target_llvm_config,
890 llvm_has_rust_patches: target_llvm_has_rust_patches,
891 llvm_filecheck: target_llvm_filecheck,
892 llvm_libunwind: target_llvm_libunwind,
893 sanitizers: target_sanitizers,
894 profiler: target_profiler,
895 rpath: target_rpath,
896 rustflags: target_rustflags,
897 crt_static: target_crt_static,
898 musl_root: target_musl_root,
899 musl_libdir: target_musl_libdir,
900 wasi_root: target_wasi_root,
901 qemu_rootfs: target_qemu_rootfs,
902 no_std: target_no_std,
903 codegen_backends: target_codegen_backends,
904 runner: target_runner,
905 optimized_compiler_builtins: target_optimized_compiler_builtins,
906 jemalloc: target_jemalloc,
907 } = cfg;
908
909 let mut target = Target::from_triple(&triple);
910
911 if target_default_linker_linux_override.is_some() {
912 targets_with_user_linker_override.insert(triple.clone());
913 }
914
915 let default_linker_linux_override = match target_default_linker_linux_override {
916 Some(DefaultLinuxLinkerOverride::SelfContainedLldCc) => {
917 if rust_default_linker.is_some() {
918 panic!(
919 "cannot set both `default-linker` and `default-linker-linux` for target `{triple}`"
920 );
921 }
922 if !triple.contains("linux-gnu") {
923 panic!(
924 "`default-linker-linux` can only be set for Linux GNU targets, not for `{triple}`"
925 );
926 }
927 if !lld_enabled {
928 panic!(
929 "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."
930 );
931 }
932 DefaultLinuxLinkerOverride::SelfContainedLldCc
933 }
934 Some(DefaultLinuxLinkerOverride::Off) => DefaultLinuxLinkerOverride::Off,
935 None => DefaultLinuxLinkerOverride::default(),
936 };
937
938 if let Some(ref s) = target_llvm_config {
939 if download_rustc_commit.is_some() && triple == *host_target.triple {
940 panic!(
941 "setting llvm_config for the host is incompatible with download-rustc"
942 );
943 }
944 target.llvm_config = Some(src.join(s));
945 }
946 if let Some(patches) = target_llvm_has_rust_patches {
947 assert!(
948 build_submodules == Some(false) || target_llvm_config.is_some(),
949 "use of `llvm-has-rust-patches` is restricted to cases where either submodules are disabled or llvm-config been provided"
950 );
951 target.llvm_has_rust_patches = Some(patches);
952 }
953 if let Some(ref s) = target_llvm_filecheck {
954 target.llvm_filecheck = Some(src.join(s));
955 }
956 target.llvm_libunwind = target_llvm_libunwind.as_ref().map(|v| {
957 v.parse().unwrap_or_else(|_| {
958 panic!("failed to parse target.{triple}.llvm-libunwind")
959 })
960 });
961 if let Some(s) = target_no_std {
962 target.no_std = s;
963 }
964 target.cc = target_cc.map(PathBuf::from);
965 target.cxx = target_cxx.map(PathBuf::from);
966 target.ar = target_ar.map(PathBuf::from);
967 target.ranlib = target_ranlib.map(PathBuf::from);
968 target.linker = target_linker.map(PathBuf::from);
969 target.crt_static = target_crt_static;
970 target.default_linker = target_default_linker;
971 target.default_linker_linux_override = default_linker_linux_override;
972 target.musl_root = target_musl_root.map(PathBuf::from);
973 target.musl_libdir = target_musl_libdir.map(PathBuf::from);
974 target.wasi_root = target_wasi_root.map(PathBuf::from);
975 target.qemu_rootfs = target_qemu_rootfs.map(PathBuf::from);
976 target.runner = target_runner;
977 target.sanitizers = target_sanitizers;
978 target.profiler = target_profiler;
979 target.rpath = target_rpath;
980 target.rustflags = target_rustflags.unwrap_or_default();
981 target.optimized_compiler_builtins = target_optimized_compiler_builtins;
982 target.jemalloc = target_jemalloc;
983 if let Some(backends) = target_codegen_backends {
984 target.codegen_backends =
985 Some(parse_codegen_backends(backends, &format!("target.{triple}")))
986 }
987
988 target.split_debuginfo = target_split_debuginfo.as_ref().map(|v| {
989 v.parse().unwrap_or_else(|_| {
990 panic!("invalid value for target.{triple}.split-debuginfo")
991 })
992 });
993
994 target_config.insert(TargetSelection::from_user(&triple), target);
995 }
996 }
997
998 let llvm_from_ci = parse_download_ci_llvm(
999 &dwn_ctx,
1000 &rust_info,
1001 &download_rustc_commit,
1002 llvm_download_ci_llvm,
1003 llvm_assertions,
1004 );
1005 let is_host_system_llvm =
1006 is_system_llvm(&target_config, llvm_from_ci, host_target, host_target);
1007
1008 if llvm_from_ci {
1009 let warn = |option: &str| {
1010 println!(
1011 "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build."
1012 );
1013 println!(
1014 "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false."
1015 );
1016 };
1017
1018 if llvm_static_libstdcpp.is_some() {
1019 warn("static-libstdcpp");
1020 }
1021
1022 if llvm_link_shared.is_some() {
1023 warn("link-shared");
1024 }
1025
1026 if llvm_libzstd.is_some() {
1032 println!(
1033 "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \
1034 like almost all `llvm.*` options, will be ignored and set by the LLVM CI \
1035 artifacts builder config."
1036 );
1037 println!(
1038 "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false."
1039 );
1040 }
1041 }
1042
1043 if llvm_from_ci {
1044 let triple = &host_target.triple;
1045 let ci_llvm_bin = ci_llvm_root(&dwn_ctx, llvm_from_ci, &out).join("bin");
1046 let build_target =
1047 target_config.entry(host_target).or_insert_with(|| Target::from_triple(triple));
1048 check_ci_llvm!(build_target.llvm_config);
1049 check_ci_llvm!(build_target.llvm_filecheck);
1050 build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", host_target)));
1051 build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", host_target)));
1052 }
1053
1054 for (target, linker_override) in default_linux_linker_overrides() {
1055 if targets_with_user_linker_override.contains(&target) {
1057 continue;
1058 }
1059
1060 if !hosts.contains(&TargetSelection::from_user(&target)) {
1066 continue;
1067 }
1068
1069 let default_linux_linker_override = match linker_override {
1070 DefaultLinuxLinkerOverride::Off => continue,
1071 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1072 match rust_lld_enabled {
1075 None if !is_host_system_llvm => {
1078 lld_enabled = true;
1079 Some(DefaultLinuxLinkerOverride::SelfContainedLldCc)
1080 }
1081 None => None,
1082 Some(true) => Some(DefaultLinuxLinkerOverride::SelfContainedLldCc),
1084 Some(false) => None,
1087 }
1088 }
1089 };
1090 if let Some(linker_override) = default_linux_linker_override {
1091 target_config
1092 .entry(TargetSelection::from_user(&target))
1093 .or_default()
1094 .default_linker_linux_override = linker_override;
1095 }
1096 }
1097
1098 let initial_rustfmt = build_rustfmt.or_else(|| maybe_download_rustfmt(&dwn_ctx, &out));
1099
1100 if matches!(bootstrap_override_lld, BootstrapOverrideLld::SelfContained)
1101 && !lld_enabled
1102 && flags_stage.unwrap_or(0) > 0
1103 {
1104 panic!(
1105 "Trying to use self-contained lld as a linker, but LLD is not being added to the sysroot. Enable it with rust.lld = true."
1106 );
1107 }
1108
1109 if lld_enabled && is_host_system_llvm {
1110 panic!("Cannot enable LLD with `rust.lld = true` when using external llvm-config.");
1111 }
1112
1113 let download_rustc = download_rustc_commit.is_some();
1114
1115 let stage = match flags_cmd {
1116 Subcommand::Check { .. } => flags_stage.or(build_check_stage).unwrap_or(1),
1117 Subcommand::Clippy { .. } | Subcommand::Fix => {
1118 flags_stage.or(build_check_stage).unwrap_or(1)
1119 }
1120 Subcommand::Doc { .. } => {
1122 flags_stage.or(build_doc_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1123 }
1124 Subcommand::Build { .. } => {
1125 flags_stage.or(build_build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1126 }
1127 Subcommand::Test { .. } | Subcommand::Miri { .. } => {
1128 flags_stage.or(build_test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1129 }
1130 Subcommand::Bench { .. } => flags_stage.or(build_bench_stage).unwrap_or(2),
1131 Subcommand::Dist => flags_stage.or(build_dist_stage).unwrap_or(2),
1132 Subcommand::Install => flags_stage.or(build_install_stage).unwrap_or(2),
1133 Subcommand::Perf { .. } => flags_stage.unwrap_or(1),
1134 Subcommand::Clean { .. }
1137 | Subcommand::Run { .. }
1138 | Subcommand::Setup { .. }
1139 | Subcommand::Format { .. }
1140 | Subcommand::Vendor { .. } => flags_stage.unwrap_or(0),
1141 };
1142
1143 let local_rebuild = build_local_rebuild.unwrap_or(false);
1144
1145 let check_stage0 = |kind: &str| {
1146 if local_rebuild {
1147 eprintln!("WARNING: running {kind} in stage 0. This might not work as expected.");
1148 } else {
1149 eprintln!(
1150 "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."
1151 );
1152 exit!(1);
1153 }
1154 };
1155
1156 match (stage, &flags_cmd) {
1158 (0, Subcommand::Build { .. }) => {
1159 check_stage0("build");
1160 }
1161 (0, Subcommand::Check { .. }) => {
1162 check_stage0("check");
1163 }
1164 (0, Subcommand::Doc { .. }) => {
1165 check_stage0("doc");
1166 }
1167 (0, Subcommand::Clippy { .. }) => {
1168 check_stage0("clippy");
1169 }
1170 (0, Subcommand::Dist) => {
1171 check_stage0("dist");
1172 }
1173 (0, Subcommand::Install) => {
1174 check_stage0("install");
1175 }
1176 (0, Subcommand::Test { .. }) if build_compiletest_allow_stage0 != Some(true) => {
1177 eprintln!(
1178 "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`."
1179 );
1180 exit!(1);
1181 }
1182 _ => {}
1183 }
1184
1185 if flags_compile_time_deps && !matches!(flags_cmd, Subcommand::Check { .. }) {
1186 eprintln!("ERROR: Can't use --compile-time-deps with any subcommand other than check.");
1187 exit!(1);
1188 }
1189
1190 if matches!(flags_cmd, Subcommand::Fix) {
1191 eprintln!(
1192 "WARNING: `x fix` is provided on a best-effort basis and does not support all `cargo fix` options correctly."
1193 );
1194 }
1195
1196 #[cfg(not(test))]
1198 if flags_stage.is_none() && ci_env.is_running_in_ci() {
1199 match flags_cmd {
1200 Subcommand::Test { .. }
1201 | Subcommand::Miri { .. }
1202 | Subcommand::Doc { .. }
1203 | Subcommand::Build { .. }
1204 | Subcommand::Bench { .. }
1205 | Subcommand::Dist
1206 | Subcommand::Install => {
1207 assert_eq!(
1208 stage, 2,
1209 "x.py should be run with `--stage 2` on CI, but was run with `--stage {stage}`",
1210 );
1211 }
1212 Subcommand::Clean { .. }
1213 | Subcommand::Check { .. }
1214 | Subcommand::Clippy { .. }
1215 | Subcommand::Fix
1216 | Subcommand::Run { .. }
1217 | Subcommand::Setup { .. }
1218 | Subcommand::Format { .. }
1219 | Subcommand::Vendor { .. }
1220 | Subcommand::Perf { .. } => {}
1221 }
1222 }
1223
1224 let with_defaults = |debuginfo_level_specific: Option<_>| {
1225 debuginfo_level_specific.or(rust_debuginfo_level).unwrap_or(
1226 if rust_debug == Some(true) {
1227 DebuginfoLevel::Limited
1228 } else {
1229 DebuginfoLevel::None
1230 },
1231 )
1232 };
1233
1234 let ccache = match build_ccache {
1235 Some(StringOrBool::String(s)) => Some(s),
1236 Some(StringOrBool::Bool(true)) => Some("ccache".to_string()),
1237 _ => None,
1238 };
1239
1240 let explicit_stage_from_config = build_test_stage.is_some()
1241 || build_build_stage.is_some()
1242 || build_doc_stage.is_some()
1243 || build_dist_stage.is_some()
1244 || build_install_stage.is_some()
1245 || build_check_stage.is_some()
1246 || build_bench_stage.is_some();
1247
1248 let deny_warnings = match flags_warnings {
1249 Warnings::Deny => true,
1250 Warnings::Warn => false,
1251 Warnings::Default => rust_deny_warnings.unwrap_or(true),
1252 };
1253
1254 let gcc_ci_mode = match gcc_download_ci_gcc {
1255 Some(value) => match value {
1256 true => GccCiMode::DownloadFromCi,
1257 false => GccCiMode::BuildLocally,
1258 },
1259 None => GccCiMode::default(),
1260 };
1261
1262 let targets = flags_target
1263 .map(|TargetSelectionList(targets)| targets)
1264 .or_else(|| {
1265 build_target.map(|t| t.iter().map(|t| TargetSelection::from_user(t)).collect())
1266 })
1267 .unwrap_or_else(|| hosts.clone());
1268
1269 #[allow(clippy::map_identity)]
1270 let skip = flags_skip
1271 .into_iter()
1272 .chain(flags_exclude)
1273 .chain(build_exclude.unwrap_or_default())
1274 .map(|p| {
1275 #[cfg(windows)]
1278 {
1279 PathBuf::from(p.to_string_lossy().replace('/', "\\"))
1280 }
1281 #[cfg(not(windows))]
1282 {
1283 p
1284 }
1285 })
1286 .collect();
1287
1288 let cargo_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/cargo"));
1289 let clippy_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/clippy"));
1290 let in_tree_gcc_info = git_info(&exec_ctx, false, &src.join("src/gcc"));
1291 let in_tree_llvm_info = git_info(&exec_ctx, false, &src.join("src/llvm-project"));
1292 let enzyme_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/enzyme"));
1293 let miri_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/miri"));
1294 let rust_analyzer_info =
1295 git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rust-analyzer"));
1296 let rustfmt_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rustfmt"));
1297
1298 let optimized_compiler_builtins =
1299 build_optimized_compiler_builtins.unwrap_or(if channel == "dev" {
1300 CompilerBuiltins::BuildRustOnly
1301 } else {
1302 CompilerBuiltins::BuildLLVMFuncs
1303 });
1304 let vendor = build_vendor.unwrap_or(
1305 rust_info.is_from_tarball()
1306 && src.join("vendor").exists()
1307 && src.join(".cargo/config.toml").exists(),
1308 );
1309 let verbose_tests = rust_verbose_tests.unwrap_or(exec_ctx.is_verbose());
1310
1311 let record_failed_tests_path =
1312 out.join(build_record_failed_tests_path.unwrap_or_else(|| "failed-tests".to_string()));
1313
1314 let paths = {
1315 let mut paths = Vec::new();
1316 if flags_cmd.rerun() {
1317 paths = collect_previously_failed_tests(&record_failed_tests_path);
1318 } else {
1319 paths.extend(flags_paths);
1320 }
1321 paths
1322 };
1323
1324 Config {
1325 android_ndk: build_android_ndk,
1327 backtrace: rust_backtrace.unwrap_or(true),
1328 backtrace_on_ice: rust_backtrace_on_ice.unwrap_or(false),
1329 bindir: install_bindir.map(PathBuf::from).unwrap_or("bin".into()),
1330 bootstrap_cache_path: build_bootstrap_cache_path,
1331 bootstrap_override_lld,
1332 bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
1333 cargo_info,
1334 cargo_native_static: build_cargo_native_static.unwrap_or(false),
1335 ccache,
1336 change_id: toml.change_id.inner,
1337 channel,
1338 ci_env,
1339 clippy_info,
1340 cmd: flags_cmd,
1341 codegen_tests: rust_codegen_tests.unwrap_or(true),
1342 color: flags_color,
1343 compile_time_deps: flags_compile_time_deps,
1344 compiler_docs: build_compiler_docs.unwrap_or(false),
1345 compiletest_allow_stage0: build_compiletest_allow_stage0.unwrap_or(false),
1346 compiletest_diff_tool: build_compiletest_diff_tool,
1347 config: toml_path,
1348 configure_args: build_configure_args.unwrap_or_default(),
1349 control_flow_guard: rust_control_flow_guard.unwrap_or(false),
1350 datadir: install_datadir.map(PathBuf::from),
1351 deny_warnings,
1352 description: build_description,
1353 dist_compression_formats,
1354 dist_compression_profile: dist_compression_profile.unwrap_or("fast".into()),
1355 dist_include_mingw_linker: dist_include_mingw_linker.unwrap_or(true),
1356 dist_sign_folder: dist_sign_folder.map(PathBuf::from),
1357 dist_upload_addr,
1358 dist_vendor: dist_vendor.unwrap_or_else(|| {
1359 rust_info.is_managed_git_subrepository() || rust_info.is_from_tarball()
1361 }),
1362 docdir: install_docdir.map(PathBuf::from),
1363 docs: build_docs.unwrap_or(true),
1364 docs_minification: build_docs_minification.unwrap_or(true),
1365 download_rustc_commit,
1366 dump_bootstrap_shims: flags_dump_bootstrap_shims,
1367 ehcont_guard: rust_ehcont_guard.unwrap_or(false),
1368 enable_bolt_settings: flags_enable_bolt_settings,
1369 enzyme_info,
1370 exec_ctx,
1371 explicit_stage_from_cli: flags_stage.is_some(),
1372 explicit_stage_from_config,
1373 extended: build_extended.unwrap_or(false),
1374 free_args: flags_free_args,
1375 full_bootstrap: build_full_bootstrap.unwrap_or(false),
1376 gcc_ci_mode,
1377 gdb: build_gdb.map(PathBuf::from),
1378 host_target,
1379 hosts,
1380 in_tree_gcc_info,
1381 in_tree_llvm_info,
1382 include_default_paths: flags_include_default_paths,
1383 incremental: flags_incremental || rust_incremental == Some(true),
1384 initial_cargo,
1385 initial_cargo_clippy: build_cargo_clippy,
1386 initial_rustc,
1387 initial_rustdoc,
1388 initial_rustfmt,
1389 initial_sysroot,
1390 jemalloc: rust_jemalloc.unwrap_or(false),
1391 jobs: Some(threads_from_config(flags_jobs.or(build_jobs).unwrap_or(0))),
1392 json_output: flags_json_output,
1393 keep_stage: flags_keep_stage,
1394 keep_stage_std: flags_keep_stage_std,
1395 libdir: install_libdir.map(PathBuf::from),
1396 libgccjit_libs_dir: gcc_libgccjit_libs_dir,
1397 library_docs_private_items: build_library_docs_private_items.unwrap_or(false),
1398 lld_enabled,
1399 lldb: build_lldb.map(PathBuf::from),
1400 llvm_allow_old_toolchain: llvm_allow_old_toolchain.unwrap_or(false),
1401 llvm_assertions,
1402 llvm_bitcode_linker_enabled: rust_llvm_bitcode_linker.unwrap_or(false),
1403 llvm_build_config: llvm_build_config.clone().unwrap_or(Default::default()),
1404 llvm_cflags,
1405 llvm_clang: llvm_clang.unwrap_or(false),
1406 llvm_clang_cl,
1407 llvm_clang_dir: llvm_clang_dir.map(PathBuf::from),
1408 llvm_cxxflags,
1409 llvm_enable_warnings: llvm_enable_warnings.unwrap_or(false),
1410 llvm_enzyme: llvm_enzyme.unwrap_or(false),
1411 llvm_experimental_targets,
1412 llvm_from_ci,
1413 llvm_ldflags,
1414 llvm_libunwind_default: rust_llvm_libunwind
1415 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")),
1416 llvm_libzstd: llvm_libzstd.unwrap_or(false),
1417 llvm_link_jobs,
1418 llvm_link_shared: Cell::new(
1422 llvm_link_shared
1423 .or((!llvm_from_ci && llvm_thin_lto.unwrap_or(false)).then_some(true)),
1424 ),
1425 llvm_offload: llvm_offload.unwrap_or(false),
1426 llvm_optimize: llvm_optimize.unwrap_or(true),
1427 llvm_plugins: llvm_plugin.unwrap_or(false),
1428 llvm_polly: llvm_polly.unwrap_or(false),
1429 llvm_profile_generate: flags_llvm_profile_generate,
1430 llvm_profile_use: flags_llvm_profile_use,
1431 llvm_release_debuginfo: llvm_release_debuginfo.unwrap_or(false),
1432 llvm_static_stdcpp: llvm_static_libstdcpp.unwrap_or(false),
1433 llvm_targets,
1434 llvm_tests: llvm_tests.unwrap_or(false),
1435 llvm_thin_lto: llvm_thin_lto.unwrap_or(false),
1436 llvm_tools_enabled: rust_llvm_tools.unwrap_or(true),
1437 llvm_use_libcxx: llvm_use_libcxx.unwrap_or(false),
1438 llvm_use_linker,
1439 llvm_version_suffix,
1440 local_rebuild,
1441 locked_deps: build_locked_deps.unwrap_or(false),
1442 low_priority: build_low_priority.unwrap_or(false),
1443 mandir: install_mandir.map(PathBuf::from),
1444 miri_info,
1445 musl_root: rust_musl_root.map(PathBuf::from),
1446 ninja_in_file: llvm_ninja.unwrap_or(true),
1447 nodejs: build_nodejs.map(PathBuf::from),
1448 omit_git_hash,
1449 on_fail: flags_on_fail,
1450 optimized_compiler_builtins,
1451 out,
1452 patch_binaries_for_nix: build_patch_binaries_for_nix,
1453 path_modification_cache,
1454 paths,
1455 prefix: install_prefix.map(PathBuf::from),
1456 print_step_rusage: build_print_step_rusage.unwrap_or(false),
1457 print_step_timings: build_print_step_timings.unwrap_or(false),
1458 profiler: build_profiler.unwrap_or(false),
1459 python: build_python.map(PathBuf::from),
1460 quiet: flags_quiet,
1461 record_failed_tests_path,
1462 reproducible_artifacts: flags_reproducible_artifact,
1463 reuse: build_reuse.map(PathBuf::from),
1464 rust_analyzer_info,
1465 rust_annotate_moves_size_limit,
1466 rust_break_on_ice: rust_break_on_ice.unwrap_or(true),
1467 rust_codegen_backends: rust_codegen_backends
1468 .map(|backends| parse_codegen_backends(backends, "rust"))
1469 .unwrap_or(vec![CodegenBackendKind::Llvm]),
1470 rust_codegen_units: rust_codegen_units.map(threads_from_config),
1471 rust_codegen_units_std: rust_codegen_units_std.map(threads_from_config),
1472 rust_debug_logging: rust_debug_logging
1473 .or(rust_rustc_debug_assertions)
1474 .unwrap_or(rust_debug == Some(true)),
1475 rust_debuginfo_level_rustc: with_defaults(rust_debuginfo_level_rustc),
1476 rust_debuginfo_level_std: with_defaults(rust_debuginfo_level_std),
1477 rust_debuginfo_level_tests: rust_debuginfo_level_tests.unwrap_or(DebuginfoLevel::None),
1478 rust_debuginfo_level_tools: with_defaults(rust_debuginfo_level_tools),
1479 rust_dist_src: dist_src_tarball.unwrap_or_else(|| rust_dist_src.unwrap_or(true)),
1480 rust_frame_pointers: rust_frame_pointers.unwrap_or(false),
1481 rust_info,
1482 rust_lto: rust_lto
1483 .as_deref()
1484 .map(|value| RustcLto::from_str(value).unwrap())
1485 .unwrap_or_default(),
1486 rust_new_symbol_mangling,
1487 rust_optimize: rust_optimize.unwrap_or(RustOptimize::Bool(true)),
1488 rust_optimize_tests: rust_optimize_tests.unwrap_or(true),
1489 rust_overflow_checks: rust_overflow_checks.unwrap_or(rust_debug == Some(true)),
1490 rust_overflow_checks_std: rust_overflow_checks_std
1491 .or(rust_overflow_checks)
1492 .unwrap_or(rust_debug == Some(true)),
1493 rust_parallel_frontend_threads: rust_parallel_frontend_threads.map(threads_from_config),
1494 rust_profile_generate: flags_rust_profile_generate.or(rust_profile_generate),
1495 rust_profile_use: flags_rust_profile_use.or(rust_profile_use),
1496 rust_randomize_layout: rust_randomize_layout.unwrap_or(false),
1497 rust_remap_debuginfo: rust_remap_debuginfo.unwrap_or(false),
1498 rust_rpath: rust_rpath.unwrap_or(true),
1499 rust_rustflags: rust_rustflags.unwrap_or_default(),
1500 rust_stack_protector,
1501 rust_std_features: rust_std_features
1502 .unwrap_or(BTreeSet::from([String::from("panic-unwind")])),
1503 rust_strip: rust_strip.unwrap_or(false),
1504 rust_thin_lto_import_instr_limit,
1505 rust_validate_mir_opts,
1506 rust_verify_llvm_ir: rust_verify_llvm_ir.unwrap_or(false),
1507 rustc_debug_assertions: rust_rustc_debug_assertions.unwrap_or(rust_debug == Some(true)),
1508 rustc_default_linker: rust_default_linker,
1509 rustc_error_format: flags_rustc_error_format,
1510 rustfmt_info,
1511 sanitizers: build_sanitizers.unwrap_or(false),
1512 save_toolstates: rust_save_toolstates.map(PathBuf::from),
1513 skip,
1514 skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
1515 src,
1516 stage,
1517 stage0_metadata,
1518 std_debug_assertions: rust_std_debug_assertions
1519 .or(rust_rustc_debug_assertions)
1520 .unwrap_or(rust_debug == Some(true)),
1521 stderr_is_tty: std::io::stderr().is_terminal(),
1522 stdout_is_tty: std::io::stdout().is_terminal(),
1523 submodules: build_submodules,
1524 sysconfdir: install_sysconfdir.map(PathBuf::from),
1525 target_config,
1526 targets,
1527 test_compare_mode: rust_test_compare_mode.unwrap_or(false),
1528 tidy_extra_checks: build_tidy_extra_checks,
1529 tool: build_tool.unwrap_or_default(),
1530 tools: build_tools,
1531 tools_debug_assertions: rust_tools_debug_assertions
1532 .or(rust_rustc_debug_assertions)
1533 .unwrap_or(rust_debug == Some(true)),
1534 vendor,
1535 verbose_tests,
1536 windows_rc: build_windows_rc.map(PathBuf::from),
1537 yarn: build_yarn.map(PathBuf::from),
1538 }
1540 }
1541
1542 pub fn dry_run(&self) -> bool {
1543 self.exec_ctx.dry_run()
1544 }
1545
1546 pub fn is_running_on_ci(&self) -> bool {
1547 self.ci_env.is_running_in_ci()
1548 }
1549
1550 pub fn is_explicit_stage(&self) -> bool {
1551 self.explicit_stage_from_cli || self.explicit_stage_from_config
1552 }
1553
1554 pub(crate) fn test_args(&self) -> Vec<&str> {
1555 let mut test_args = match self.cmd {
1556 Subcommand::Test { ref test_args, .. }
1557 | Subcommand::Bench { ref test_args, .. }
1558 | Subcommand::Miri { ref test_args, .. } => {
1559 test_args.iter().flat_map(|s| s.split_whitespace()).collect()
1560 }
1561 _ => vec![],
1562 };
1563 test_args.extend(self.free_args.iter().map(|s| s.as_str()));
1564 test_args
1565 }
1566
1567 pub(crate) fn args(&self) -> Vec<&str> {
1568 let mut args = match self.cmd {
1569 Subcommand::Run { ref args, .. } => {
1570 args.iter().flat_map(|s| s.split_whitespace()).collect()
1571 }
1572 _ => vec![],
1573 };
1574 args.extend(self.free_args.iter().map(|s| s.as_str()));
1575 args
1576 }
1577
1578 pub(crate) fn read_file_by_commit(&self, file: &Path, commit: &str) -> String {
1580 let dwn_ctx = DownloadContext::from(self);
1581 read_file_by_commit(dwn_ctx, &self.rust_info, file, commit)
1582 }
1583
1584 pub(crate) fn artifact_version_part(&self, commit: &str) -> String {
1587 let (channel, version) = if self.rust_info.is_managed_git_subrepository() {
1588 let channel =
1589 self.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
1590 let version =
1591 self.read_file_by_commit(Path::new("src/version"), commit).trim().to_owned();
1592 (channel, version)
1593 } else {
1594 let channel = fs::read_to_string(self.src.join("src/ci/channel"));
1595 let version = fs::read_to_string(self.src.join("src/version"));
1596 match (channel, version) {
1597 (Ok(channel), Ok(version)) => {
1598 (channel.trim().to_owned(), version.trim().to_owned())
1599 }
1600 (channel, version) => {
1601 let src = self.src.display();
1602 eprintln!("ERROR: failed to determine artifact channel and/or version");
1603 eprintln!(
1604 "HELP: consider using a git checkout or ensure these files are readable"
1605 );
1606 if let Err(channel) = channel {
1607 eprintln!("reading {src}/src/ci/channel failed: {channel:?}");
1608 }
1609 if let Err(version) = version {
1610 eprintln!("reading {src}/src/version failed: {version:?}");
1611 }
1612 panic!();
1613 }
1614 }
1615 };
1616
1617 match channel.as_str() {
1618 "stable" => version,
1619 "beta" => channel,
1620 "nightly" => channel,
1621 other => unreachable!("{:?} is not recognized as a valid channel", other),
1622 }
1623 }
1624
1625 pub fn bindir_relative(&self) -> &Path {
1627 let bindir = &self.bindir;
1628 if bindir.is_absolute() {
1629 if let Some(prefix) = &self.prefix
1631 && let Ok(stripped) = bindir.strip_prefix(prefix)
1632 {
1633 return stripped;
1634 }
1635 }
1636 bindir
1637 }
1638
1639 pub fn libdir_relative(&self) -> Option<&Path> {
1641 let libdir = self.libdir.as_ref()?;
1642 if libdir.is_relative() {
1643 Some(libdir)
1644 } else {
1645 libdir.strip_prefix(self.prefix.as_ref()?).ok()
1647 }
1648 }
1649
1650 pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1652 let dwn_ctx = DownloadContext::from(self);
1653 ci_llvm_root(dwn_ctx, self.llvm_from_ci, &self.out)
1654 }
1655
1656 pub(crate) fn ci_rustc_dir(&self) -> PathBuf {
1658 assert!(self.download_rustc());
1659 self.out.join(self.host_target).join("ci-rustc")
1660 }
1661
1662 pub(crate) fn llvm_link_shared(&self) -> bool {
1667 let mut opt = self.llvm_link_shared.get();
1668 if opt.is_none() && self.dry_run() {
1669 return false;
1671 }
1672
1673 let llvm_link_shared = *opt.get_or_insert_with(|| {
1674 if self.llvm_from_ci {
1675 self.maybe_download_ci_llvm();
1676 let ci_llvm = self.ci_llvm_root();
1677 let link_type = t!(
1678 std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1679 format!("CI llvm missing: {}", ci_llvm.display())
1680 );
1681 link_type == "dynamic"
1682 } else {
1683 false
1686 }
1687 });
1688 self.llvm_link_shared.set(opt);
1689 llvm_link_shared
1690 }
1691
1692 pub(crate) fn download_rustc(&self) -> bool {
1694 self.download_rustc_commit().is_some()
1695 }
1696
1697 pub(crate) fn download_rustc_commit(&self) -> Option<&str> {
1698 static DOWNLOAD_RUSTC: OnceLock<Option<String>> = OnceLock::new();
1699 if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
1700 return self.download_rustc_commit.as_deref();
1702 }
1703
1704 DOWNLOAD_RUSTC
1705 .get_or_init(|| match &self.download_rustc_commit {
1706 None => None,
1707 Some(commit) => {
1708 self.download_ci_rustc(commit);
1709
1710 if !self.llvm_from_ci {
1714 if self.is_running_on_ci() {
1717 println!("WARNING: LLVM submodule has changes, `download-rustc` will be disabled.");
1718 return None;
1719 } else {
1720 panic!("ERROR: LLVM submodule has changes, `download-rustc` can't be used.");
1721 }
1722 }
1723
1724 if let Some(config_path) = &self.config {
1725 let ci_config_toml = match self.get_builder_toml("ci-rustc") {
1726 Ok(ci_config_toml) => ci_config_toml,
1727 Err(e) if e.to_string().contains("unknown field") => {
1728 println!("WARNING: CI rustc has some fields that are no longer supported in bootstrap; download-rustc will be disabled.");
1729 println!("HELP: Consider rebasing to a newer commit if available.");
1730 return None;
1731 }
1732 Err(e) => {
1733 eprintln!("ERROR: Failed to parse CI rustc bootstrap.toml: {e}");
1734 exit!(2);
1735 }
1736 };
1737
1738 let current_config_toml = Self::get_toml(config_path).unwrap();
1739
1740 let res = check_incompatible_options_for_ci_rustc(
1743 self.host_target,
1744 current_config_toml,
1745 ci_config_toml,
1746 );
1747
1748 let disable_ci_rustc_if_incompatible = env::var_os("DISABLE_CI_RUSTC_IF_INCOMPATIBLE")
1751 .is_some_and(|s| s == "1" || s == "true");
1752
1753 if disable_ci_rustc_if_incompatible && res.is_err() {
1754 println!("WARNING: download-rustc is disabled with `DISABLE_CI_RUSTC_IF_INCOMPATIBLE` env.");
1755 return None;
1756 }
1757
1758 res.unwrap();
1759 }
1760
1761 Some(commit.clone())
1762 }
1763 })
1764 .as_deref()
1765 }
1766
1767 pub fn do_if_verbose(&self, f: impl Fn()) {
1769 self.exec_ctx.do_if_verbose(f);
1770 }
1771
1772 pub fn any_sanitizers_to_build(&self) -> bool {
1773 self.target_config
1774 .iter()
1775 .any(|(ts, t)| !ts.is_msvc() && t.sanitizers.unwrap_or(self.sanitizers))
1776 }
1777
1778 pub fn any_profiler_enabled(&self) -> bool {
1779 self.target_config.values().any(|t| matches!(&t.profiler, Some(p) if p.is_string_or_true()))
1780 || self.profiler
1781 }
1782
1783 pub fn submodules(&self) -> bool {
1785 self.submodules.unwrap_or(self.rust_info.is_managed_git_subrepository())
1788 }
1789
1790 pub fn git_config(&self) -> GitConfig<'_> {
1791 GitConfig {
1792 nightly_branch: &self.stage0_metadata.config.nightly_branch,
1793 git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
1794 }
1795 }
1796
1797 #[cfg_attr(
1807 feature = "tracing",
1808 instrument(
1809 level = "trace",
1810 name = "Config::update_submodule",
1811 skip_all,
1812 fields(relative_path = ?relative_path),
1813 ),
1814 )]
1815 pub(crate) fn update_submodule(&self, relative_path: &str) {
1816 let dwn_ctx = DownloadContext::from(self);
1817 update_submodule(dwn_ctx, &self.rust_info, relative_path);
1818 }
1819
1820 pub fn has_changes_from_upstream(&self, paths: &[&'static str]) -> bool {
1822 let dwn_ctx = DownloadContext::from(self);
1823 has_changes_from_upstream(dwn_ctx, paths)
1824 }
1825
1826 pub fn check_path_modifications(&self, paths: &[&'static str]) -> PathFreshness {
1828 self.path_modification_cache
1834 .lock()
1835 .unwrap()
1836 .entry(paths.to_vec())
1837 .or_insert_with(|| {
1838 check_path_modifications(&self.src, &self.git_config(), paths, self.ci_env).unwrap()
1839 })
1840 .clone()
1841 }
1842
1843 pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1844 self.target_config.get(&target).and_then(|t| t.sanitizers).unwrap_or(self.sanitizers)
1845 }
1846
1847 pub fn needs_sanitizer_runtime_built(&self, target: TargetSelection) -> bool {
1848 !target.is_msvc() && self.sanitizers_enabled(target)
1850 }
1851
1852 pub fn profiler_path(&self, target: TargetSelection) -> Option<&str> {
1853 match self.target_config.get(&target)?.profiler.as_ref()? {
1854 StringOrBool::String(s) => Some(s),
1855 StringOrBool::Bool(_) => None,
1856 }
1857 }
1858
1859 pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1860 self.target_config
1861 .get(&target)
1862 .and_then(|t| t.profiler.as_ref())
1863 .map(StringOrBool::is_string_or_true)
1864 .unwrap_or(self.profiler)
1865 }
1866
1867 pub fn enabled_codegen_backends(&self, target: TargetSelection) -> &[CodegenBackendKind] {
1871 self.target_config
1872 .get(&target)
1873 .and_then(|cfg| cfg.codegen_backends.as_deref())
1874 .unwrap_or(&self.rust_codegen_backends)
1875 }
1876
1877 pub fn default_codegen_backend(&self, target: TargetSelection) -> &CodegenBackendKind {
1880 self.enabled_codegen_backends(target).first().unwrap()
1882 }
1883
1884 pub fn jemalloc(&self, target: TargetSelection) -> bool {
1885 self.target_config.get(&target).and_then(|cfg| cfg.jemalloc).unwrap_or(self.jemalloc)
1886 }
1887
1888 pub fn rpath_enabled(&self, target: TargetSelection) -> bool {
1889 self.target_config.get(&target).and_then(|t| t.rpath).unwrap_or(self.rust_rpath)
1890 }
1891
1892 pub fn optimized_compiler_builtins(&self, target: TargetSelection) -> &CompilerBuiltins {
1893 self.target_config
1894 .get(&target)
1895 .and_then(|t| t.optimized_compiler_builtins.as_ref())
1896 .unwrap_or(&self.optimized_compiler_builtins)
1897 }
1898
1899 pub fn llvm_enabled(&self, target: TargetSelection) -> bool {
1900 self.enabled_codegen_backends(target).contains(&CodegenBackendKind::Llvm)
1901 }
1902
1903 pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1904 self.target_config
1905 .get(&target)
1906 .and_then(|t| t.llvm_libunwind)
1907 .or(self.llvm_libunwind_default)
1908 .unwrap_or(
1909 if target.contains("fuchsia")
1910 || (target.contains("hexagon") && !target.contains("qurt"))
1911 {
1912 LlvmLibunwind::InTree
1915 } else {
1916 LlvmLibunwind::No
1917 },
1918 )
1919 }
1920
1921 pub fn split_debuginfo(&self, target: TargetSelection) -> SplitDebuginfo {
1922 self.target_config
1923 .get(&target)
1924 .and_then(|t| t.split_debuginfo)
1925 .unwrap_or_else(|| SplitDebuginfo::default_for_platform(target))
1926 }
1927
1928 pub fn is_host_target(&self, target: TargetSelection) -> bool {
1930 self.host_target == target
1931 }
1932
1933 pub fn is_system_llvm(&self, target: TargetSelection) -> bool {
1938 is_system_llvm(&self.target_config, self.llvm_from_ci, self.host_target, target)
1939 }
1940
1941 pub fn is_rust_llvm(&self, target: TargetSelection) -> bool {
1945 match self.target_config.get(&target) {
1946 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
1950 _ => !self.is_system_llvm(target),
1953 }
1954 }
1955
1956 pub fn exec_ctx(&self) -> &ExecutionContext {
1957 &self.exec_ctx
1958 }
1959
1960 pub fn git_info(&self, omit_git_hash: bool, dir: &Path) -> GitInfo {
1961 GitInfo::new(omit_git_hash, dir, self)
1962 }
1963}
1964
1965impl AsRef<ExecutionContext> for Config {
1966 fn as_ref(&self) -> &ExecutionContext {
1967 &self.exec_ctx
1968 }
1969}
1970
1971fn compute_src_directory(src_dir: Option<PathBuf>, exec_ctx: &ExecutionContext) -> Option<PathBuf> {
1972 if let Some(src) = src_dir {
1973 return Some(src);
1974 } else {
1975 let mut cmd = helpers::git(None);
1978 cmd.arg("rev-parse").arg("--show-cdup");
1986 let output = cmd.allow_failure().run_capture_stdout(exec_ctx);
1988 if output.is_success() {
1989 let git_root_relative = output.stdout();
1990 let git_root = env::current_dir()
1993 .unwrap()
1994 .join(PathBuf::from(git_root_relative.trim()))
1995 .canonicalize()
1996 .unwrap();
1997 let s = git_root.to_str().unwrap();
1998
1999 let git_root = match s.strip_prefix("\\\\?\\") {
2001 Some(p) => PathBuf::from(p),
2002 None => git_root,
2003 };
2004 if git_root.join("src").join("stage0").exists() {
2011 return Some(git_root);
2012 }
2013 } else {
2014 }
2017 };
2018 None
2019}
2020
2021fn load_toml_config(
2026 src: &Path,
2027 config_path: Option<PathBuf>,
2028 get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2029) -> (TomlConfig, Option<PathBuf>) {
2030 let toml_path = config_path.or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
2038 let using_default_path = toml_path.is_none();
2039 let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml"));
2040
2041 if using_default_path && !toml_path.exists() {
2042 toml_path = src.join(PathBuf::from("bootstrap.toml"));
2043 if !toml_path.exists() {
2044 toml_path = PathBuf::from("config.toml");
2045 if !toml_path.exists() {
2046 toml_path = src.join(PathBuf::from("config.toml"));
2047 }
2048 }
2049 }
2050
2051 if !using_default_path || toml_path.exists() {
2054 let path = Some(if cfg!(not(test)) {
2055 toml_path = toml_path.canonicalize().unwrap();
2056 toml_path.clone()
2057 } else {
2058 toml_path.clone()
2059 });
2060 (get_toml(&toml_path).unwrap_or_else(|e| bad_config(&toml_path, e)), path)
2061 } else {
2062 (TomlConfig::default(), None)
2063 }
2064}
2065
2066fn postprocess_toml(
2067 toml: &mut TomlConfig,
2068 src_dir: &Path,
2069 toml_path: Option<PathBuf>,
2070 exec_ctx: &ExecutionContext,
2071 override_set: &[String],
2072 get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2073) {
2074 let git_info = GitInfo::new(false, src_dir, exec_ctx);
2075
2076 if git_info.is_from_tarball() && toml.profile.is_none() {
2077 toml.profile = Some("dist".into());
2078 }
2079
2080 for include_path in toml.include.clone().unwrap_or_default().iter().rev() {
2086 let include_path = toml_path
2087 .as_ref()
2088 .expect("include found in default TOML config")
2089 .parent()
2090 .unwrap()
2091 .join(include_path);
2092
2093 let included_toml =
2094 get_toml(&include_path).unwrap_or_else(|e| bad_config(&include_path, e));
2095 toml.merge(
2096 Some(include_path),
2097 &mut Default::default(),
2098 included_toml,
2099 ReplaceOpt::IgnoreDuplicate,
2100 );
2101 }
2102
2103 if let Some(include) = &toml.profile {
2104 let profile_aliases = HashMap::from([("user", "dist")]);
2108 let include = match profile_aliases.get(include.as_str()) {
2109 Some(alias) => alias,
2110 None => include.as_str(),
2111 };
2112 let mut include_path = PathBuf::from(src_dir);
2113 include_path.push("src");
2114 include_path.push("bootstrap");
2115 include_path.push("defaults");
2116 include_path.push(format!("bootstrap.{include}.toml"));
2117 let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
2118 eprintln!(
2119 "ERROR: Failed to parse default config profile at '{}': {e}",
2120 include_path.display()
2121 );
2122 exit!(2);
2123 });
2124 toml.merge(
2125 Some(include_path),
2126 &mut Default::default(),
2127 included_toml,
2128 ReplaceOpt::IgnoreDuplicate,
2129 );
2130 }
2131
2132 let mut override_toml = TomlConfig::default();
2133 for option in override_set.iter() {
2134 fn get_table(option: &str) -> Result<TomlConfig, toml::de::Error> {
2135 toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table))
2136 }
2137
2138 let mut err = match get_table(option) {
2139 Ok(v) => {
2140 override_toml.merge(None, &mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate);
2141 continue;
2142 }
2143 Err(e) => e,
2144 };
2145 if let Some((key, value)) = option.split_once('=')
2148 && !value.contains('"')
2149 {
2150 match get_table(&format!(r#"{key}="{value}""#)) {
2151 Ok(v) => {
2152 override_toml.merge(
2153 None,
2154 &mut Default::default(),
2155 v,
2156 ReplaceOpt::ErrorOnDuplicate,
2157 );
2158 continue;
2159 }
2160 Err(e) => err = e,
2161 }
2162 }
2163 eprintln!("failed to parse override `{option}`: `{err}");
2164 exit!(2)
2165 }
2166 toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override);
2167}
2168
2169#[cfg(test)]
2170pub fn check_stage0_version(
2171 _program_path: &Path,
2172 _component_name: &'static str,
2173 _src_dir: &Path,
2174 _exec_ctx: &ExecutionContext,
2175) {
2176}
2177
2178#[cfg(not(test))]
2180pub fn check_stage0_version(
2181 program_path: &Path,
2182 component_name: &'static str,
2183 src_dir: &Path,
2184 exec_ctx: &ExecutionContext,
2185) {
2186 use build_helper::util::fail;
2187
2188 if exec_ctx.dry_run() {
2189 return;
2190 }
2191
2192 let stage0_output =
2193 command(program_path).arg("--version").run_capture_stdout(exec_ctx).stdout();
2194 let mut stage0_output = stage0_output.lines().next().unwrap().split(' ');
2195
2196 let stage0_name = stage0_output.next().unwrap();
2197 if stage0_name != component_name {
2198 fail(&format!(
2199 "Expected to find {component_name} at {} but it claims to be {stage0_name}",
2200 program_path.display()
2201 ));
2202 }
2203
2204 let stage0_version =
2205 semver::Version::parse(stage0_output.next().unwrap().split('-').next().unwrap().trim())
2206 .unwrap();
2207 let source_version =
2208 semver::Version::parse(fs::read_to_string(src_dir.join("src/version")).unwrap().trim())
2209 .unwrap();
2210 if !(source_version == stage0_version
2211 || (source_version.major == stage0_version.major
2212 && (source_version.minor == stage0_version.minor
2213 || source_version.minor == stage0_version.minor + 1)))
2214 {
2215 let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1);
2216 fail(&format!(
2217 "Unexpected {component_name} version: {stage0_version}, we should use {prev_version}/{source_version} to build source with {source_version}"
2218 ));
2219 }
2220}
2221
2222fn print_rustc_modifications(
2223 dwn_ctx: &DownloadContext<'_>,
2224 if_unchanged: bool,
2225 mut modifications: Vec<PathBuf>,
2226) -> Option<()> {
2227 if !dwn_ctx.exec_ctx.is_verbose() {
2228 modifications.retain(|path| !path.starts_with("compiler"));
2229 }
2230 if modifications.is_empty() {
2231 eprintln!(
2233 "skipping rustc download with `download-rustc = 'if-unchanged'` due to local changes"
2234 );
2235 return None;
2236 }
2237
2238 eprintln!(
2239 "NOTE: detected {} modifications that could affect a build of rustc",
2240 modifications.len()
2241 );
2242 for file in modifications.iter().take(10) {
2243 eprintln!("- {}", file.display());
2244 }
2245 if modifications.len() > 10 {
2246 eprintln!("- ... and {} more", modifications.len() - 10);
2247 }
2248
2249 if if_unchanged {
2250 eprintln!("skipping rustc download due to `download-rustc = 'if-unchanged'`");
2251 None
2252 } else {
2253 eprintln!("downloading unconditionally due to `download-rustc = true`");
2254 Some(())
2255 }
2256}
2257
2258pub fn download_ci_rustc_commit<'a>(
2259 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2260 rust_info: &channel::GitInfo,
2261 download_rustc: Option<StringOrBool>,
2262 llvm_assertions: bool,
2263) -> Option<String> {
2264 let dwn_ctx = dwn_ctx.as_ref();
2265
2266 if !is_download_ci_available(&dwn_ctx.host_target.triple, llvm_assertions) {
2267 return None;
2268 }
2269
2270 let if_unchanged = match download_rustc {
2272 None | Some(StringOrBool::Bool(false)) => return None,
2278 Some(StringOrBool::Bool(true)) => false,
2279 Some(StringOrBool::String(s)) if s == "if-unchanged" => {
2280 if !rust_info.is_managed_git_subrepository() {
2281 println!(
2282 "ERROR: `download-rustc=if-unchanged` is only compatible with Git managed sources."
2283 );
2284 crate::exit!(1);
2285 }
2286
2287 true
2288 }
2289 Some(StringOrBool::String(other)) => {
2290 panic!("unrecognized option for download-rustc: {other}")
2291 }
2292 };
2293
2294 let commit = if rust_info.is_managed_git_subrepository() {
2295 let freshness = check_path_modifications_(dwn_ctx, RUSTC_IF_UNCHANGED_ALLOWED_PATHS);
2298 dwn_ctx.exec_ctx.do_if_verbose(|| {
2299 eprintln!("rustc freshness: {freshness:?}");
2300 });
2301 match freshness {
2302 PathFreshness::LastModifiedUpstream { upstream } => upstream,
2303 PathFreshness::HasLocalModifications { upstream, modifications } => {
2304 if dwn_ctx.is_running_on_ci() {
2305 eprintln!("CI rustc commit matches with HEAD and we are in CI.");
2306 eprintln!(
2307 "`rustc.download-ci` functionality will be skipped as artifacts are not available."
2308 );
2309 return None;
2310 }
2311
2312 print_rustc_modifications(dwn_ctx, if_unchanged, modifications)?;
2313 upstream
2314 }
2315 PathFreshness::MissingUpstream => {
2316 eprintln!("No upstream commit found");
2317 return None;
2318 }
2319 }
2320 } else {
2321 channel::read_commit_info_file(dwn_ctx.src)
2322 .map(|info| info.sha.trim().to_owned())
2323 .expect("git-commit-info is missing in the project root")
2324 };
2325
2326 Some(commit)
2327}
2328
2329pub fn check_path_modifications_<'a>(
2330 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2331 paths: &[&'static str],
2332) -> PathFreshness {
2333 let dwn_ctx = dwn_ctx.as_ref();
2334 dwn_ctx
2340 .path_modification_cache
2341 .lock()
2342 .unwrap()
2343 .entry(paths.to_vec())
2344 .or_insert_with(|| {
2345 check_path_modifications(
2346 dwn_ctx.src,
2347 &git_config(dwn_ctx.stage0_metadata),
2348 paths,
2349 dwn_ctx.ci_env,
2350 )
2351 .unwrap()
2352 })
2353 .clone()
2354}
2355
2356pub fn git_config(stage0_metadata: &build_helper::stage0_parser::Stage0) -> GitConfig<'_> {
2357 GitConfig {
2358 nightly_branch: &stage0_metadata.config.nightly_branch,
2359 git_merge_commit_email: &stage0_metadata.config.git_merge_commit_email,
2360 }
2361}
2362
2363pub fn parse_download_ci_llvm<'a>(
2364 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2365 rust_info: &channel::GitInfo,
2366 download_rustc_commit: &Option<String>,
2367 download_ci_llvm: Option<StringOrBool>,
2368 asserts: bool,
2369) -> bool {
2370 let dwn_ctx = dwn_ctx.as_ref();
2371 let download_ci_llvm = download_ci_llvm.unwrap_or(StringOrBool::Bool(true));
2372
2373 let if_unchanged = || {
2374 if rust_info.is_from_tarball() {
2375 println!("ERROR: 'if-unchanged' is only compatible with Git managed sources.");
2377 crate::exit!(1);
2378 }
2379
2380 #[cfg(not(test))]
2382 update_submodule(dwn_ctx, rust_info, "src/llvm-project");
2383
2384 let has_changes = has_changes_from_upstream(dwn_ctx, LLVM_INVALIDATION_PATHS);
2386
2387 if has_changes {
2389 false
2390 } else {
2391 llvm::is_ci_llvm_available_for_target(&dwn_ctx.host_target, asserts)
2392 }
2393 };
2394
2395 match download_ci_llvm {
2396 StringOrBool::Bool(b) => {
2397 if !b && download_rustc_commit.is_some() {
2398 panic!(
2399 "`llvm.download-ci-llvm` cannot be set to `false` if `rust.download-rustc` is set to `true` or `if-unchanged`."
2400 );
2401 }
2402
2403 #[cfg(not(test))]
2404 if b && dwn_ctx.is_running_on_ci() && CiEnv::is_rust_lang_managed_ci_job() {
2405 panic!(
2407 "`llvm.download-ci-llvm` cannot be set to `true` on CI. Use `if-unchanged` instead."
2408 );
2409 }
2410
2411 b && llvm::is_ci_llvm_available_for_target(&dwn_ctx.host_target, asserts)
2413 }
2414 StringOrBool::String(s) if s == "if-unchanged" => if_unchanged(),
2415 StringOrBool::String(other) => {
2416 panic!("unrecognized option for download-ci-llvm: {other:?}")
2417 }
2418 }
2419}
2420
2421pub fn has_changes_from_upstream<'a>(
2422 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2423 paths: &[&'static str],
2424) -> bool {
2425 let dwn_ctx = dwn_ctx.as_ref();
2426 match check_path_modifications_(dwn_ctx, paths) {
2427 PathFreshness::LastModifiedUpstream { .. } => false,
2428 PathFreshness::HasLocalModifications { .. } | PathFreshness::MissingUpstream => true,
2429 }
2430}
2431
2432#[cfg_attr(
2433 feature = "tracing",
2434 instrument(
2435 level = "trace",
2436 name = "Config::update_submodule",
2437 skip_all,
2438 fields(relative_path = ?relative_path),
2439 ),
2440)]
2441pub(crate) fn update_submodule<'a>(
2442 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2443 rust_info: &channel::GitInfo,
2444 relative_path: &str,
2445) {
2446 let dwn_ctx = dwn_ctx.as_ref();
2447 if rust_info.is_from_tarball() || !submodules_(dwn_ctx.submodules, rust_info) {
2448 return;
2449 }
2450
2451 let absolute_path = dwn_ctx.src.join(relative_path);
2452
2453 if !absolute_path.exists() {
2457 t!(fs::create_dir_all(&absolute_path));
2458 }
2459
2460 if !git_info(dwn_ctx.exec_ctx, false, &absolute_path).is_managed_git_subrepository()
2463 && !helpers::dir_is_empty(&absolute_path)
2464 {
2465 return;
2466 }
2467
2468 let submodule_git = || helpers::git(Some(&absolute_path));
2469
2470 let checked_out_hash =
2472 submodule_git().args(["rev-parse", "HEAD"]).run_capture_stdout(dwn_ctx.exec_ctx).stdout();
2473 let checked_out_hash = checked_out_hash.trim_end();
2474 let recorded = helpers::git(Some(dwn_ctx.src))
2476 .run_in_dry_run() .args(["ls-tree", "HEAD"])
2478 .arg(relative_path)
2479 .run_capture_stdout(dwn_ctx.exec_ctx)
2480 .stdout();
2481
2482 let actual_hash = recorded
2483 .split_whitespace()
2484 .nth(2)
2485 .unwrap_or_else(|| panic!("unexpected output `{recorded}` when updating {relative_path}"));
2486
2487 if actual_hash == checked_out_hash {
2488 return;
2490 }
2491
2492 if !dwn_ctx.exec_ctx.dry_run() {
2493 println!("Updating submodule {relative_path}");
2494 };
2495
2496 helpers::git(Some(dwn_ctx.src))
2497 .allow_failure()
2498 .args(["submodule", "-q", "sync"])
2499 .arg(relative_path)
2500 .run(dwn_ctx.exec_ctx);
2501
2502 let update = |progress: bool| {
2504 let current_branch = helpers::git(Some(dwn_ctx.src))
2507 .allow_failure()
2508 .args(["symbolic-ref", "--short", "HEAD"])
2509 .run_capture(dwn_ctx.exec_ctx);
2510
2511 let mut git = helpers::git(Some(dwn_ctx.src)).allow_failure();
2512 if current_branch.is_success() {
2513 let branch = current_branch.stdout();
2516 let branch = branch.trim();
2517 let branch = branch.strip_prefix("heads/").unwrap_or(branch);
2518 git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
2519 }
2520 git.args(["submodule", "update", "--init", "--recursive", "--depth=1"]);
2521 if progress {
2522 git.arg("--progress");
2523 }
2524 git.arg(relative_path);
2525 git
2526 };
2527 if !update(true).allow_failure().run(dwn_ctx.exec_ctx) {
2528 update(false).allow_failure().run(dwn_ctx.exec_ctx);
2529 }
2530
2531 let has_local_modifications = !submodule_git()
2534 .allow_failure()
2535 .args(["diff-index", "--quiet", "HEAD"])
2536 .run(dwn_ctx.exec_ctx);
2537 if has_local_modifications {
2538 submodule_git().allow_failure().args(["stash", "push"]).run(dwn_ctx.exec_ctx);
2539 }
2540
2541 submodule_git().allow_failure().args(["reset", "-q", "--hard"]).run(dwn_ctx.exec_ctx);
2542 submodule_git().allow_failure().args(["clean", "-qdfx"]).run(dwn_ctx.exec_ctx);
2543
2544 if has_local_modifications {
2545 submodule_git().allow_failure().args(["stash", "pop"]).run(dwn_ctx.exec_ctx);
2546 }
2547}
2548
2549pub fn git_info(exec_ctx: &ExecutionContext, omit_git_hash: bool, dir: &Path) -> GitInfo {
2550 GitInfo::new(omit_git_hash, dir, exec_ctx)
2551}
2552
2553pub fn submodules_(submodules: &Option<bool>, rust_info: &channel::GitInfo) -> bool {
2554 submodules.unwrap_or(rust_info.is_managed_git_subrepository())
2557}
2558
2559pub fn is_system_llvm(
2564 target_config: &HashMap<TargetSelection, Target>,
2565 llvm_from_ci: bool,
2566 host_target: TargetSelection,
2567 target: TargetSelection,
2568) -> bool {
2569 match target_config.get(&target) {
2570 Some(Target { llvm_config: Some(_), .. }) => {
2571 let ci_llvm = llvm_from_ci && is_host_target(&host_target, &target);
2572 !ci_llvm
2573 }
2574 Some(Target { llvm_config: None, .. }) => false,
2576 None => false,
2577 }
2578}
2579
2580pub fn is_host_target(host_target: &TargetSelection, target: &TargetSelection) -> bool {
2581 host_target == target
2582}
2583
2584pub(crate) fn ci_llvm_root<'a>(
2585 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2586 llvm_from_ci: bool,
2587 out: &Path,
2588) -> PathBuf {
2589 let dwn_ctx = dwn_ctx.as_ref();
2590 assert!(llvm_from_ci);
2591 out.join(dwn_ctx.host_target).join("ci-llvm")
2592}
2593
2594pub(crate) fn read_file_by_commit<'a>(
2596 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2597 rust_info: &channel::GitInfo,
2598 file: &Path,
2599 commit: &str,
2600) -> String {
2601 let dwn_ctx = dwn_ctx.as_ref();
2602 assert!(
2603 rust_info.is_managed_git_subrepository(),
2604 "`Config::read_file_by_commit` is not supported in non-git sources."
2605 );
2606
2607 let mut git = helpers::git(Some(dwn_ctx.src));
2608 git.arg("show").arg(format!("{commit}:{}", file.to_str().unwrap()));
2609 git.run_capture_stdout(dwn_ctx.exec_ctx).stdout()
2610}
2611
2612fn bad_config(toml_path: &Path, e: toml::de::Error) -> ! {
2613 eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display());
2614 let e_s = e.to_string();
2615 if e_s.contains("unknown field")
2616 && let Some(field_name) = e_s.split("`").nth(1)
2617 && let sections = find_correct_section_for_field(field_name)
2618 && !sections.is_empty()
2619 {
2620 if sections.len() == 1 {
2621 match sections[0] {
2622 WouldBeValidFor::TopLevel { is_section } => {
2623 if is_section {
2624 eprintln!(
2625 "hint: section name `{field_name}` used as a key within a section"
2626 );
2627 } else {
2628 eprintln!("hint: try using `{field_name}` as a top level key");
2629 }
2630 }
2631 WouldBeValidFor::Section(section) => {
2632 eprintln!("hint: try moving `{field_name}` to the `{section}` section")
2633 }
2634 }
2635 } else {
2636 eprintln!(
2637 "hint: `{field_name}` would be valid {}",
2638 join_oxford_comma(sections.iter(), "or"),
2639 );
2640 }
2641 }
2642
2643 exit!(2);
2644}
2645
2646#[derive(Copy, Clone, Debug)]
2647enum WouldBeValidFor {
2648 TopLevel { is_section: bool },
2649 Section(&'static str),
2650}
2651
2652fn join_oxford_comma(
2653 mut parts: impl ExactSizeIterator<Item = impl std::fmt::Display>,
2654 conj: &str,
2655) -> String {
2656 use std::fmt::Write;
2657 let mut out = String::new();
2658
2659 assert!(parts.len() > 1);
2660 while let Some(part) = parts.next() {
2661 if parts.len() == 0 {
2662 write!(&mut out, "{conj} {part}")
2663 } else {
2664 write!(&mut out, "{part}, ")
2665 }
2666 .unwrap();
2667 }
2668 out
2669}
2670
2671impl std::fmt::Display for WouldBeValidFor {
2672 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2673 match self {
2674 Self::TopLevel { .. } => write!(f, "at top level"),
2675 Self::Section(section_name) => write!(f, "in section `{section_name}`"),
2676 }
2677 }
2678}
2679
2680fn find_correct_section_for_field(field_name: &str) -> Vec<WouldBeValidFor> {
2681 let sections = ["build", "install", "llvm", "gcc", "rust", "dist"];
2682 sections
2683 .iter()
2684 .map(Some)
2685 .chain([None])
2686 .filter_map(|section_name| {
2687 let dummy_config_str = if let Some(section_name) = section_name {
2688 format!("{section_name}.{field_name} = 0\n")
2689 } else {
2690 format!("{field_name} = 0\n")
2691 };
2692 let is_unknown_field = toml::from_str::<toml::Value>(&dummy_config_str)
2693 .and_then(TomlConfig::deserialize)
2694 .err()
2695 .is_some_and(|e| e.to_string().contains("unknown field"));
2696 if is_unknown_field {
2697 None
2698 } else {
2699 Some(section_name.copied().map(WouldBeValidFor::Section).unwrap_or_else(|| {
2700 WouldBeValidFor::TopLevel { is_section: sections.contains(&field_name) }
2701 }))
2702 }
2703 })
2704 .collect()
2705}