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