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, 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, 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_compress_debuginfo: CompressDebuginfo,
214 pub rust_rpath: bool,
215 pub rust_strip: bool,
216 pub rust_frame_pointers: bool,
217 pub rust_stack_protector: Option<String>,
218 pub rustc_default_linker: Option<String>,
219 pub rust_optimize_tests: bool,
220 pub rust_dist_src: bool,
221 pub rust_codegen_backends: Vec<CodegenBackendKind>,
222 pub rust_verify_llvm_ir: bool,
223 pub rust_thin_lto_import_instr_limit: Option<u32>,
224 pub rust_randomize_layout: bool,
225 pub rust_remap_debuginfo: bool,
226 pub rust_new_symbol_mangling: Option<bool>,
227 pub rust_annotate_moves_size_limit: Option<u64>,
228 pub rust_profile_use: Option<String>,
229 pub rust_profile_generate: Option<String>,
230 pub rust_lto: RustcLto,
231 pub rust_validate_mir_opts: Option<u32>,
232 pub rust_std_features: BTreeSet<String>,
233 pub rust_break_on_ice: bool,
234 pub rust_parallel_frontend_threads: Option<u32>,
235 pub rust_rustflags: Vec<String>,
236
237 pub llvm_profile_use: Option<String>,
238 pub llvm_profile_generate: bool,
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 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 pub backtrace: bool, 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 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 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 pub paths: Vec<PathBuf>,
314
315 pub compiletest_diff_tool: Option<String>,
317
318 pub compiletest_allow_stage0: bool,
324
325 pub tidy_extra_checks: Option<String>,
327 pub ci_env: CiEnv,
328
329 pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
331
332 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 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 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 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 let (mut toml, toml_path) = load_toml_config(&src, flags_config, &get_toml);
459
460 postprocess_toml(&mut toml, &src, toml_path.clone(), &exec_ctx, &flags_set, &get_toml);
461
462 let Build {
465 description: build_description,
466 build: build_build,
467 host: build_host,
468 target: build_target,
469 build_dir: build_build_dir,
470 cargo: mut build_cargo,
471 rustc: mut build_rustc,
472 rustdoc: build_rustdoc,
473 rustfmt: build_rustfmt,
474 cargo_clippy: build_cargo_clippy,
475 docs: build_docs,
476 compiler_docs: build_compiler_docs,
477 library_docs_private_items: build_library_docs_private_items,
478 docs_minification: build_docs_minification,
479 submodules: build_submodules,
480 gdb: build_gdb,
481 lldb: build_lldb,
482 nodejs: build_nodejs,
483
484 yarn: build_yarn,
485 npm: build_npm,
486 python: build_python,
487 windows_rc: build_windows_rc,
488 reuse: build_reuse,
489 locked_deps: build_locked_deps,
490 vendor: build_vendor,
491 full_bootstrap: build_full_bootstrap,
492 bootstrap_cache_path: build_bootstrap_cache_path,
493 extended: build_extended,
494 tools: build_tools,
495 tool: build_tool,
496 verbose: build_verbose,
497 sanitizers: build_sanitizers,
498 profiler: build_profiler,
499 cargo_native_static: build_cargo_native_static,
500 low_priority: build_low_priority,
501 configure_args: build_configure_args,
502 local_rebuild: build_local_rebuild,
503 print_step_timings: build_print_step_timings,
504 print_step_rusage: build_print_step_rusage,
505 check_stage: build_check_stage,
506 doc_stage: build_doc_stage,
507 build_stage: build_build_stage,
508 test_stage: build_test_stage,
509 install_stage: build_install_stage,
510 dist_stage: build_dist_stage,
511 bench_stage: build_bench_stage,
512 patch_binaries_for_nix: build_patch_binaries_for_nix,
513 record_failed_tests_path: build_record_failed_tests_path,
514 metrics: _,
516 android_ndk: build_android_ndk,
517 optimized_compiler_builtins: build_optimized_compiler_builtins,
518 jobs: build_jobs,
519 compiletest_diff_tool: build_compiletest_diff_tool,
520 compiletest_use_stage0_libtest: _,
522 tidy_extra_checks: build_tidy_extra_checks,
523 ccache: build_ccache,
524 exclude: build_exclude,
525 compiletest_allow_stage0: build_compiletest_allow_stage0,
526 } = toml.build.unwrap_or_default();
527
528 let Install {
529 prefix: install_prefix,
530 sysconfdir: install_sysconfdir,
531 docdir: install_docdir,
532 bindir: install_bindir,
533 libdir: install_libdir,
534 mandir: install_mandir,
535 datadir: install_datadir,
536 } = toml.install.unwrap_or_default();
537
538 let Rust {
539 optimize: rust_optimize,
540 debug: rust_debug,
541 codegen_units: rust_codegen_units,
542 codegen_units_std: rust_codegen_units_std,
543 rustc_debug_assertions: rust_rustc_debug_assertions,
544 std_debug_assertions: rust_std_debug_assertions,
545 tools_debug_assertions: rust_tools_debug_assertions,
546 overflow_checks: rust_overflow_checks,
547 overflow_checks_std: rust_overflow_checks_std,
548 debug_logging: rust_debug_logging,
549 debuginfo_level: rust_debuginfo_level,
550 debuginfo_level_rustc: rust_debuginfo_level_rustc,
551 debuginfo_level_std: rust_debuginfo_level_std,
552 debuginfo_level_tools: rust_debuginfo_level_tools,
553 debuginfo_level_tests: rust_debuginfo_level_tests,
554 compress_debuginfo: rust_compress_debuginfo,
555 backtrace: rust_backtrace,
556 incremental: rust_incremental,
557 randomize_layout: rust_randomize_layout,
558 default_linker: rust_default_linker,
559 channel: rust_channel,
560 musl_root: rust_musl_root,
561 rpath: rust_rpath,
562 verbose_tests: rust_verbose_tests,
563 optimize_tests: rust_optimize_tests,
564 codegen_tests: rust_codegen_tests,
565 omit_git_hash: rust_omit_git_hash,
566 dist_src: rust_dist_src,
567 save_toolstates: rust_save_toolstates,
568 codegen_backends: rust_codegen_backends,
569 lld: rust_lld_enabled,
570 llvm_tools: rust_llvm_tools,
571 llvm_bitcode_linker: rust_llvm_bitcode_linker,
572 deny_warnings: rust_deny_warnings,
573 backtrace_on_ice: rust_backtrace_on_ice,
574 verify_llvm_ir: rust_verify_llvm_ir,
575 thin_lto_import_instr_limit: rust_thin_lto_import_instr_limit,
576 parallel_frontend_threads: rust_parallel_frontend_threads,
577 remap_debuginfo: rust_remap_debuginfo,
578 jemalloc: rust_jemalloc,
579 test_compare_mode: rust_test_compare_mode,
580 llvm_libunwind: rust_llvm_libunwind,
581 control_flow_guard: rust_control_flow_guard,
582 ehcont_guard: rust_ehcont_guard,
583 new_symbol_mangling: rust_new_symbol_mangling,
584 annotate_moves_size_limit: rust_annotate_moves_size_limit,
585 profile_generate: rust_profile_generate,
586 profile_use: rust_profile_use,
587 download_rustc: rust_download_rustc,
588 lto: rust_lto,
589 validate_mir_opts: rust_validate_mir_opts,
590 frame_pointers: rust_frame_pointers,
591 stack_protector: rust_stack_protector,
592 strip: rust_strip,
593 bootstrap_override_lld: rust_bootstrap_override_lld,
594 bootstrap_override_lld_legacy: rust_bootstrap_override_lld_legacy,
595 std_features: rust_std_features,
596 break_on_ice: rust_break_on_ice,
597 rustflags: rust_rustflags,
598 } = toml.rust.unwrap_or_default();
599
600 let Llvm {
601 optimize: llvm_optimize,
602 thin_lto: llvm_thin_lto,
603 release_debuginfo: llvm_release_debuginfo,
604 assertions: llvm_assertions,
605 tests: llvm_tests,
606 enzyme: llvm_enzyme,
607 plugins: llvm_plugin,
608 static_libstdcpp: llvm_static_libstdcpp,
609 libzstd: llvm_libzstd,
610 ninja: llvm_ninja,
611 targets: llvm_targets,
612 experimental_targets: llvm_experimental_targets,
613 link_jobs: llvm_link_jobs,
614 link_shared: llvm_link_shared,
615 version_suffix: llvm_version_suffix,
616 clang_cl: llvm_clang_cl,
617 cflags: llvm_cflags,
618 cxxflags: llvm_cxxflags,
619 ldflags: llvm_ldflags,
620 use_libcxx: llvm_use_libcxx,
621 use_linker: llvm_use_linker,
622 allow_old_toolchain: llvm_allow_old_toolchain,
623 offload: llvm_offload,
624 offload_clang_dir: llvm_clang_dir,
625 polly: llvm_polly,
626 clang: llvm_clang,
627 enable_warnings: llvm_enable_warnings,
628 download_ci_llvm: llvm_download_ci_llvm,
629 build_config: llvm_build_config,
630 } = toml.llvm.unwrap_or_default();
631
632 let Dist {
633 sign_folder: dist_sign_folder,
634 upload_addr: dist_upload_addr,
635 src_tarball: dist_src_tarball,
636 compression_formats: dist_compression_formats,
637 compression_profile: dist_compression_profile,
638 include_mingw_linker: dist_include_mingw_linker,
639 vendor: dist_vendor,
640 } = toml.dist.unwrap_or_default();
641
642 let Gcc {
643 download_ci_gcc: gcc_download_ci_gcc,
644 libgccjit_libs_dir: gcc_libgccjit_libs_dir,
645 } = toml.gcc.unwrap_or_default();
646
647 if rust_bootstrap_override_lld.is_some() && rust_bootstrap_override_lld_legacy.is_some() {
648 panic!(
649 "Cannot use both `rust.use-lld` and `rust.bootstrap-override-lld`. Please use only `rust.bootstrap-override-lld`"
650 );
651 }
652
653 let bootstrap_override_lld =
654 rust_bootstrap_override_lld.or(rust_bootstrap_override_lld_legacy).unwrap_or_default();
655
656 if rust_optimize.as_ref().is_some_and(|v| matches!(v, RustOptimize::Bool(false))) {
657 eprintln!(
658 "WARNING: setting `optimize` to `false` is known to cause errors and \
659 should be considered unsupported. Refer to `bootstrap.example.toml` \
660 for more details."
661 );
662 }
663
664 exec_ctx.set_verbosity(cmp::max(build_verbose.unwrap_or_default() as u8, flags_verbose));
667
668 let stage0_metadata = build_helper::stage0_parser::parse_stage0_file();
669 let path_modification_cache = Arc::new(Mutex::new(HashMap::new()));
670
671 let host_target = flags_build
672 .or(build_build)
673 .map(|build| TargetSelection::from_user(&build))
674 .unwrap_or_else(get_host_target);
675 let hosts = flags_host
676 .map(|TargetSelectionList(hosts)| hosts)
677 .or_else(|| {
678 build_host.map(|h| h.iter().map(|t| TargetSelection::from_user(t)).collect())
679 })
680 .unwrap_or_else(|| vec![host_target]);
681
682 let llvm_assertions = llvm_assertions.unwrap_or(false);
683 let mut target_config = HashMap::new();
684 let mut channel = "dev".to_string();
685
686 let out = flags_build_dir.or_else(|| build_build_dir.map(PathBuf::from));
687 let out = if cfg!(test) {
688 out.expect("--build-dir has to be specified in tests")
689 } else {
690 out.unwrap_or_else(|| PathBuf::from("build"))
691 };
692
693 let mut out = if !out.is_absolute() {
696 absolute(&out).expect("can't make empty path absolute")
698 } else {
699 out
700 };
701
702 let default_stage0_rustc_path = |dir: &Path| {
703 dir.join(host_target).join("stage0").join("bin").join(exe("rustc", host_target))
704 };
705
706 if cfg!(test) {
707 build_rustc = build_rustc.take().or(std::env::var_os("RUSTC").map(|p| p.into()));
713 build_cargo = build_cargo.take().or(std::env::var_os("CARGO").map(|p| p.into()));
714
715 let is_test_outside_x = std::env::var("CARGO_TARGET_DIR").is_err();
721 if is_test_outside_x && build_rustc.is_none() {
722 let stage0_rustc = default_stage0_rustc_path(&default_src_dir.join("build"));
723 assert!(
724 stage0_rustc.exists(),
725 "Trying to run cargo test without having a stage0 rustc available in {}",
726 stage0_rustc.display()
727 );
728 build_rustc = Some(stage0_rustc);
729 }
730 }
731
732 if !flags_skip_stage0_validation {
733 if let Some(rustc) = &build_rustc {
734 check_stage0_version(rustc, "rustc", &src, &exec_ctx);
735 }
736 if let Some(cargo) = &build_cargo {
737 check_stage0_version(cargo, "cargo", &src, &exec_ctx);
738 }
739 }
740
741 if build_cargo_clippy.is_some() && build_rustc.is_none() {
742 println!(
743 "WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict."
744 );
745 }
746
747 let ci_env = match flags_ci {
748 Some(true) => CiEnv::GitHubActions,
749 Some(false) => CiEnv::None,
750 None => CiEnv::current(),
751 };
752 let dwn_ctx = DownloadContext {
753 path_modification_cache: path_modification_cache.clone(),
754 src: &src,
755 submodules: &build_submodules,
756 host_target,
757 patch_binaries_for_nix: build_patch_binaries_for_nix,
758 exec_ctx: &exec_ctx,
759 stage0_metadata: &stage0_metadata,
760 llvm_assertions,
761 bootstrap_cache_path: &build_bootstrap_cache_path,
762 ci_env,
763 };
764
765 let initial_rustc = build_rustc.unwrap_or_else(|| {
766 download_beta_toolchain(&dwn_ctx, &out);
767 default_stage0_rustc_path(&out)
768 });
769
770 let initial_rustdoc = build_rustdoc
771 .unwrap_or_else(|| initial_rustc.with_file_name(exe("rustdoc", host_target)));
772
773 let initial_sysroot = t!(PathBuf::from_str(
774 command(&initial_rustc)
775 .args(["--print", "sysroot"])
776 .run_in_dry_run()
777 .run_capture_stdout(&exec_ctx)
778 .stdout()
779 .trim()
780 ));
781
782 let initial_cargo = build_cargo.unwrap_or_else(|| {
783 download_beta_toolchain(&dwn_ctx, &out);
784 initial_sysroot.join("bin").join(exe("cargo", host_target))
785 });
786
787 if exec_ctx.dry_run() {
789 out = out.join("tmp-dry-run");
790 fs::create_dir_all(&out).expect("Failed to create dry-run directory");
791 }
792
793 let file_content = t!(fs::read_to_string(src.join("src/ci/channel")));
794 let ci_channel = file_content.trim_end();
795
796 let is_user_configured_rust_channel = match rust_channel {
797 Some(channel_) if channel_ == "auto-detect" => {
798 channel = ci_channel.into();
799 true
800 }
801 Some(channel_) => {
802 channel = channel_;
803 true
804 }
805 None => false,
806 };
807
808 let omit_git_hash = rust_omit_git_hash.unwrap_or(channel == "dev");
809
810 let rust_info = git_info(&exec_ctx, omit_git_hash, &src);
811
812 if !is_user_configured_rust_channel && rust_info.is_from_tarball() {
813 channel = ci_channel.into();
814 }
815
816 let debug_assertions_requested = matches!(rust_rustc_debug_assertions, Some(true))
827 || (matches!(rust_debug, Some(true))
828 && !matches!(rust_rustc_debug_assertions, Some(false)));
829
830 if debug_assertions_requested
831 && let Some(ref opt) = rust_download_rustc
832 && opt.is_string_or_true()
833 {
834 eprintln!(
835 "WARN: currently no CI rustc builds have rustc debug assertions \
836 enabled. Please either set `rust.debug-assertions` to `false` if you \
837 want to use download CI rustc or set `rust.download-rustc` to `false`."
838 );
839 }
840
841 let mut download_rustc_commit =
842 download_ci_rustc_commit(&dwn_ctx, &rust_info, rust_download_rustc, llvm_assertions);
843
844 if debug_assertions_requested && download_rustc_commit.is_some() {
845 eprintln!(
846 "WARN: `rust.debug-assertions = true` will prevent downloading CI rustc as alt CI \
847 rustc is not currently built with debug assertions."
848 );
849 download_rustc_commit = None;
851 }
852
853 if let Some(commit) = &download_rustc_commit
857 && is_user_configured_rust_channel
858 {
859 println!(
860 "WARNING: `rust.download-rustc` is enabled. The `rust.channel` option will be overridden by the CI rustc's channel."
861 );
862
863 channel =
864 read_file_by_commit(&dwn_ctx, &rust_info, Path::new("src/ci/channel"), commit)
865 .trim()
866 .to_owned();
867 }
868
869 if build_npm.is_some() {
870 println!(
871 "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."
872 );
873 }
874
875 let mut lld_enabled = rust_lld_enabled.unwrap_or(false);
876
877 let mut targets_with_user_linker_override = HashSet::new();
879
880 if let Some(t) = toml.target {
881 for (triple, cfg) in t {
882 let TomlTarget {
883 cc: target_cc,
884 cxx: target_cxx,
885 ar: target_ar,
886 ranlib: target_ranlib,
887 default_linker: target_default_linker,
888 default_linker_linux_override: target_default_linker_linux_override,
889 linker: target_linker,
890 split_debuginfo: target_split_debuginfo,
891 llvm_config: target_llvm_config,
892 llvm_has_rust_patches: target_llvm_has_rust_patches,
893 llvm_filecheck: target_llvm_filecheck,
894 llvm_libunwind: target_llvm_libunwind,
895 sanitizers: target_sanitizers,
896 profiler: target_profiler,
897 rpath: target_rpath,
898 rustflags: target_rustflags,
899 crt_static: target_crt_static,
900 musl_root: target_musl_root,
901 musl_libdir: target_musl_libdir,
902 wasi_root: target_wasi_root,
903 qemu_rootfs: target_qemu_rootfs,
904 no_std: target_no_std,
905 codegen_backends: target_codegen_backends,
906 runner: target_runner,
907 optimized_compiler_builtins: target_optimized_compiler_builtins,
908 jemalloc: target_jemalloc,
909 } = cfg;
910
911 let mut target = Target::from_triple(&triple);
912
913 if target_default_linker_linux_override.is_some() {
914 targets_with_user_linker_override.insert(triple.clone());
915 }
916
917 let default_linker_linux_override = match target_default_linker_linux_override {
918 Some(DefaultLinuxLinkerOverride::SelfContainedLldCc) => {
919 if rust_default_linker.is_some() {
920 panic!(
921 "cannot set both `default-linker` and `default-linker-linux` for target `{triple}`"
922 );
923 }
924 if !triple.contains("linux-gnu") {
925 panic!(
926 "`default-linker-linux` can only be set for Linux GNU targets, not for `{triple}`"
927 );
928 }
929 if !lld_enabled {
930 panic!(
931 "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."
932 );
933 }
934 DefaultLinuxLinkerOverride::SelfContainedLldCc
935 }
936 Some(DefaultLinuxLinkerOverride::Off) => DefaultLinuxLinkerOverride::Off,
937 None => DefaultLinuxLinkerOverride::default(),
938 };
939
940 if let Some(ref s) = target_llvm_config {
941 if download_rustc_commit.is_some() && triple == *host_target.triple {
942 panic!(
943 "setting llvm_config for the host is incompatible with download-rustc"
944 );
945 }
946 target.llvm_config = Some(src.join(s));
947 }
948 if let Some(patches) = target_llvm_has_rust_patches {
949 assert!(
950 build_submodules == Some(false) || target_llvm_config.is_some(),
951 "use of `llvm-has-rust-patches` is restricted to cases where either submodules are disabled or llvm-config been provided"
952 );
953 target.llvm_has_rust_patches = Some(patches);
954 }
955 if let Some(ref s) = target_llvm_filecheck {
956 target.llvm_filecheck = Some(src.join(s));
957 }
958 target.llvm_libunwind = target_llvm_libunwind.as_ref().map(|v| {
959 v.parse().unwrap_or_else(|_| {
960 panic!("failed to parse target.{triple}.llvm-libunwind")
961 })
962 });
963 if let Some(s) = target_no_std {
964 target.no_std = s;
965 }
966 target.cc = target_cc.map(PathBuf::from);
967 target.cxx = target_cxx.map(PathBuf::from);
968 target.ar = target_ar.map(PathBuf::from);
969 target.ranlib = target_ranlib.map(PathBuf::from);
970 target.linker = target_linker.map(PathBuf::from);
971 target.crt_static = target_crt_static;
972 target.default_linker = target_default_linker;
973 target.default_linker_linux_override = default_linker_linux_override;
974 target.musl_root = target_musl_root.map(PathBuf::from);
975 target.musl_libdir = target_musl_libdir.map(PathBuf::from);
976 target.wasi_root = target_wasi_root.map(PathBuf::from);
977 target.qemu_rootfs = target_qemu_rootfs.map(PathBuf::from);
978 target.runner = target_runner;
979 target.sanitizers = target_sanitizers;
980 target.profiler = target_profiler;
981 target.rpath = target_rpath;
982 target.rustflags = target_rustflags.unwrap_or_default();
983 target.optimized_compiler_builtins = target_optimized_compiler_builtins;
984 target.jemalloc = target_jemalloc;
985 if let Some(backends) = target_codegen_backends {
986 target.codegen_backends =
987 Some(parse_codegen_backends(backends, &format!("target.{triple}")))
988 }
989
990 target.split_debuginfo = target_split_debuginfo.as_ref().map(|v| {
991 v.parse().unwrap_or_else(|_| {
992 panic!("invalid value for target.{triple}.split-debuginfo")
993 })
994 });
995
996 target_config.insert(TargetSelection::from_user(&triple), target);
997 }
998 }
999
1000 let llvm_from_ci = parse_download_ci_llvm(
1001 &dwn_ctx,
1002 &rust_info,
1003 &download_rustc_commit,
1004 llvm_download_ci_llvm,
1005 llvm_assertions,
1006 );
1007 let is_host_system_llvm =
1008 is_system_llvm(&target_config, llvm_from_ci, host_target, host_target);
1009
1010 if llvm_from_ci {
1011 let warn = |option: &str| {
1012 println!(
1013 "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build."
1014 );
1015 println!(
1016 "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false."
1017 );
1018 };
1019
1020 if llvm_static_libstdcpp.is_some() {
1021 warn("static-libstdcpp");
1022 }
1023
1024 if llvm_link_shared.is_some() {
1025 warn("link-shared");
1026 }
1027
1028 if llvm_libzstd.is_some() {
1034 println!(
1035 "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \
1036 like almost all `llvm.*` options, will be ignored and set by the LLVM CI \
1037 artifacts builder config."
1038 );
1039 println!(
1040 "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false."
1041 );
1042 }
1043 }
1044
1045 if llvm_from_ci {
1046 let triple = &host_target.triple;
1047 let ci_llvm_bin = ci_llvm_root(&dwn_ctx, llvm_from_ci, &out).join("bin");
1048 let build_target =
1049 target_config.entry(host_target).or_insert_with(|| Target::from_triple(triple));
1050 check_ci_llvm!(build_target.llvm_config);
1051 check_ci_llvm!(build_target.llvm_filecheck);
1052 build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", host_target)));
1053 build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", host_target)));
1054 }
1055
1056 for (target, linker_override) in default_linux_linker_overrides() {
1057 if targets_with_user_linker_override.contains(&target) {
1059 continue;
1060 }
1061
1062 if !hosts.contains(&TargetSelection::from_user(&target)) {
1068 continue;
1069 }
1070
1071 let default_linux_linker_override = match linker_override {
1072 DefaultLinuxLinkerOverride::Off => continue,
1073 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1074 match rust_lld_enabled {
1077 None if !is_host_system_llvm => {
1080 lld_enabled = true;
1081 Some(DefaultLinuxLinkerOverride::SelfContainedLldCc)
1082 }
1083 None => None,
1084 Some(true) => Some(DefaultLinuxLinkerOverride::SelfContainedLldCc),
1086 Some(false) => None,
1089 }
1090 }
1091 };
1092 if let Some(linker_override) = default_linux_linker_override {
1093 target_config
1094 .entry(TargetSelection::from_user(&target))
1095 .or_default()
1096 .default_linker_linux_override = linker_override;
1097 }
1098 }
1099
1100 let initial_rustfmt = build_rustfmt.or_else(|| maybe_download_rustfmt(&dwn_ctx, &out));
1101
1102 if matches!(bootstrap_override_lld, BootstrapOverrideLld::SelfContained)
1103 && !lld_enabled
1104 && flags_stage.unwrap_or(0) > 0
1105 {
1106 panic!(
1107 "Trying to use self-contained lld as a linker, but LLD is not being added to the sysroot. Enable it with rust.lld = true."
1108 );
1109 }
1110
1111 if lld_enabled && is_host_system_llvm {
1112 panic!("Cannot enable LLD with `rust.lld = true` when using external llvm-config.");
1113 }
1114
1115 let download_rustc = download_rustc_commit.is_some();
1116
1117 let stage = match flags_cmd {
1118 Subcommand::Check { .. } => flags_stage.or(build_check_stage).unwrap_or(1),
1119 Subcommand::Clippy { .. } | Subcommand::Fix => {
1120 flags_stage.or(build_check_stage).unwrap_or(1)
1121 }
1122 Subcommand::Doc { .. } => {
1124 flags_stage.or(build_doc_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1125 }
1126 Subcommand::Build { .. } => {
1127 flags_stage.or(build_build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1128 }
1129 Subcommand::Test { .. } | Subcommand::Miri { .. } => {
1130 flags_stage.or(build_test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1131 }
1132 Subcommand::Bench { .. } => flags_stage.or(build_bench_stage).unwrap_or(2),
1133 Subcommand::Dist => flags_stage.or(build_dist_stage).unwrap_or(2),
1134 Subcommand::Install => flags_stage.or(build_install_stage).unwrap_or(2),
1135 Subcommand::Perf { .. } => flags_stage.unwrap_or(1),
1136 Subcommand::Clean { .. }
1139 | Subcommand::Run { .. }
1140 | Subcommand::Setup { .. }
1141 | Subcommand::Format { .. }
1142 | Subcommand::Vendor { .. } => flags_stage.unwrap_or(0),
1143 };
1144
1145 let local_rebuild = build_local_rebuild.unwrap_or(false);
1146
1147 let check_stage0 = |kind: &str| {
1148 if local_rebuild {
1149 eprintln!("WARNING: running {kind} in stage 0. This might not work as expected.");
1150 } else {
1151 eprintln!(
1152 "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."
1153 );
1154 exit!(1);
1155 }
1156 };
1157
1158 match (stage, &flags_cmd) {
1160 (0, Subcommand::Build { .. }) => {
1161 check_stage0("build");
1162 }
1163 (0, Subcommand::Check { .. }) => {
1164 check_stage0("check");
1165 }
1166 (0, Subcommand::Doc { .. }) => {
1167 check_stage0("doc");
1168 }
1169 (0, Subcommand::Clippy { .. }) => {
1170 check_stage0("clippy");
1171 }
1172 (0, Subcommand::Dist) => {
1173 check_stage0("dist");
1174 }
1175 (0, Subcommand::Install) => {
1176 check_stage0("install");
1177 }
1178 (0, Subcommand::Test { .. }) if build_compiletest_allow_stage0 != Some(true) => {
1179 eprintln!(
1180 "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`."
1181 );
1182 exit!(1);
1183 }
1184 _ => {}
1185 }
1186
1187 if flags_compile_time_deps && !matches!(flags_cmd, Subcommand::Check { .. }) {
1188 eprintln!("ERROR: Can't use --compile-time-deps with any subcommand other than check.");
1189 exit!(1);
1190 }
1191
1192 if matches!(flags_cmd, Subcommand::Fix) {
1193 eprintln!(
1194 "WARNING: `x fix` is provided on a best-effort basis and does not support all `cargo fix` options correctly."
1195 );
1196 }
1197
1198 #[cfg(not(test))]
1200 if flags_stage.is_none() && ci_env.is_running_in_ci() {
1201 match flags_cmd {
1202 Subcommand::Test { .. }
1203 | Subcommand::Miri { .. }
1204 | Subcommand::Doc { .. }
1205 | Subcommand::Build { .. }
1206 | Subcommand::Bench { .. }
1207 | Subcommand::Dist
1208 | Subcommand::Install => {
1209 assert_eq!(
1210 stage, 2,
1211 "\
1212x.py was run under CI with an implicit `--stage {stage}`. This is probably wrong and you want stage 2.
1213NOTE: Please add `--stage 2` to your command line, or if you're sure you want to run stage {stage} then add `--stage {stage}` explicitly"
1214 );
1215 }
1216 Subcommand::Clean { .. }
1217 | Subcommand::Check { .. }
1218 | Subcommand::Clippy { .. }
1219 | Subcommand::Fix
1220 | Subcommand::Run { .. }
1221 | Subcommand::Setup { .. }
1222 | Subcommand::Format { .. }
1223 | Subcommand::Vendor { .. }
1224 | Subcommand::Perf { .. } => {}
1225 }
1226 }
1227
1228 let with_defaults = |debuginfo_level_specific: Option<_>| {
1229 debuginfo_level_specific.or(rust_debuginfo_level).unwrap_or(
1230 if rust_debug == Some(true) {
1231 DebuginfoLevel::Limited
1232 } else {
1233 DebuginfoLevel::None
1234 },
1235 )
1236 };
1237
1238 let ccache = match build_ccache {
1239 Some(StringOrBool::String(s)) => Some(s),
1240 Some(StringOrBool::Bool(true)) => Some("ccache".to_string()),
1241 _ => None,
1242 };
1243
1244 let explicit_stage_from_config = build_test_stage.is_some()
1245 || build_build_stage.is_some()
1246 || build_doc_stage.is_some()
1247 || build_dist_stage.is_some()
1248 || build_install_stage.is_some()
1249 || build_check_stage.is_some()
1250 || build_bench_stage.is_some();
1251
1252 let deny_warnings = match flags_warnings {
1253 Warnings::Deny => true,
1254 Warnings::Warn => false,
1255 Warnings::Default => rust_deny_warnings.unwrap_or(true),
1256 };
1257
1258 let gcc_ci_mode = match gcc_download_ci_gcc {
1259 Some(value) => match value {
1260 true => GccCiMode::DownloadFromCi,
1261 false => GccCiMode::BuildLocally,
1262 },
1263 None => GccCiMode::default(),
1264 };
1265
1266 let targets = flags_target
1267 .map(|TargetSelectionList(targets)| targets)
1268 .or_else(|| {
1269 build_target.map(|t| t.iter().map(|t| TargetSelection::from_user(t)).collect())
1270 })
1271 .unwrap_or_else(|| hosts.clone());
1272
1273 #[allow(clippy::map_identity)]
1274 let skip = flags_skip
1275 .into_iter()
1276 .chain(flags_exclude)
1277 .chain(build_exclude.unwrap_or_default())
1278 .map(|p| {
1279 #[cfg(windows)]
1282 {
1283 PathBuf::from(p.to_string_lossy().replace('/', "\\"))
1284 }
1285 #[cfg(not(windows))]
1286 {
1287 p
1288 }
1289 })
1290 .collect();
1291
1292 let cargo_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/cargo"));
1293 let clippy_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/clippy"));
1294 let in_tree_gcc_info = git_info(&exec_ctx, false, &src.join("src/gcc"));
1295 let in_tree_llvm_info = git_info(&exec_ctx, false, &src.join("src/llvm-project"));
1296 let enzyme_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/enzyme"));
1297 let miri_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/miri"));
1298 let rust_analyzer_info =
1299 git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rust-analyzer"));
1300 let rustfmt_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rustfmt"));
1301
1302 let optimized_compiler_builtins =
1303 build_optimized_compiler_builtins.unwrap_or(if channel == "dev" {
1304 CompilerBuiltins::BuildRustOnly
1305 } else {
1306 CompilerBuiltins::BuildLLVMFuncs
1307 });
1308 let vendor = build_vendor.unwrap_or(
1309 rust_info.is_from_tarball()
1310 && src.join("vendor").exists()
1311 && src.join(".cargo/config.toml").exists(),
1312 );
1313 let verbose_tests = rust_verbose_tests.unwrap_or(exec_ctx.is_verbose());
1314
1315 let record_failed_tests_path =
1316 out.join(build_record_failed_tests_path.unwrap_or_else(|| "failed-tests".to_string()));
1317
1318 let paths = {
1319 let mut paths = Vec::new();
1320 if flags_cmd.rerun() {
1321 paths = collect_previously_failed_tests(&record_failed_tests_path);
1322 } else {
1323 paths.extend(flags_paths);
1324 }
1325 paths
1326 };
1327
1328 Config {
1329 android_ndk: build_android_ndk,
1331 backtrace: rust_backtrace.unwrap_or(true),
1332 backtrace_on_ice: rust_backtrace_on_ice.unwrap_or(false),
1333 bindir: install_bindir.map(PathBuf::from).unwrap_or("bin".into()),
1334 bootstrap_cache_path: build_bootstrap_cache_path,
1335 bootstrap_override_lld,
1336 bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
1337 cargo_info,
1338 cargo_native_static: build_cargo_native_static.unwrap_or(false),
1339 ccache,
1340 change_id: toml.change_id.inner,
1341 channel,
1342 ci_env,
1343 clippy_info,
1344 cmd: flags_cmd,
1345 codegen_tests: rust_codegen_tests.unwrap_or(true),
1346 color: flags_color,
1347 compile_time_deps: flags_compile_time_deps,
1348 compiler_docs: build_compiler_docs.unwrap_or(false),
1349 compiletest_allow_stage0: build_compiletest_allow_stage0.unwrap_or(false),
1350 compiletest_diff_tool: build_compiletest_diff_tool,
1351 config: toml_path,
1352 configure_args: build_configure_args.unwrap_or_default(),
1353 control_flow_guard: rust_control_flow_guard.unwrap_or(false),
1354 datadir: install_datadir.map(PathBuf::from),
1355 deny_warnings,
1356 description: build_description,
1357 dist_compression_formats,
1358 dist_compression_profile: dist_compression_profile.unwrap_or("fast".into()),
1359 dist_include_mingw_linker: dist_include_mingw_linker.unwrap_or(true),
1360 dist_sign_folder: dist_sign_folder.map(PathBuf::from),
1361 dist_upload_addr,
1362 dist_vendor: dist_vendor.unwrap_or_else(|| {
1363 rust_info.is_managed_git_subrepository() || rust_info.is_from_tarball()
1365 }),
1366 docdir: install_docdir.map(PathBuf::from),
1367 docs: build_docs.unwrap_or(true),
1368 docs_minification: build_docs_minification.unwrap_or(true),
1369 download_rustc_commit,
1370 dump_bootstrap_shims: flags_dump_bootstrap_shims,
1371 ehcont_guard: rust_ehcont_guard.unwrap_or(false),
1372 enable_bolt_settings: flags_enable_bolt_settings,
1373 enzyme_info,
1374 exec_ctx,
1375 explicit_stage_from_cli: flags_stage.is_some(),
1376 explicit_stage_from_config,
1377 extended: build_extended.unwrap_or(false),
1378 free_args: flags_free_args,
1379 full_bootstrap: build_full_bootstrap.unwrap_or(false),
1380 gcc_ci_mode,
1381 gdb: build_gdb.map(PathBuf::from),
1382 host_target,
1383 hosts,
1384 in_tree_gcc_info,
1385 in_tree_llvm_info,
1386 include_default_paths: flags_include_default_paths,
1387 incremental: flags_incremental || rust_incremental == Some(true),
1388 initial_cargo,
1389 initial_cargo_clippy: build_cargo_clippy,
1390 initial_rustc,
1391 initial_rustdoc,
1392 initial_rustfmt,
1393 initial_sysroot,
1394 jemalloc: rust_jemalloc.unwrap_or(false),
1395 jobs: Some(threads_from_config(flags_jobs.or(build_jobs).unwrap_or(0))),
1396 json_output: flags_json_output,
1397 keep_stage: flags_keep_stage,
1398 keep_stage_std: flags_keep_stage_std,
1399 libdir: install_libdir.map(PathBuf::from),
1400 libgccjit_libs_dir: gcc_libgccjit_libs_dir,
1401 library_docs_private_items: build_library_docs_private_items.unwrap_or(false),
1402 lld_enabled,
1403 lldb: build_lldb.map(PathBuf::from),
1404 llvm_allow_old_toolchain: llvm_allow_old_toolchain.unwrap_or(false),
1405 llvm_assertions,
1406 llvm_bitcode_linker_enabled: rust_llvm_bitcode_linker.unwrap_or(false),
1407 llvm_build_config: llvm_build_config.clone().unwrap_or(Default::default()),
1408 llvm_cflags,
1409 llvm_clang: llvm_clang.unwrap_or(false),
1410 llvm_clang_cl,
1411 llvm_clang_dir: llvm_clang_dir.map(PathBuf::from),
1412 llvm_cxxflags,
1413 llvm_enable_warnings: llvm_enable_warnings.unwrap_or(false),
1414 llvm_enzyme: llvm_enzyme.unwrap_or(false),
1415 llvm_experimental_targets,
1416 llvm_from_ci,
1417 llvm_ldflags,
1418 llvm_libunwind_default: rust_llvm_libunwind
1419 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")),
1420 llvm_libzstd: llvm_libzstd.unwrap_or(false),
1421 llvm_link_jobs,
1422 llvm_link_shared: Cell::new(
1426 llvm_link_shared
1427 .or((!llvm_from_ci && llvm_thin_lto.unwrap_or(false)).then_some(true)),
1428 ),
1429 llvm_offload: llvm_offload.unwrap_or(false),
1430 llvm_optimize: llvm_optimize.unwrap_or(true),
1431 llvm_plugins: llvm_plugin.unwrap_or(false),
1432 llvm_polly: llvm_polly.unwrap_or(false),
1433 llvm_profile_generate: flags_llvm_profile_generate,
1434 llvm_profile_use: flags_llvm_profile_use,
1435 llvm_release_debuginfo: llvm_release_debuginfo.unwrap_or(false),
1436 llvm_static_stdcpp: llvm_static_libstdcpp.unwrap_or(false),
1437 llvm_targets,
1438 llvm_tests: llvm_tests.unwrap_or(false),
1439 llvm_thin_lto: llvm_thin_lto.unwrap_or(false),
1440 llvm_tools_enabled: rust_llvm_tools.unwrap_or(true),
1441 llvm_use_libcxx: llvm_use_libcxx.unwrap_or(false),
1442 llvm_use_linker,
1443 llvm_version_suffix,
1444 local_rebuild,
1445 locked_deps: build_locked_deps.unwrap_or(false),
1446 low_priority: build_low_priority.unwrap_or(false),
1447 mandir: install_mandir.map(PathBuf::from),
1448 miri_info,
1449 musl_root: rust_musl_root.map(PathBuf::from),
1450 ninja_in_file: llvm_ninja.unwrap_or(true),
1451 nodejs: build_nodejs.map(PathBuf::from),
1452 omit_git_hash,
1453 on_fail: flags_on_fail,
1454 optimized_compiler_builtins,
1455 out,
1456 patch_binaries_for_nix: build_patch_binaries_for_nix,
1457 path_modification_cache,
1458 paths,
1459 prefix: install_prefix.map(PathBuf::from),
1460 print_step_rusage: build_print_step_rusage.unwrap_or(false),
1461 print_step_timings: build_print_step_timings.unwrap_or(false),
1462 profiler: build_profiler.unwrap_or(false),
1463 python: build_python.map(PathBuf::from),
1464 quiet: flags_quiet,
1465 record_failed_tests_path,
1466 reproducible_artifacts: flags_reproducible_artifact,
1467 reuse: build_reuse.map(PathBuf::from),
1468 rust_analyzer_info,
1469 rust_annotate_moves_size_limit,
1470 rust_break_on_ice: rust_break_on_ice.unwrap_or(true),
1471 rust_codegen_backends: rust_codegen_backends
1472 .map(|backends| parse_codegen_backends(backends, "rust"))
1473 .unwrap_or(vec![CodegenBackendKind::Llvm]),
1474 rust_codegen_units: rust_codegen_units.map(threads_from_config),
1475 rust_codegen_units_std: rust_codegen_units_std.map(threads_from_config),
1476 rust_compress_debuginfo: rust_compress_debuginfo.unwrap_or_default(),
1477 rust_debug_logging: rust_debug_logging
1478 .or(rust_rustc_debug_assertions)
1479 .unwrap_or(rust_debug == Some(true)),
1480 rust_debuginfo_level_rustc: with_defaults(rust_debuginfo_level_rustc),
1481 rust_debuginfo_level_std: with_defaults(rust_debuginfo_level_std),
1482 rust_debuginfo_level_tests: rust_debuginfo_level_tests.unwrap_or(DebuginfoLevel::None),
1483 rust_debuginfo_level_tools: with_defaults(rust_debuginfo_level_tools),
1484 rust_dist_src: dist_src_tarball.unwrap_or_else(|| rust_dist_src.unwrap_or(true)),
1485 rust_frame_pointers: rust_frame_pointers.unwrap_or(false),
1486 rust_info,
1487 rust_lto: rust_lto
1488 .as_deref()
1489 .map(|value| RustcLto::from_str(value).unwrap())
1490 .unwrap_or_default(),
1491 rust_new_symbol_mangling,
1492 rust_optimize: rust_optimize.unwrap_or(RustOptimize::Bool(true)),
1493 rust_optimize_tests: rust_optimize_tests.unwrap_or(true),
1494 rust_overflow_checks: rust_overflow_checks.unwrap_or(rust_debug == Some(true)),
1495 rust_overflow_checks_std: rust_overflow_checks_std
1496 .or(rust_overflow_checks)
1497 .unwrap_or(rust_debug == Some(true)),
1498 rust_parallel_frontend_threads: rust_parallel_frontend_threads.map(threads_from_config),
1499 rust_profile_generate: flags_rust_profile_generate.or(rust_profile_generate),
1500 rust_profile_use: flags_rust_profile_use.or(rust_profile_use),
1501 rust_randomize_layout: rust_randomize_layout.unwrap_or(false),
1502 rust_remap_debuginfo: rust_remap_debuginfo.unwrap_or(false),
1503 rust_rpath: rust_rpath.unwrap_or(true),
1504 rust_rustflags: rust_rustflags.unwrap_or_default(),
1505 rust_stack_protector,
1506 rust_std_features: rust_std_features
1507 .unwrap_or(BTreeSet::from([String::from("panic-unwind")])),
1508 rust_strip: rust_strip.unwrap_or(false),
1509 rust_thin_lto_import_instr_limit,
1510 rust_validate_mir_opts,
1511 rust_verify_llvm_ir: rust_verify_llvm_ir.unwrap_or(false),
1512 rustc_debug_assertions: rust_rustc_debug_assertions.unwrap_or(rust_debug == Some(true)),
1513 rustc_default_linker: rust_default_linker,
1514 rustc_error_format: flags_rustc_error_format,
1515 rustfmt_info,
1516 sanitizers: build_sanitizers.unwrap_or(false),
1517 save_toolstates: rust_save_toolstates.map(PathBuf::from),
1518 skip,
1519 skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
1520 src,
1521 stage,
1522 stage0_metadata,
1523 std_debug_assertions: rust_std_debug_assertions
1524 .or(rust_rustc_debug_assertions)
1525 .unwrap_or(rust_debug == Some(true)),
1526 stderr_is_tty: std::io::stderr().is_terminal(),
1527 stdout_is_tty: std::io::stdout().is_terminal(),
1528 submodules: build_submodules,
1529 sysconfdir: install_sysconfdir.map(PathBuf::from),
1530 target_config,
1531 targets,
1532 test_compare_mode: rust_test_compare_mode.unwrap_or(false),
1533 tidy_extra_checks: build_tidy_extra_checks,
1534 tool: build_tool.unwrap_or_default(),
1535 tools: build_tools,
1536 tools_debug_assertions: rust_tools_debug_assertions
1537 .or(rust_rustc_debug_assertions)
1538 .unwrap_or(rust_debug == Some(true)),
1539 vendor,
1540 verbose_tests,
1541 windows_rc: build_windows_rc.map(PathBuf::from),
1542 yarn: build_yarn.map(PathBuf::from),
1543 }
1545 }
1546
1547 pub fn dry_run(&self) -> bool {
1548 self.exec_ctx.dry_run()
1549 }
1550
1551 pub fn is_running_on_ci(&self) -> bool {
1552 self.ci_env.is_running_in_ci()
1553 }
1554
1555 pub fn is_explicit_stage(&self) -> bool {
1556 self.explicit_stage_from_cli || self.explicit_stage_from_config
1557 }
1558
1559 pub(crate) fn test_args(&self) -> Vec<&str> {
1560 let mut test_args = match self.cmd {
1561 Subcommand::Test { ref test_args, .. }
1562 | Subcommand::Bench { ref test_args, .. }
1563 | Subcommand::Miri { ref test_args, .. } => {
1564 test_args.iter().flat_map(|s| s.split_whitespace()).collect()
1565 }
1566 _ => vec![],
1567 };
1568 test_args.extend(self.free_args.iter().map(|s| s.as_str()));
1569 test_args
1570 }
1571
1572 pub(crate) fn args(&self) -> Vec<&str> {
1573 let mut args = match self.cmd {
1574 Subcommand::Run { ref args, .. } => {
1575 args.iter().flat_map(|s| s.split_whitespace()).collect()
1576 }
1577 _ => vec![],
1578 };
1579 args.extend(self.free_args.iter().map(|s| s.as_str()));
1580 args
1581 }
1582
1583 pub(crate) fn read_file_by_commit(&self, file: &Path, commit: &str) -> String {
1585 let dwn_ctx = DownloadContext::from(self);
1586 read_file_by_commit(dwn_ctx, &self.rust_info, file, commit)
1587 }
1588
1589 pub(crate) fn artifact_version_part(&self, commit: &str) -> String {
1592 let (channel, version) = if self.rust_info.is_managed_git_subrepository() {
1593 let channel =
1594 self.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
1595 let version =
1596 self.read_file_by_commit(Path::new("src/version"), commit).trim().to_owned();
1597 (channel, version)
1598 } else {
1599 let channel = fs::read_to_string(self.src.join("src/ci/channel"));
1600 let version = fs::read_to_string(self.src.join("src/version"));
1601 match (channel, version) {
1602 (Ok(channel), Ok(version)) => {
1603 (channel.trim().to_owned(), version.trim().to_owned())
1604 }
1605 (channel, version) => {
1606 let src = self.src.display();
1607 eprintln!("ERROR: failed to determine artifact channel and/or version");
1608 eprintln!(
1609 "HELP: consider using a git checkout or ensure these files are readable"
1610 );
1611 if let Err(channel) = channel {
1612 eprintln!("reading {src}/src/ci/channel failed: {channel:?}");
1613 }
1614 if let Err(version) = version {
1615 eprintln!("reading {src}/src/version failed: {version:?}");
1616 }
1617 panic!();
1618 }
1619 }
1620 };
1621
1622 match channel.as_str() {
1623 "stable" => version,
1624 "beta" => channel,
1625 "nightly" => channel,
1626 other => unreachable!("{:?} is not recognized as a valid channel", other),
1627 }
1628 }
1629
1630 pub fn bindir_relative(&self) -> &Path {
1632 let bindir = &self.bindir;
1633 if bindir.is_absolute() {
1634 if let Some(prefix) = &self.prefix
1636 && let Ok(stripped) = bindir.strip_prefix(prefix)
1637 {
1638 return stripped;
1639 }
1640 }
1641 bindir
1642 }
1643
1644 pub fn libdir_relative(&self) -> Option<&Path> {
1646 let libdir = self.libdir.as_ref()?;
1647 if libdir.is_relative() {
1648 Some(libdir)
1649 } else {
1650 libdir.strip_prefix(self.prefix.as_ref()?).ok()
1652 }
1653 }
1654
1655 pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1657 let dwn_ctx = DownloadContext::from(self);
1658 ci_llvm_root(dwn_ctx, self.llvm_from_ci, &self.out)
1659 }
1660
1661 pub(crate) fn ci_rustc_dir(&self) -> PathBuf {
1663 assert!(self.download_rustc());
1664 self.out.join(self.host_target).join("ci-rustc")
1665 }
1666
1667 pub(crate) fn llvm_link_shared(&self) -> bool {
1672 let mut opt = self.llvm_link_shared.get();
1673 if opt.is_none() && self.dry_run() {
1674 return false;
1676 }
1677
1678 let llvm_link_shared = *opt.get_or_insert_with(|| {
1679 if self.llvm_from_ci {
1680 self.maybe_download_ci_llvm();
1681 let ci_llvm = self.ci_llvm_root();
1682 let link_type = t!(
1683 std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1684 format!("CI llvm missing: {}", ci_llvm.display())
1685 );
1686 link_type == "dynamic"
1687 } else {
1688 false
1691 }
1692 });
1693 self.llvm_link_shared.set(opt);
1694 llvm_link_shared
1695 }
1696
1697 pub(crate) fn download_rustc(&self) -> bool {
1699 self.download_rustc_commit().is_some()
1700 }
1701
1702 pub(crate) fn download_rustc_commit(&self) -> Option<&str> {
1703 static DOWNLOAD_RUSTC: OnceLock<Option<String>> = OnceLock::new();
1704 if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
1705 return self.download_rustc_commit.as_deref();
1707 }
1708
1709 DOWNLOAD_RUSTC
1710 .get_or_init(|| match &self.download_rustc_commit {
1711 None => None,
1712 Some(commit) => {
1713 self.download_ci_rustc(commit);
1714
1715 if !self.llvm_from_ci {
1719 if self.is_running_on_ci() {
1722 println!("WARNING: LLVM submodule has changes, `download-rustc` will be disabled.");
1723 return None;
1724 } else {
1725 panic!("ERROR: LLVM submodule has changes, `download-rustc` can't be used.");
1726 }
1727 }
1728
1729 if let Some(config_path) = &self.config {
1730 let ci_config_toml = match self.get_builder_toml("ci-rustc") {
1731 Ok(ci_config_toml) => ci_config_toml,
1732 Err(e) if e.to_string().contains("unknown field") => {
1733 println!("WARNING: CI rustc has some fields that are no longer supported in bootstrap; download-rustc will be disabled.");
1734 println!("HELP: Consider rebasing to a newer commit if available.");
1735 return None;
1736 }
1737 Err(e) => {
1738 eprintln!("ERROR: Failed to parse CI rustc bootstrap.toml: {e}");
1739 exit!(2);
1740 }
1741 };
1742
1743 let current_config_toml = Self::get_toml(config_path).unwrap();
1744
1745 let res = check_incompatible_options_for_ci_rustc(
1748 self.host_target,
1749 current_config_toml,
1750 ci_config_toml,
1751 );
1752
1753 let disable_ci_rustc_if_incompatible = env::var_os("DISABLE_CI_RUSTC_IF_INCOMPATIBLE")
1756 .is_some_and(|s| s == "1" || s == "true");
1757
1758 if disable_ci_rustc_if_incompatible && res.is_err() {
1759 println!("WARNING: download-rustc is disabled with `DISABLE_CI_RUSTC_IF_INCOMPATIBLE` env.");
1760 return None;
1761 }
1762
1763 res.unwrap();
1764 }
1765
1766 Some(commit.clone())
1767 }
1768 })
1769 .as_deref()
1770 }
1771
1772 pub fn do_if_verbose(&self, f: impl Fn()) {
1774 self.exec_ctx.do_if_verbose(f);
1775 }
1776
1777 pub fn any_sanitizers_to_build(&self) -> bool {
1778 self.target_config
1779 .iter()
1780 .any(|(ts, t)| !ts.is_msvc() && t.sanitizers.unwrap_or(self.sanitizers))
1781 }
1782
1783 pub fn any_profiler_enabled(&self) -> bool {
1784 self.target_config.values().any(|t| matches!(&t.profiler, Some(p) if p.is_string_or_true()))
1785 || self.profiler
1786 }
1787
1788 pub fn submodules(&self) -> bool {
1790 self.submodules.unwrap_or(self.rust_info.is_managed_git_subrepository())
1793 }
1794
1795 pub fn git_config(&self) -> GitConfig<'_> {
1796 GitConfig {
1797 nightly_branch: &self.stage0_metadata.config.nightly_branch,
1798 git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
1799 }
1800 }
1801
1802 #[cfg_attr(
1812 feature = "tracing",
1813 instrument(
1814 level = "trace",
1815 name = "Config::update_submodule",
1816 skip_all,
1817 fields(relative_path = ?relative_path),
1818 ),
1819 )]
1820 pub(crate) fn update_submodule(&self, relative_path: &str) {
1821 let dwn_ctx = DownloadContext::from(self);
1822 update_submodule(dwn_ctx, &self.rust_info, relative_path);
1823 }
1824
1825 pub fn has_changes_from_upstream(&self, paths: &[&'static str]) -> bool {
1827 let dwn_ctx = DownloadContext::from(self);
1828 has_changes_from_upstream(dwn_ctx, paths)
1829 }
1830
1831 pub fn check_path_modifications(&self, paths: &[&'static str]) -> PathFreshness {
1833 self.path_modification_cache
1839 .lock()
1840 .unwrap()
1841 .entry(paths.to_vec())
1842 .or_insert_with(|| {
1843 check_path_modifications(&self.src, &self.git_config(), paths, self.ci_env).unwrap()
1844 })
1845 .clone()
1846 }
1847
1848 pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1849 self.target_config.get(&target).and_then(|t| t.sanitizers).unwrap_or(self.sanitizers)
1850 }
1851
1852 pub fn needs_sanitizer_runtime_built(&self, target: TargetSelection) -> bool {
1853 !target.is_msvc() && self.sanitizers_enabled(target)
1855 }
1856
1857 pub fn profiler_path(&self, target: TargetSelection) -> Option<&str> {
1858 match self.target_config.get(&target)?.profiler.as_ref()? {
1859 StringOrBool::String(s) => Some(s),
1860 StringOrBool::Bool(_) => None,
1861 }
1862 }
1863
1864 pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1865 self.target_config
1866 .get(&target)
1867 .and_then(|t| t.profiler.as_ref())
1868 .map(StringOrBool::is_string_or_true)
1869 .unwrap_or(self.profiler)
1870 }
1871
1872 pub fn enabled_codegen_backends(&self, target: TargetSelection) -> &[CodegenBackendKind] {
1876 self.target_config
1877 .get(&target)
1878 .and_then(|cfg| cfg.codegen_backends.as_deref())
1879 .unwrap_or(&self.rust_codegen_backends)
1880 }
1881
1882 pub fn default_codegen_backend(&self, target: TargetSelection) -> &CodegenBackendKind {
1885 self.enabled_codegen_backends(target).first().unwrap()
1887 }
1888
1889 pub fn jemalloc(&self, target: TargetSelection) -> bool {
1890 self.target_config.get(&target).and_then(|cfg| cfg.jemalloc).unwrap_or(self.jemalloc)
1891 }
1892
1893 pub fn rpath_enabled(&self, target: TargetSelection) -> bool {
1894 self.target_config.get(&target).and_then(|t| t.rpath).unwrap_or(self.rust_rpath)
1895 }
1896
1897 pub fn optimized_compiler_builtins(&self, target: TargetSelection) -> &CompilerBuiltins {
1898 self.target_config
1899 .get(&target)
1900 .and_then(|t| t.optimized_compiler_builtins.as_ref())
1901 .unwrap_or(&self.optimized_compiler_builtins)
1902 }
1903
1904 pub fn llvm_enabled(&self, target: TargetSelection) -> bool {
1905 self.enabled_codegen_backends(target).contains(&CodegenBackendKind::Llvm)
1906 }
1907
1908 pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1909 self.target_config
1910 .get(&target)
1911 .and_then(|t| t.llvm_libunwind)
1912 .or(self.llvm_libunwind_default)
1913 .unwrap_or(
1914 if target.contains("fuchsia")
1915 || (target.contains("hexagon") && !target.contains("qurt"))
1916 {
1917 LlvmLibunwind::InTree
1920 } else {
1921 LlvmLibunwind::No
1922 },
1923 )
1924 }
1925
1926 pub fn split_debuginfo(&self, target: TargetSelection) -> SplitDebuginfo {
1927 self.target_config
1928 .get(&target)
1929 .and_then(|t| t.split_debuginfo)
1930 .unwrap_or_else(|| SplitDebuginfo::default_for_platform(target))
1931 }
1932
1933 pub fn compress_debuginfo(&self, target: TargetSelection) -> CompressDebuginfo {
1934 self.target_config
1935 .get(&target)
1936 .and_then(|t| t.compress_debuginfo)
1937 .unwrap_or(self.rust_compress_debuginfo)
1938 }
1939
1940 pub fn is_host_target(&self, target: TargetSelection) -> bool {
1942 self.host_target == target
1943 }
1944
1945 pub fn is_system_llvm(&self, target: TargetSelection) -> bool {
1950 is_system_llvm(&self.target_config, self.llvm_from_ci, self.host_target, target)
1951 }
1952
1953 pub fn is_rust_llvm(&self, target: TargetSelection) -> bool {
1957 match self.target_config.get(&target) {
1958 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
1962 _ => !self.is_system_llvm(target),
1965 }
1966 }
1967
1968 pub fn exec_ctx(&self) -> &ExecutionContext {
1969 &self.exec_ctx
1970 }
1971
1972 pub fn git_info(&self, omit_git_hash: bool, dir: &Path) -> GitInfo {
1973 GitInfo::new(omit_git_hash, dir, self)
1974 }
1975}
1976
1977impl AsRef<ExecutionContext> for Config {
1978 fn as_ref(&self) -> &ExecutionContext {
1979 &self.exec_ctx
1980 }
1981}
1982
1983fn compute_src_directory(src_dir: Option<PathBuf>, exec_ctx: &ExecutionContext) -> Option<PathBuf> {
1984 if let Some(src) = src_dir {
1985 return Some(src);
1986 } else {
1987 let mut cmd = helpers::git(None);
1990 cmd.arg("rev-parse").arg("--show-cdup");
1998 let output = cmd.allow_failure().run_capture_stdout(exec_ctx);
2000 if output.is_success() {
2001 let git_root_relative = output.stdout();
2002 let git_root = env::current_dir()
2005 .unwrap()
2006 .join(PathBuf::from(git_root_relative.trim()))
2007 .canonicalize()
2008 .unwrap();
2009 let s = git_root.to_str().unwrap();
2010
2011 let git_root = match s.strip_prefix("\\\\?\\") {
2013 Some(p) => PathBuf::from(p),
2014 None => git_root,
2015 };
2016 if git_root.join("src").join("stage0").exists() {
2023 return Some(git_root);
2024 }
2025 } else {
2026 }
2029 };
2030 None
2031}
2032
2033fn load_toml_config(
2038 src: &Path,
2039 config_path: Option<PathBuf>,
2040 get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2041) -> (TomlConfig, Option<PathBuf>) {
2042 let toml_path = config_path.or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
2050 let using_default_path = toml_path.is_none();
2051 let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml"));
2052
2053 if using_default_path && !toml_path.exists() {
2054 toml_path = src.join(PathBuf::from("bootstrap.toml"));
2055 if !toml_path.exists() {
2056 toml_path = PathBuf::from("config.toml");
2057 if !toml_path.exists() {
2058 toml_path = src.join(PathBuf::from("config.toml"));
2059 }
2060 }
2061 }
2062
2063 if !using_default_path || toml_path.exists() {
2066 let path = Some(if cfg!(not(test)) {
2067 toml_path = toml_path.canonicalize().unwrap();
2068 toml_path.clone()
2069 } else {
2070 toml_path.clone()
2071 });
2072 (get_toml(&toml_path).unwrap_or_else(|e| bad_config(&toml_path, e)), path)
2073 } else {
2074 (TomlConfig::default(), None)
2075 }
2076}
2077
2078fn postprocess_toml(
2079 toml: &mut TomlConfig,
2080 src_dir: &Path,
2081 toml_path: Option<PathBuf>,
2082 exec_ctx: &ExecutionContext,
2083 override_set: &[String],
2084 get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2085) {
2086 let git_info = GitInfo::new(false, src_dir, exec_ctx);
2087
2088 if git_info.is_from_tarball() && toml.profile.is_none() {
2089 toml.profile = Some("dist".into());
2090 }
2091
2092 for include_path in toml.include.clone().unwrap_or_default().iter().rev() {
2098 let include_path = toml_path
2099 .as_ref()
2100 .expect("include found in default TOML config")
2101 .parent()
2102 .unwrap()
2103 .join(include_path);
2104
2105 let included_toml =
2106 get_toml(&include_path).unwrap_or_else(|e| bad_config(&include_path, e));
2107 toml.merge(
2108 Some(include_path),
2109 &mut Default::default(),
2110 included_toml,
2111 ReplaceOpt::IgnoreDuplicate,
2112 );
2113 }
2114
2115 if let Some(include) = &toml.profile {
2116 let profile_aliases = HashMap::from([("user", "dist")]);
2120 let include = match profile_aliases.get(include.as_str()) {
2121 Some(alias) => alias,
2122 None => include.as_str(),
2123 };
2124 let mut include_path = PathBuf::from(src_dir);
2125 include_path.push("src");
2126 include_path.push("bootstrap");
2127 include_path.push("defaults");
2128 include_path.push(format!("bootstrap.{include}.toml"));
2129 let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
2130 eprintln!(
2131 "ERROR: Failed to parse default config profile at '{}': {e}",
2132 include_path.display()
2133 );
2134 exit!(2);
2135 });
2136 toml.merge(
2137 Some(include_path),
2138 &mut Default::default(),
2139 included_toml,
2140 ReplaceOpt::IgnoreDuplicate,
2141 );
2142 }
2143
2144 let mut override_toml = TomlConfig::default();
2145 for option in override_set.iter() {
2146 fn get_table(option: &str) -> Result<TomlConfig, toml::de::Error> {
2147 toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table))
2148 }
2149
2150 let mut err = match get_table(option) {
2151 Ok(v) => {
2152 override_toml.merge(None, &mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate);
2153 continue;
2154 }
2155 Err(e) => e,
2156 };
2157 if let Some((key, value)) = option.split_once('=')
2160 && !value.contains('"')
2161 {
2162 match get_table(&format!(r#"{key}="{value}""#)) {
2163 Ok(v) => {
2164 override_toml.merge(
2165 None,
2166 &mut Default::default(),
2167 v,
2168 ReplaceOpt::ErrorOnDuplicate,
2169 );
2170 continue;
2171 }
2172 Err(e) => err = e,
2173 }
2174 }
2175 eprintln!("failed to parse override `{option}`: `{err}");
2176 exit!(2)
2177 }
2178 toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override);
2179}
2180
2181#[cfg(test)]
2182pub fn check_stage0_version(
2183 _program_path: &Path,
2184 _component_name: &'static str,
2185 _src_dir: &Path,
2186 _exec_ctx: &ExecutionContext,
2187) {
2188}
2189
2190#[cfg(not(test))]
2192pub fn check_stage0_version(
2193 program_path: &Path,
2194 component_name: &'static str,
2195 src_dir: &Path,
2196 exec_ctx: &ExecutionContext,
2197) {
2198 use build_helper::util::fail;
2199
2200 if exec_ctx.dry_run() {
2201 return;
2202 }
2203
2204 let stage0_output =
2205 command(program_path).arg("--version").run_capture_stdout(exec_ctx).stdout();
2206 let mut stage0_output = stage0_output.lines().next().unwrap().split(' ');
2207
2208 let stage0_name = stage0_output.next().unwrap();
2209 if stage0_name != component_name {
2210 fail(&format!(
2211 "Expected to find {component_name} at {} but it claims to be {stage0_name}",
2212 program_path.display()
2213 ));
2214 }
2215
2216 let stage0_version =
2217 semver::Version::parse(stage0_output.next().unwrap().split('-').next().unwrap().trim())
2218 .unwrap();
2219 let source_version =
2220 semver::Version::parse(fs::read_to_string(src_dir.join("src/version")).unwrap().trim())
2221 .unwrap();
2222 if !(source_version == stage0_version
2223 || (source_version.major == stage0_version.major
2224 && (source_version.minor == stage0_version.minor
2225 || source_version.minor == stage0_version.minor + 1)))
2226 {
2227 let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1);
2228 fail(&format!(
2229 "Unexpected {component_name} version: {stage0_version}, we should use {prev_version}/{source_version} to build source with {source_version}"
2230 ));
2231 }
2232}
2233
2234fn print_rustc_modifications(
2235 dwn_ctx: &DownloadContext<'_>,
2236 if_unchanged: bool,
2237 mut modifications: Vec<PathBuf>,
2238) -> Option<()> {
2239 if !dwn_ctx.exec_ctx.is_verbose() {
2240 modifications.retain(|path| !path.starts_with("compiler"));
2241 }
2242 if modifications.is_empty() {
2243 eprintln!(
2245 "skipping rustc download with `download-rustc = 'if-unchanged'` due to local changes"
2246 );
2247 return None;
2248 }
2249
2250 eprintln!(
2251 "NOTE: detected {} modifications that could affect a build of rustc",
2252 modifications.len()
2253 );
2254 for file in modifications.iter().take(10) {
2255 eprintln!("- {}", file.display());
2256 }
2257 if modifications.len() > 10 {
2258 eprintln!("- ... and {} more", modifications.len() - 10);
2259 }
2260
2261 if if_unchanged {
2262 eprintln!("skipping rustc download due to `download-rustc = 'if-unchanged'`");
2263 None
2264 } else {
2265 eprintln!("downloading unconditionally due to `download-rustc = true`");
2266 Some(())
2267 }
2268}
2269
2270pub fn download_ci_rustc_commit<'a>(
2271 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2272 rust_info: &channel::GitInfo,
2273 download_rustc: Option<StringOrBool>,
2274 llvm_assertions: bool,
2275) -> Option<String> {
2276 let dwn_ctx = dwn_ctx.as_ref();
2277
2278 if !is_download_ci_available(&dwn_ctx.host_target.triple, llvm_assertions) {
2279 return None;
2280 }
2281
2282 let if_unchanged = match download_rustc {
2284 None | Some(StringOrBool::Bool(false)) => return None,
2290 Some(StringOrBool::Bool(true)) => false,
2291 Some(StringOrBool::String(s)) if s == "if-unchanged" => {
2292 if !rust_info.is_managed_git_subrepository() {
2293 println!(
2294 "ERROR: `download-rustc=if-unchanged` is only compatible with Git managed sources."
2295 );
2296 crate::exit!(1);
2297 }
2298
2299 true
2300 }
2301 Some(StringOrBool::String(other)) => {
2302 panic!("unrecognized option for download-rustc: {other}")
2303 }
2304 };
2305
2306 let commit = if rust_info.is_managed_git_subrepository() {
2307 let freshness = check_path_modifications_(dwn_ctx, RUSTC_IF_UNCHANGED_ALLOWED_PATHS);
2310 dwn_ctx.exec_ctx.do_if_verbose(|| {
2311 eprintln!("rustc freshness: {freshness:?}");
2312 });
2313 match freshness {
2314 PathFreshness::LastModifiedUpstream { upstream } => upstream,
2315 PathFreshness::HasLocalModifications { upstream, modifications } => {
2316 if dwn_ctx.is_running_on_ci() {
2317 eprintln!("CI rustc commit matches with HEAD and we are in CI.");
2318 eprintln!(
2319 "`rustc.download-ci` functionality will be skipped as artifacts are not available."
2320 );
2321 return None;
2322 }
2323
2324 print_rustc_modifications(dwn_ctx, if_unchanged, modifications)?;
2325 upstream
2326 }
2327 PathFreshness::MissingUpstream => {
2328 eprintln!("No upstream commit found");
2329 return None;
2330 }
2331 }
2332 } else {
2333 channel::read_commit_info_file(dwn_ctx.src)
2334 .map(|info| info.sha.trim().to_owned())
2335 .expect("git-commit-info is missing in the project root")
2336 };
2337
2338 Some(commit)
2339}
2340
2341pub fn check_path_modifications_<'a>(
2342 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2343 paths: &[&'static str],
2344) -> PathFreshness {
2345 let dwn_ctx = dwn_ctx.as_ref();
2346 dwn_ctx
2352 .path_modification_cache
2353 .lock()
2354 .unwrap()
2355 .entry(paths.to_vec())
2356 .or_insert_with(|| {
2357 check_path_modifications(
2358 dwn_ctx.src,
2359 &git_config(dwn_ctx.stage0_metadata),
2360 paths,
2361 dwn_ctx.ci_env,
2362 )
2363 .unwrap()
2364 })
2365 .clone()
2366}
2367
2368pub fn git_config(stage0_metadata: &build_helper::stage0_parser::Stage0) -> GitConfig<'_> {
2369 GitConfig {
2370 nightly_branch: &stage0_metadata.config.nightly_branch,
2371 git_merge_commit_email: &stage0_metadata.config.git_merge_commit_email,
2372 }
2373}
2374
2375pub fn parse_download_ci_llvm<'a>(
2376 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2377 rust_info: &channel::GitInfo,
2378 download_rustc_commit: &Option<String>,
2379 download_ci_llvm: Option<StringOrBool>,
2380 asserts: bool,
2381) -> bool {
2382 let dwn_ctx = dwn_ctx.as_ref();
2383 let download_ci_llvm = download_ci_llvm.unwrap_or(StringOrBool::Bool(true));
2384
2385 let if_unchanged = || {
2386 if rust_info.is_from_tarball() {
2387 println!("ERROR: 'if-unchanged' is only compatible with Git managed sources.");
2389 crate::exit!(1);
2390 }
2391
2392 #[cfg(not(test))]
2394 update_submodule(dwn_ctx, rust_info, "src/llvm-project");
2395
2396 let has_changes = has_changes_from_upstream(dwn_ctx, LLVM_INVALIDATION_PATHS);
2398
2399 if has_changes {
2401 false
2402 } else {
2403 llvm::is_ci_llvm_available_for_target(&dwn_ctx.host_target, asserts)
2404 }
2405 };
2406
2407 match download_ci_llvm {
2408 StringOrBool::Bool(b) => {
2409 if !b && download_rustc_commit.is_some() {
2410 panic!(
2411 "`llvm.download-ci-llvm` cannot be set to `false` if `rust.download-rustc` is set to `true` or `if-unchanged`."
2412 );
2413 }
2414
2415 #[cfg(not(test))]
2416 if b && dwn_ctx.is_running_on_ci() && CiEnv::is_rust_lang_managed_ci_job() {
2417 panic!(
2419 "`llvm.download-ci-llvm` cannot be set to `true` on CI. Use `if-unchanged` instead."
2420 );
2421 }
2422
2423 b && llvm::is_ci_llvm_available_for_target(&dwn_ctx.host_target, asserts)
2425 }
2426 StringOrBool::String(s) if s == "if-unchanged" => if_unchanged(),
2427 StringOrBool::String(other) => {
2428 panic!("unrecognized option for download-ci-llvm: {other:?}")
2429 }
2430 }
2431}
2432
2433pub fn has_changes_from_upstream<'a>(
2434 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2435 paths: &[&'static str],
2436) -> bool {
2437 let dwn_ctx = dwn_ctx.as_ref();
2438 match check_path_modifications_(dwn_ctx, paths) {
2439 PathFreshness::LastModifiedUpstream { .. } => false,
2440 PathFreshness::HasLocalModifications { .. } | PathFreshness::MissingUpstream => true,
2441 }
2442}
2443
2444#[cfg_attr(
2445 feature = "tracing",
2446 instrument(
2447 level = "trace",
2448 name = "Config::update_submodule",
2449 skip_all,
2450 fields(relative_path = ?relative_path),
2451 ),
2452)]
2453pub(crate) fn update_submodule<'a>(
2454 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2455 rust_info: &channel::GitInfo,
2456 relative_path: &str,
2457) {
2458 let dwn_ctx = dwn_ctx.as_ref();
2459 if rust_info.is_from_tarball() || !submodules_(dwn_ctx.submodules, rust_info) {
2460 return;
2461 }
2462
2463 let absolute_path = dwn_ctx.src.join(relative_path);
2464
2465 if !absolute_path.exists() {
2469 t!(fs::create_dir_all(&absolute_path));
2470 }
2471
2472 if !git_info(dwn_ctx.exec_ctx, false, &absolute_path).is_managed_git_subrepository()
2475 && !helpers::dir_is_empty(&absolute_path)
2476 {
2477 return;
2478 }
2479
2480 let submodule_git = || helpers::git(Some(&absolute_path));
2481
2482 let checked_out_hash =
2484 submodule_git().args(["rev-parse", "HEAD"]).run_capture_stdout(dwn_ctx.exec_ctx).stdout();
2485 let checked_out_hash = checked_out_hash.trim_end();
2486 let recorded = helpers::git(Some(dwn_ctx.src))
2488 .run_in_dry_run() .args(["ls-tree", "HEAD"])
2490 .arg(relative_path)
2491 .run_capture_stdout(dwn_ctx.exec_ctx)
2492 .stdout();
2493
2494 let actual_hash = recorded
2495 .split_whitespace()
2496 .nth(2)
2497 .unwrap_or_else(|| panic!("unexpected output `{recorded}` when updating {relative_path}"));
2498
2499 if actual_hash == checked_out_hash {
2500 return;
2502 }
2503
2504 if !dwn_ctx.exec_ctx.dry_run() {
2505 println!("Updating submodule {relative_path}");
2506 };
2507
2508 helpers::git(Some(dwn_ctx.src))
2509 .allow_failure()
2510 .args(["submodule", "-q", "sync"])
2511 .arg(relative_path)
2512 .run(dwn_ctx.exec_ctx);
2513
2514 let update = |progress: bool| {
2516 let current_branch = helpers::git(Some(dwn_ctx.src))
2519 .allow_failure()
2520 .args(["symbolic-ref", "--short", "HEAD"])
2521 .run_capture(dwn_ctx.exec_ctx);
2522
2523 let mut git = helpers::git(Some(dwn_ctx.src)).allow_failure();
2524 if current_branch.is_success() {
2525 let branch = current_branch.stdout();
2528 let branch = branch.trim();
2529 let branch = branch.strip_prefix("heads/").unwrap_or(branch);
2530 git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
2531 }
2532 git.args(["submodule", "update", "--init", "--recursive", "--depth=1"]);
2533 if progress {
2534 git.arg("--progress");
2535 }
2536 git.arg(relative_path);
2537 git
2538 };
2539 if !update(true).allow_failure().run(dwn_ctx.exec_ctx) {
2540 update(false).allow_failure().run(dwn_ctx.exec_ctx);
2541 }
2542
2543 let has_local_modifications = !submodule_git()
2546 .allow_failure()
2547 .args(["diff-index", "--quiet", "HEAD"])
2548 .run(dwn_ctx.exec_ctx);
2549 if has_local_modifications {
2550 submodule_git().allow_failure().args(["stash", "push"]).run(dwn_ctx.exec_ctx);
2551 }
2552
2553 submodule_git().allow_failure().args(["reset", "-q", "--hard"]).run(dwn_ctx.exec_ctx);
2554 submodule_git().allow_failure().args(["clean", "-qdfx"]).run(dwn_ctx.exec_ctx);
2555
2556 if has_local_modifications {
2557 submodule_git().allow_failure().args(["stash", "pop"]).run(dwn_ctx.exec_ctx);
2558 }
2559}
2560
2561pub fn git_info(exec_ctx: &ExecutionContext, omit_git_hash: bool, dir: &Path) -> GitInfo {
2562 GitInfo::new(omit_git_hash, dir, exec_ctx)
2563}
2564
2565pub fn submodules_(submodules: &Option<bool>, rust_info: &channel::GitInfo) -> bool {
2566 submodules.unwrap_or(rust_info.is_managed_git_subrepository())
2569}
2570
2571pub fn is_system_llvm(
2576 target_config: &HashMap<TargetSelection, Target>,
2577 llvm_from_ci: bool,
2578 host_target: TargetSelection,
2579 target: TargetSelection,
2580) -> bool {
2581 match target_config.get(&target) {
2582 Some(Target { llvm_config: Some(_), .. }) => {
2583 let ci_llvm = llvm_from_ci && is_host_target(&host_target, &target);
2584 !ci_llvm
2585 }
2586 Some(Target { llvm_config: None, .. }) => false,
2588 None => false,
2589 }
2590}
2591
2592pub fn is_host_target(host_target: &TargetSelection, target: &TargetSelection) -> bool {
2593 host_target == target
2594}
2595
2596pub(crate) fn ci_llvm_root<'a>(
2597 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2598 llvm_from_ci: bool,
2599 out: &Path,
2600) -> PathBuf {
2601 let dwn_ctx = dwn_ctx.as_ref();
2602 assert!(llvm_from_ci);
2603 out.join(dwn_ctx.host_target).join("ci-llvm")
2604}
2605
2606pub(crate) fn read_file_by_commit<'a>(
2608 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2609 rust_info: &channel::GitInfo,
2610 file: &Path,
2611 commit: &str,
2612) -> String {
2613 let dwn_ctx = dwn_ctx.as_ref();
2614 assert!(
2615 rust_info.is_managed_git_subrepository(),
2616 "`Config::read_file_by_commit` is not supported in non-git sources."
2617 );
2618
2619 let mut git = helpers::git(Some(dwn_ctx.src));
2620 git.arg("show").arg(format!("{commit}:{}", file.to_str().unwrap()));
2621 git.run_capture_stdout(dwn_ctx.exec_ctx).stdout()
2622}
2623
2624fn bad_config(toml_path: &Path, e: toml::de::Error) -> ! {
2625 eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display());
2626 let e_s = e.to_string();
2627 if e_s.contains("unknown field")
2628 && let Some(field_name) = e_s.split("`").nth(1)
2629 && let sections = find_correct_section_for_field(field_name)
2630 && !sections.is_empty()
2631 {
2632 if sections.len() == 1 {
2633 match sections[0] {
2634 WouldBeValidFor::TopLevel { is_section } => {
2635 if is_section {
2636 eprintln!(
2637 "hint: section name `{field_name}` used as a key within a section"
2638 );
2639 } else {
2640 eprintln!("hint: try using `{field_name}` as a top level key");
2641 }
2642 }
2643 WouldBeValidFor::Section(section) => {
2644 eprintln!("hint: try moving `{field_name}` to the `{section}` section")
2645 }
2646 }
2647 } else {
2648 eprintln!(
2649 "hint: `{field_name}` would be valid {}",
2650 join_oxford_comma(sections.iter(), "or"),
2651 );
2652 }
2653 }
2654
2655 exit!(2);
2656}
2657
2658#[derive(Copy, Clone, Debug)]
2659enum WouldBeValidFor {
2660 TopLevel { is_section: bool },
2661 Section(&'static str),
2662}
2663
2664fn join_oxford_comma(
2665 mut parts: impl ExactSizeIterator<Item = impl std::fmt::Display>,
2666 conj: &str,
2667) -> String {
2668 use std::fmt::Write;
2669 let mut out = String::new();
2670
2671 assert!(parts.len() > 1);
2672 while let Some(part) = parts.next() {
2673 if parts.len() == 0 {
2674 write!(&mut out, "{conj} {part}")
2675 } else {
2676 write!(&mut out, "{part}, ")
2677 }
2678 .unwrap();
2679 }
2680 out
2681}
2682
2683impl std::fmt::Display for WouldBeValidFor {
2684 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2685 match self {
2686 Self::TopLevel { .. } => write!(f, "at top level"),
2687 Self::Section(section_name) => write!(f, "in section `{section_name}`"),
2688 }
2689 }
2690}
2691
2692fn find_correct_section_for_field(field_name: &str) -> Vec<WouldBeValidFor> {
2693 let sections = ["build", "install", "llvm", "gcc", "rust", "dist"];
2694 sections
2695 .iter()
2696 .map(Some)
2697 .chain([None])
2698 .filter_map(|section_name| {
2699 let dummy_config_str = if let Some(section_name) = section_name {
2700 format!("{section_name}.{field_name} = 0\n")
2701 } else {
2702 format!("{field_name} = 0\n")
2703 };
2704 let is_unknown_field = toml::from_str::<toml::Value>(&dummy_config_str)
2705 .and_then(TomlConfig::deserialize)
2706 .err()
2707 .is_some_and(|e| e.to_string().contains("unknown field"));
2708 if is_unknown_field {
2709 None
2710 } else {
2711 Some(section_name.copied().map(WouldBeValidFor::Section).unwrap_or_else(|| {
2712 WouldBeValidFor::TopLevel { is_section: sections.contains(&field_name) }
2713 }))
2714 }
2715 })
2716 .collect()
2717}