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