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