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