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