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_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 ci_env: CiEnv,
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 ci_env = match flags_ci {
732 Some(true) => CiEnv::GitHubActions,
733 Some(false) => CiEnv::None,
734 None => CiEnv::current(),
735 };
736 let dwn_ctx = DownloadContext {
737 path_modification_cache: path_modification_cache.clone(),
738 src: &src,
739 submodules: &build_submodules,
740 host_target,
741 patch_binaries_for_nix: build_patch_binaries_for_nix,
742 exec_ctx: &exec_ctx,
743 stage0_metadata: &stage0_metadata,
744 llvm_assertions,
745 bootstrap_cache_path: &build_bootstrap_cache_path,
746 ci_env,
747 };
748
749 let initial_rustc = build_rustc.unwrap_or_else(|| {
750 download_beta_toolchain(&dwn_ctx, &out);
751 default_stage0_rustc_path(&out)
752 });
753
754 let initial_sysroot = t!(PathBuf::from_str(
755 command(&initial_rustc)
756 .args(["--print", "sysroot"])
757 .run_in_dry_run()
758 .run_capture_stdout(&exec_ctx)
759 .stdout()
760 .trim()
761 ));
762
763 let initial_cargo = build_cargo.unwrap_or_else(|| {
764 download_beta_toolchain(&dwn_ctx, &out);
765 initial_sysroot.join("bin").join(exe("cargo", host_target))
766 });
767
768 if exec_ctx.dry_run() {
770 out = out.join("tmp-dry-run");
771 fs::create_dir_all(&out).expect("Failed to create dry-run directory");
772 }
773
774 let file_content = t!(fs::read_to_string(src.join("src/ci/channel")));
775 let ci_channel = file_content.trim_end();
776
777 let is_user_configured_rust_channel = match rust_channel {
778 Some(channel_) if channel_ == "auto-detect" => {
779 channel = ci_channel.into();
780 true
781 }
782 Some(channel_) => {
783 channel = channel_;
784 true
785 }
786 None => false,
787 };
788
789 let omit_git_hash = rust_omit_git_hash.unwrap_or(channel == "dev");
790
791 let rust_info = git_info(&exec_ctx, omit_git_hash, &src);
792
793 if !is_user_configured_rust_channel && rust_info.is_from_tarball() {
794 channel = ci_channel.into();
795 }
796
797 let debug_assertions_requested = matches!(rust_rustc_debug_assertions, Some(true))
808 || (matches!(rust_debug, Some(true))
809 && !matches!(rust_rustc_debug_assertions, Some(false)));
810
811 if debug_assertions_requested
812 && let Some(ref opt) = rust_download_rustc
813 && opt.is_string_or_true()
814 {
815 eprintln!(
816 "WARN: currently no CI rustc builds have rustc debug assertions \
817 enabled. Please either set `rust.debug-assertions` to `false` if you \
818 want to use download CI rustc or set `rust.download-rustc` to `false`."
819 );
820 }
821
822 let mut download_rustc_commit =
823 download_ci_rustc_commit(&dwn_ctx, &rust_info, rust_download_rustc, llvm_assertions);
824
825 if debug_assertions_requested && download_rustc_commit.is_some() {
826 eprintln!(
827 "WARN: `rust.debug-assertions = true` will prevent downloading CI rustc as alt CI \
828 rustc is not currently built with debug assertions."
829 );
830 download_rustc_commit = None;
832 }
833
834 if let Some(commit) = &download_rustc_commit
838 && is_user_configured_rust_channel
839 {
840 println!(
841 "WARNING: `rust.download-rustc` is enabled. The `rust.channel` option will be overridden by the CI rustc's channel."
842 );
843
844 channel =
845 read_file_by_commit(&dwn_ctx, &rust_info, Path::new("src/ci/channel"), commit)
846 .trim()
847 .to_owned();
848 }
849
850 if build_npm.is_some() {
851 println!(
852 "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."
853 );
854 }
855
856 let mut lld_enabled = rust_lld_enabled.unwrap_or(false);
857
858 let mut targets_with_user_linker_override = HashSet::new();
860
861 if let Some(t) = toml.target {
862 for (triple, cfg) in t {
863 let TomlTarget {
864 cc: target_cc,
865 cxx: target_cxx,
866 ar: target_ar,
867 ranlib: target_ranlib,
868 default_linker: target_default_linker,
869 default_linker_linux_override: target_default_linker_linux_override,
870 linker: target_linker,
871 split_debuginfo: target_split_debuginfo,
872 llvm_config: target_llvm_config,
873 llvm_has_rust_patches: target_llvm_has_rust_patches,
874 llvm_filecheck: target_llvm_filecheck,
875 llvm_libunwind: target_llvm_libunwind,
876 sanitizers: target_sanitizers,
877 profiler: target_profiler,
878 rpath: target_rpath,
879 rustflags: target_rustflags,
880 crt_static: target_crt_static,
881 musl_root: target_musl_root,
882 musl_libdir: target_musl_libdir,
883 wasi_root: target_wasi_root,
884 qemu_rootfs: target_qemu_rootfs,
885 no_std: target_no_std,
886 codegen_backends: target_codegen_backends,
887 runner: target_runner,
888 optimized_compiler_builtins: target_optimized_compiler_builtins,
889 jemalloc: target_jemalloc,
890 } = cfg;
891
892 let mut target = Target::from_triple(&triple);
893
894 if target_default_linker_linux_override.is_some() {
895 targets_with_user_linker_override.insert(triple.clone());
896 }
897
898 let default_linker_linux_override = match target_default_linker_linux_override {
899 Some(DefaultLinuxLinkerOverride::SelfContainedLldCc) => {
900 if rust_default_linker.is_some() {
901 panic!(
902 "cannot set both `default-linker` and `default-linker-linux` for target `{triple}`"
903 );
904 }
905 if !triple.contains("linux-gnu") {
906 panic!(
907 "`default-linker-linux` can only be set for Linux GNU targets, not for `{triple}`"
908 );
909 }
910 if !lld_enabled {
911 panic!(
912 "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."
913 );
914 }
915 DefaultLinuxLinkerOverride::SelfContainedLldCc
916 }
917 Some(DefaultLinuxLinkerOverride::Off) => DefaultLinuxLinkerOverride::Off,
918 None => DefaultLinuxLinkerOverride::default(),
919 };
920
921 if let Some(ref s) = target_llvm_config {
922 if download_rustc_commit.is_some() && triple == *host_target.triple {
923 panic!(
924 "setting llvm_config for the host is incompatible with download-rustc"
925 );
926 }
927 target.llvm_config = Some(src.join(s));
928 }
929 if let Some(patches) = target_llvm_has_rust_patches {
930 assert!(
931 build_submodules == Some(false) || target_llvm_config.is_some(),
932 "use of `llvm-has-rust-patches` is restricted to cases where either submodules are disabled or llvm-config been provided"
933 );
934 target.llvm_has_rust_patches = Some(patches);
935 }
936 if let Some(ref s) = target_llvm_filecheck {
937 target.llvm_filecheck = Some(src.join(s));
938 }
939 target.llvm_libunwind = target_llvm_libunwind.as_ref().map(|v| {
940 v.parse().unwrap_or_else(|_| {
941 panic!("failed to parse target.{triple}.llvm-libunwind")
942 })
943 });
944 if let Some(s) = target_no_std {
945 target.no_std = s;
946 }
947 target.cc = target_cc.map(PathBuf::from);
948 target.cxx = target_cxx.map(PathBuf::from);
949 target.ar = target_ar.map(PathBuf::from);
950 target.ranlib = target_ranlib.map(PathBuf::from);
951 target.linker = target_linker.map(PathBuf::from);
952 target.crt_static = target_crt_static;
953 target.default_linker = target_default_linker;
954 target.default_linker_linux_override = default_linker_linux_override;
955 target.musl_root = target_musl_root.map(PathBuf::from);
956 target.musl_libdir = target_musl_libdir.map(PathBuf::from);
957 target.wasi_root = target_wasi_root.map(PathBuf::from);
958 target.qemu_rootfs = target_qemu_rootfs.map(PathBuf::from);
959 target.runner = target_runner;
960 target.sanitizers = target_sanitizers;
961 target.profiler = target_profiler;
962 target.rpath = target_rpath;
963 target.rustflags = target_rustflags.unwrap_or_default();
964 target.optimized_compiler_builtins = target_optimized_compiler_builtins;
965 target.jemalloc = target_jemalloc;
966 if let Some(backends) = target_codegen_backends {
967 target.codegen_backends =
968 Some(parse_codegen_backends(backends, &format!("target.{triple}")))
969 }
970
971 target.split_debuginfo = target_split_debuginfo.as_ref().map(|v| {
972 v.parse().unwrap_or_else(|_| {
973 panic!("invalid value for target.{triple}.split-debuginfo")
974 })
975 });
976
977 target_config.insert(TargetSelection::from_user(&triple), target);
978 }
979 }
980
981 let llvm_from_ci = parse_download_ci_llvm(
982 &dwn_ctx,
983 &rust_info,
984 &download_rustc_commit,
985 llvm_download_ci_llvm,
986 llvm_assertions,
987 );
988 let is_host_system_llvm =
989 is_system_llvm(&target_config, llvm_from_ci, host_target, host_target);
990
991 if llvm_from_ci {
992 let warn = |option: &str| {
993 println!(
994 "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build."
995 );
996 println!(
997 "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false."
998 );
999 };
1000
1001 if llvm_static_libstdcpp.is_some() {
1002 warn("static-libstdcpp");
1003 }
1004
1005 if llvm_link_shared.is_some() {
1006 warn("link-shared");
1007 }
1008
1009 if llvm_libzstd.is_some() {
1015 println!(
1016 "WARNING: when using `download-ci-llvm`, the local `llvm.libzstd` option, \
1017 like almost all `llvm.*` options, will be ignored and set by the LLVM CI \
1018 artifacts builder config."
1019 );
1020 println!(
1021 "HELP: To use `llvm.libzstd` for LLVM/LLD builds, set `download-ci-llvm` option to false."
1022 );
1023 }
1024 }
1025
1026 if llvm_from_ci {
1027 let triple = &host_target.triple;
1028 let ci_llvm_bin = ci_llvm_root(&dwn_ctx, llvm_from_ci, &out).join("bin");
1029 let build_target =
1030 target_config.entry(host_target).or_insert_with(|| Target::from_triple(triple));
1031 check_ci_llvm!(build_target.llvm_config);
1032 check_ci_llvm!(build_target.llvm_filecheck);
1033 build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", host_target)));
1034 build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", host_target)));
1035 }
1036
1037 for (target, linker_override) in default_linux_linker_overrides() {
1038 if targets_with_user_linker_override.contains(&target) {
1040 continue;
1041 }
1042
1043 if !hosts.contains(&TargetSelection::from_user(&target)) {
1049 continue;
1050 }
1051
1052 let default_linux_linker_override = match linker_override {
1053 DefaultLinuxLinkerOverride::Off => continue,
1054 DefaultLinuxLinkerOverride::SelfContainedLldCc => {
1055 match rust_lld_enabled {
1058 None if !is_host_system_llvm => {
1061 lld_enabled = true;
1062 Some(DefaultLinuxLinkerOverride::SelfContainedLldCc)
1063 }
1064 None => None,
1065 Some(true) => Some(DefaultLinuxLinkerOverride::SelfContainedLldCc),
1067 Some(false) => None,
1070 }
1071 }
1072 };
1073 if let Some(linker_override) = default_linux_linker_override {
1074 target_config
1075 .entry(TargetSelection::from_user(&target))
1076 .or_default()
1077 .default_linker_linux_override = linker_override;
1078 }
1079 }
1080
1081 let initial_rustfmt = build_rustfmt.or_else(|| maybe_download_rustfmt(&dwn_ctx, &out));
1082
1083 if matches!(bootstrap_override_lld, BootstrapOverrideLld::SelfContained)
1084 && !lld_enabled
1085 && flags_stage.unwrap_or(0) > 0
1086 {
1087 panic!(
1088 "Trying to use self-contained lld as a linker, but LLD is not being added to the sysroot. Enable it with rust.lld = true."
1089 );
1090 }
1091
1092 if lld_enabled && is_host_system_llvm {
1093 panic!("Cannot enable LLD with `rust.lld = true` when using external llvm-config.");
1094 }
1095
1096 let download_rustc = download_rustc_commit.is_some();
1097
1098 let stage = match flags_cmd {
1099 Subcommand::Check { .. } => flags_stage.or(build_check_stage).unwrap_or(1),
1100 Subcommand::Clippy { .. } | Subcommand::Fix => {
1101 flags_stage.or(build_check_stage).unwrap_or(1)
1102 }
1103 Subcommand::Doc { .. } => {
1105 flags_stage.or(build_doc_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1106 }
1107 Subcommand::Build { .. } => {
1108 flags_stage.or(build_build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1109 }
1110 Subcommand::Test { .. } | Subcommand::Miri { .. } => {
1111 flags_stage.or(build_test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1112 }
1113 Subcommand::Bench { .. } => flags_stage.or(build_bench_stage).unwrap_or(2),
1114 Subcommand::Dist => flags_stage.or(build_dist_stage).unwrap_or(2),
1115 Subcommand::Install => flags_stage.or(build_install_stage).unwrap_or(2),
1116 Subcommand::Perf { .. } => flags_stage.unwrap_or(1),
1117 Subcommand::Clean { .. }
1120 | Subcommand::Run { .. }
1121 | Subcommand::Setup { .. }
1122 | Subcommand::Format { .. }
1123 | Subcommand::Vendor { .. } => flags_stage.unwrap_or(0),
1124 };
1125
1126 let local_rebuild = build_local_rebuild.unwrap_or(false);
1127
1128 let check_stage0 = |kind: &str| {
1129 if local_rebuild {
1130 eprintln!("WARNING: running {kind} in stage 0. This might not work as expected.");
1131 } else {
1132 eprintln!(
1133 "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."
1134 );
1135 exit!(1);
1136 }
1137 };
1138
1139 match (stage, &flags_cmd) {
1141 (0, Subcommand::Build { .. }) => {
1142 check_stage0("build");
1143 }
1144 (0, Subcommand::Check { .. }) => {
1145 check_stage0("check");
1146 }
1147 (0, Subcommand::Doc { .. }) => {
1148 check_stage0("doc");
1149 }
1150 (0, Subcommand::Clippy { .. }) => {
1151 check_stage0("clippy");
1152 }
1153 (0, Subcommand::Dist) => {
1154 check_stage0("dist");
1155 }
1156 (0, Subcommand::Install) => {
1157 check_stage0("install");
1158 }
1159 (0, Subcommand::Test { .. }) if build_compiletest_allow_stage0 != Some(true) => {
1160 eprintln!(
1161 "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`."
1162 );
1163 exit!(1);
1164 }
1165 _ => {}
1166 }
1167
1168 if flags_compile_time_deps && !matches!(flags_cmd, Subcommand::Check { .. }) {
1169 eprintln!("ERROR: Can't use --compile-time-deps with any subcommand other than check.");
1170 exit!(1);
1171 }
1172
1173 #[cfg(not(test))]
1175 if flags_stage.is_none() && ci_env.is_running_in_ci() {
1176 match flags_cmd {
1177 Subcommand::Test { .. }
1178 | Subcommand::Miri { .. }
1179 | Subcommand::Doc { .. }
1180 | Subcommand::Build { .. }
1181 | Subcommand::Bench { .. }
1182 | Subcommand::Dist
1183 | Subcommand::Install => {
1184 assert_eq!(
1185 stage, 2,
1186 "x.py should be run with `--stage 2` on CI, but was run with `--stage {stage}`",
1187 );
1188 }
1189 Subcommand::Clean { .. }
1190 | Subcommand::Check { .. }
1191 | Subcommand::Clippy { .. }
1192 | Subcommand::Fix
1193 | Subcommand::Run { .. }
1194 | Subcommand::Setup { .. }
1195 | Subcommand::Format { .. }
1196 | Subcommand::Vendor { .. }
1197 | Subcommand::Perf { .. } => {}
1198 }
1199 }
1200
1201 let with_defaults = |debuginfo_level_specific: Option<_>| {
1202 debuginfo_level_specific.or(rust_debuginfo_level).unwrap_or(
1203 if rust_debug == Some(true) {
1204 DebuginfoLevel::Limited
1205 } else {
1206 DebuginfoLevel::None
1207 },
1208 )
1209 };
1210
1211 let ccache = match build_ccache {
1212 Some(StringOrBool::String(s)) => Some(s),
1213 Some(StringOrBool::Bool(true)) => Some("ccache".to_string()),
1214 _ => None,
1215 };
1216
1217 let explicit_stage_from_config = build_test_stage.is_some()
1218 || build_build_stage.is_some()
1219 || build_doc_stage.is_some()
1220 || build_dist_stage.is_some()
1221 || build_install_stage.is_some()
1222 || build_check_stage.is_some()
1223 || build_bench_stage.is_some();
1224
1225 let deny_warnings = match flags_warnings {
1226 Warnings::Deny => true,
1227 Warnings::Warn => false,
1228 Warnings::Default => rust_deny_warnings.unwrap_or(true),
1229 };
1230
1231 let gcc_ci_mode = match gcc_download_ci_gcc {
1232 Some(value) => match value {
1233 true => GccCiMode::DownloadFromCi,
1234 false => GccCiMode::BuildLocally,
1235 },
1236 None => GccCiMode::default(),
1237 };
1238
1239 let targets = flags_target
1240 .map(|TargetSelectionList(targets)| targets)
1241 .or_else(|| {
1242 build_target.map(|t| t.iter().map(|t| TargetSelection::from_user(t)).collect())
1243 })
1244 .unwrap_or_else(|| hosts.clone());
1245
1246 #[allow(clippy::map_identity)]
1247 let skip = flags_skip
1248 .into_iter()
1249 .chain(flags_exclude)
1250 .chain(build_exclude.unwrap_or_default())
1251 .map(|p| {
1252 #[cfg(windows)]
1255 {
1256 PathBuf::from(p.to_string_lossy().replace('/', "\\"))
1257 }
1258 #[cfg(not(windows))]
1259 {
1260 p
1261 }
1262 })
1263 .collect();
1264
1265 let cargo_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/cargo"));
1266 let clippy_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/clippy"));
1267 let in_tree_gcc_info = git_info(&exec_ctx, false, &src.join("src/gcc"));
1268 let in_tree_llvm_info = git_info(&exec_ctx, false, &src.join("src/llvm-project"));
1269 let enzyme_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/enzyme"));
1270 let miri_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/miri"));
1271 let rust_analyzer_info =
1272 git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rust-analyzer"));
1273 let rustfmt_info = git_info(&exec_ctx, omit_git_hash, &src.join("src/tools/rustfmt"));
1274
1275 let optimized_compiler_builtins =
1276 build_optimized_compiler_builtins.unwrap_or(if channel == "dev" {
1277 CompilerBuiltins::BuildRustOnly
1278 } else {
1279 CompilerBuiltins::BuildLLVMFuncs
1280 });
1281 let vendor = build_vendor.unwrap_or(
1282 rust_info.is_from_tarball()
1283 && src.join("vendor").exists()
1284 && src.join(".cargo/config.toml").exists(),
1285 );
1286 let verbose_tests = rust_verbose_tests.unwrap_or(exec_ctx.is_verbose());
1287
1288 Config {
1289 android_ndk: build_android_ndk,
1291 backtrace: rust_backtrace.unwrap_or(true),
1292 backtrace_on_ice: rust_backtrace_on_ice.unwrap_or(false),
1293 bindir: install_bindir.map(PathBuf::from).unwrap_or("bin".into()),
1294 bootstrap_cache_path: build_bootstrap_cache_path,
1295 bootstrap_override_lld,
1296 bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
1297 cargo_info,
1298 cargo_native_static: build_cargo_native_static.unwrap_or(false),
1299 ccache,
1300 change_id: toml.change_id.inner,
1301 channel,
1302 ci_env,
1303 clippy_info,
1304 cmd: flags_cmd,
1305 codegen_tests: rust_codegen_tests.unwrap_or(true),
1306 color: flags_color,
1307 compile_time_deps: flags_compile_time_deps,
1308 compiler_docs: build_compiler_docs.unwrap_or(false),
1309 compiletest_allow_stage0: build_compiletest_allow_stage0.unwrap_or(false),
1310 compiletest_diff_tool: build_compiletest_diff_tool,
1311 config: toml_path,
1312 configure_args: build_configure_args.unwrap_or_default(),
1313 control_flow_guard: rust_control_flow_guard.unwrap_or(false),
1314 datadir: install_datadir.map(PathBuf::from),
1315 deny_warnings,
1316 description: build_description,
1317 dist_compression_formats,
1318 dist_compression_profile: dist_compression_profile.unwrap_or("fast".into()),
1319 dist_include_mingw_linker: dist_include_mingw_linker.unwrap_or(true),
1320 dist_sign_folder: dist_sign_folder.map(PathBuf::from),
1321 dist_upload_addr,
1322 dist_vendor: dist_vendor.unwrap_or_else(|| {
1323 rust_info.is_managed_git_subrepository() || rust_info.is_from_tarball()
1325 }),
1326 docdir: install_docdir.map(PathBuf::from),
1327 docs: build_docs.unwrap_or(true),
1328 docs_minification: build_docs_minification.unwrap_or(true),
1329 download_rustc_commit,
1330 dump_bootstrap_shims: flags_dump_bootstrap_shims,
1331 ehcont_guard: rust_ehcont_guard.unwrap_or(false),
1332 enable_bolt_settings: flags_enable_bolt_settings,
1333 enzyme_info,
1334 exec_ctx,
1335 explicit_stage_from_cli: flags_stage.is_some(),
1336 explicit_stage_from_config,
1337 extended: build_extended.unwrap_or(false),
1338 free_args: flags_free_args,
1339 full_bootstrap: build_full_bootstrap.unwrap_or(false),
1340 gcc_ci_mode,
1341 gdb: build_gdb.map(PathBuf::from),
1342 host_target,
1343 hosts,
1344 in_tree_gcc_info,
1345 in_tree_llvm_info,
1346 include_default_paths: flags_include_default_paths,
1347 incremental: flags_incremental || rust_incremental == Some(true),
1348 initial_cargo,
1349 initial_cargo_clippy: build_cargo_clippy,
1350 initial_rustc,
1351 initial_rustfmt,
1352 initial_sysroot,
1353 jemalloc: rust_jemalloc.unwrap_or(false),
1354 jobs: Some(threads_from_config(flags_jobs.or(build_jobs).unwrap_or(0))),
1355 json_output: flags_json_output,
1356 keep_stage: flags_keep_stage,
1357 keep_stage_std: flags_keep_stage_std,
1358 libdir: install_libdir.map(PathBuf::from),
1359 libgccjit_libs_dir: gcc_libgccjit_libs_dir,
1360 library_docs_private_items: build_library_docs_private_items.unwrap_or(false),
1361 lld_enabled,
1362 lldb: build_lldb.map(PathBuf::from),
1363 llvm_allow_old_toolchain: llvm_allow_old_toolchain.unwrap_or(false),
1364 llvm_assertions,
1365 llvm_bitcode_linker_enabled: rust_llvm_bitcode_linker.unwrap_or(false),
1366 llvm_build_config: llvm_build_config.clone().unwrap_or(Default::default()),
1367 llvm_cflags,
1368 llvm_clang: llvm_clang.unwrap_or(false),
1369 llvm_clang_cl,
1370 llvm_clang_dir: llvm_clang_dir.map(PathBuf::from),
1371 llvm_cxxflags,
1372 llvm_enable_warnings: llvm_enable_warnings.unwrap_or(false),
1373 llvm_enzyme: llvm_enzyme.unwrap_or(false),
1374 llvm_experimental_targets,
1375 llvm_from_ci,
1376 llvm_ldflags,
1377 llvm_libunwind_default: rust_llvm_libunwind
1378 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind")),
1379 llvm_libzstd: llvm_libzstd.unwrap_or(false),
1380 llvm_link_jobs,
1381 llvm_link_shared: Cell::new(
1385 llvm_link_shared
1386 .or((!llvm_from_ci && llvm_thin_lto.unwrap_or(false)).then_some(true)),
1387 ),
1388 llvm_offload: llvm_offload.unwrap_or(false),
1389 llvm_optimize: llvm_optimize.unwrap_or(true),
1390 llvm_plugins: llvm_plugin.unwrap_or(false),
1391 llvm_polly: llvm_polly.unwrap_or(false),
1392 llvm_profile_generate: flags_llvm_profile_generate,
1393 llvm_profile_use: flags_llvm_profile_use,
1394 llvm_release_debuginfo: llvm_release_debuginfo.unwrap_or(false),
1395 llvm_static_stdcpp: llvm_static_libstdcpp.unwrap_or(false),
1396 llvm_targets,
1397 llvm_tests: llvm_tests.unwrap_or(false),
1398 llvm_thin_lto: llvm_thin_lto.unwrap_or(false),
1399 llvm_tools_enabled: rust_llvm_tools.unwrap_or(true),
1400 llvm_use_libcxx: llvm_use_libcxx.unwrap_or(false),
1401 llvm_use_linker,
1402 llvm_version_suffix,
1403 local_rebuild,
1404 locked_deps: build_locked_deps.unwrap_or(false),
1405 low_priority: build_low_priority.unwrap_or(false),
1406 mandir: install_mandir.map(PathBuf::from),
1407 miri_info,
1408 musl_root: rust_musl_root.map(PathBuf::from),
1409 ninja_in_file: llvm_ninja.unwrap_or(true),
1410 nodejs: build_nodejs.map(PathBuf::from),
1411 omit_git_hash,
1412 on_fail: flags_on_fail,
1413 optimized_compiler_builtins,
1414 out,
1415 patch_binaries_for_nix: build_patch_binaries_for_nix,
1416 path_modification_cache,
1417 paths: flags_paths,
1418 prefix: install_prefix.map(PathBuf::from),
1419 print_step_rusage: build_print_step_rusage.unwrap_or(false),
1420 print_step_timings: build_print_step_timings.unwrap_or(false),
1421 profiler: build_profiler.unwrap_or(false),
1422 python: build_python.map(PathBuf::from),
1423 reproducible_artifacts: flags_reproducible_artifact,
1424 reuse: build_reuse.map(PathBuf::from),
1425 rust_analyzer_info,
1426 rust_annotate_moves_size_limit,
1427 rust_break_on_ice: rust_break_on_ice.unwrap_or(true),
1428 rust_codegen_backends: rust_codegen_backends
1429 .map(|backends| parse_codegen_backends(backends, "rust"))
1430 .unwrap_or(vec![CodegenBackendKind::Llvm]),
1431 rust_codegen_units: rust_codegen_units.map(threads_from_config),
1432 rust_codegen_units_std: rust_codegen_units_std.map(threads_from_config),
1433 rust_debug_logging: rust_debug_logging
1434 .or(rust_rustc_debug_assertions)
1435 .unwrap_or(rust_debug == Some(true)),
1436 rust_debuginfo_level_rustc: with_defaults(rust_debuginfo_level_rustc),
1437 rust_debuginfo_level_std: with_defaults(rust_debuginfo_level_std),
1438 rust_debuginfo_level_tests: rust_debuginfo_level_tests.unwrap_or(DebuginfoLevel::None),
1439 rust_debuginfo_level_tools: with_defaults(rust_debuginfo_level_tools),
1440 rust_dist_src: dist_src_tarball.unwrap_or_else(|| rust_dist_src.unwrap_or(true)),
1441 rust_frame_pointers: rust_frame_pointers.unwrap_or(false),
1442 rust_info,
1443 rust_lto: rust_lto
1444 .as_deref()
1445 .map(|value| RustcLto::from_str(value).unwrap())
1446 .unwrap_or_default(),
1447 rust_new_symbol_mangling,
1448 rust_optimize: rust_optimize.unwrap_or(RustOptimize::Bool(true)),
1449 rust_optimize_tests: rust_optimize_tests.unwrap_or(true),
1450 rust_overflow_checks: rust_overflow_checks.unwrap_or(rust_debug == Some(true)),
1451 rust_overflow_checks_std: rust_overflow_checks_std
1452 .or(rust_overflow_checks)
1453 .unwrap_or(rust_debug == Some(true)),
1454 rust_parallel_frontend_threads: rust_parallel_frontend_threads.map(threads_from_config),
1455 rust_profile_generate: flags_rust_profile_generate.or(rust_profile_generate),
1456 rust_profile_use: flags_rust_profile_use.or(rust_profile_use),
1457 rust_randomize_layout: rust_randomize_layout.unwrap_or(false),
1458 rust_remap_debuginfo: rust_remap_debuginfo.unwrap_or(false),
1459 rust_rpath: rust_rpath.unwrap_or(true),
1460 rust_rustflags: rust_rustflags.unwrap_or_default(),
1461 rust_stack_protector,
1462 rust_std_features: rust_std_features
1463 .unwrap_or(BTreeSet::from([String::from("panic-unwind")])),
1464 rust_strip: rust_strip.unwrap_or(false),
1465 rust_thin_lto_import_instr_limit,
1466 rust_validate_mir_opts,
1467 rust_verify_llvm_ir: rust_verify_llvm_ir.unwrap_or(false),
1468 rustc_debug_assertions: rust_rustc_debug_assertions.unwrap_or(rust_debug == Some(true)),
1469 rustc_default_linker: rust_default_linker,
1470 rustc_error_format: flags_rustc_error_format,
1471 rustfmt_info,
1472 sanitizers: build_sanitizers.unwrap_or(false),
1473 save_toolstates: rust_save_toolstates.map(PathBuf::from),
1474 skip,
1475 skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
1476 src,
1477 stage,
1478 stage0_metadata,
1479 std_debug_assertions: rust_std_debug_assertions
1480 .or(rust_rustc_debug_assertions)
1481 .unwrap_or(rust_debug == Some(true)),
1482 stderr_is_tty: std::io::stderr().is_terminal(),
1483 stdout_is_tty: std::io::stdout().is_terminal(),
1484 submodules: build_submodules,
1485 sysconfdir: install_sysconfdir.map(PathBuf::from),
1486 target_config,
1487 targets,
1488 test_compare_mode: rust_test_compare_mode.unwrap_or(false),
1489 tidy_extra_checks: build_tidy_extra_checks,
1490 tool: build_tool.unwrap_or_default(),
1491 tools: build_tools,
1492 tools_debug_assertions: rust_tools_debug_assertions
1493 .or(rust_rustc_debug_assertions)
1494 .unwrap_or(rust_debug == Some(true)),
1495 vendor,
1496 verbose_tests,
1497 windows_rc: build_windows_rc.map(PathBuf::from),
1498 yarn: build_yarn.map(PathBuf::from),
1499 }
1501 }
1502
1503 pub fn dry_run(&self) -> bool {
1504 self.exec_ctx.dry_run()
1505 }
1506
1507 pub fn is_running_on_ci(&self) -> bool {
1508 self.ci_env.is_running_in_ci()
1509 }
1510
1511 pub fn is_explicit_stage(&self) -> bool {
1512 self.explicit_stage_from_cli || self.explicit_stage_from_config
1513 }
1514
1515 pub(crate) fn test_args(&self) -> Vec<&str> {
1516 let mut test_args = match self.cmd {
1517 Subcommand::Test { ref test_args, .. }
1518 | Subcommand::Bench { ref test_args, .. }
1519 | Subcommand::Miri { ref test_args, .. } => {
1520 test_args.iter().flat_map(|s| s.split_whitespace()).collect()
1521 }
1522 _ => vec![],
1523 };
1524 test_args.extend(self.free_args.iter().map(|s| s.as_str()));
1525 test_args
1526 }
1527
1528 pub(crate) fn args(&self) -> Vec<&str> {
1529 let mut args = match self.cmd {
1530 Subcommand::Run { ref args, .. } => {
1531 args.iter().flat_map(|s| s.split_whitespace()).collect()
1532 }
1533 _ => vec![],
1534 };
1535 args.extend(self.free_args.iter().map(|s| s.as_str()));
1536 args
1537 }
1538
1539 pub(crate) fn read_file_by_commit(&self, file: &Path, commit: &str) -> String {
1541 let dwn_ctx = DownloadContext::from(self);
1542 read_file_by_commit(dwn_ctx, &self.rust_info, file, commit)
1543 }
1544
1545 pub(crate) fn artifact_version_part(&self, commit: &str) -> String {
1548 let (channel, version) = if self.rust_info.is_managed_git_subrepository() {
1549 let channel =
1550 self.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
1551 let version =
1552 self.read_file_by_commit(Path::new("src/version"), commit).trim().to_owned();
1553 (channel, version)
1554 } else {
1555 let channel = fs::read_to_string(self.src.join("src/ci/channel"));
1556 let version = fs::read_to_string(self.src.join("src/version"));
1557 match (channel, version) {
1558 (Ok(channel), Ok(version)) => {
1559 (channel.trim().to_owned(), version.trim().to_owned())
1560 }
1561 (channel, version) => {
1562 let src = self.src.display();
1563 eprintln!("ERROR: failed to determine artifact channel and/or version");
1564 eprintln!(
1565 "HELP: consider using a git checkout or ensure these files are readable"
1566 );
1567 if let Err(channel) = channel {
1568 eprintln!("reading {src}/src/ci/channel failed: {channel:?}");
1569 }
1570 if let Err(version) = version {
1571 eprintln!("reading {src}/src/version failed: {version:?}");
1572 }
1573 panic!();
1574 }
1575 }
1576 };
1577
1578 match channel.as_str() {
1579 "stable" => version,
1580 "beta" => channel,
1581 "nightly" => channel,
1582 other => unreachable!("{:?} is not recognized as a valid channel", other),
1583 }
1584 }
1585
1586 pub fn bindir_relative(&self) -> &Path {
1588 let bindir = &self.bindir;
1589 if bindir.is_absolute() {
1590 if let Some(prefix) = &self.prefix
1592 && let Ok(stripped) = bindir.strip_prefix(prefix)
1593 {
1594 return stripped;
1595 }
1596 }
1597 bindir
1598 }
1599
1600 pub fn libdir_relative(&self) -> Option<&Path> {
1602 let libdir = self.libdir.as_ref()?;
1603 if libdir.is_relative() {
1604 Some(libdir)
1605 } else {
1606 libdir.strip_prefix(self.prefix.as_ref()?).ok()
1608 }
1609 }
1610
1611 pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1613 let dwn_ctx = DownloadContext::from(self);
1614 ci_llvm_root(dwn_ctx, self.llvm_from_ci, &self.out)
1615 }
1616
1617 pub(crate) fn ci_rustc_dir(&self) -> PathBuf {
1619 assert!(self.download_rustc());
1620 self.out.join(self.host_target).join("ci-rustc")
1621 }
1622
1623 pub(crate) fn llvm_link_shared(&self) -> bool {
1628 let mut opt = self.llvm_link_shared.get();
1629 if opt.is_none() && self.dry_run() {
1630 return false;
1632 }
1633
1634 let llvm_link_shared = *opt.get_or_insert_with(|| {
1635 if self.llvm_from_ci {
1636 self.maybe_download_ci_llvm();
1637 let ci_llvm = self.ci_llvm_root();
1638 let link_type = t!(
1639 std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1640 format!("CI llvm missing: {}", ci_llvm.display())
1641 );
1642 link_type == "dynamic"
1643 } else {
1644 false
1647 }
1648 });
1649 self.llvm_link_shared.set(opt);
1650 llvm_link_shared
1651 }
1652
1653 pub(crate) fn download_rustc(&self) -> bool {
1655 self.download_rustc_commit().is_some()
1656 }
1657
1658 pub(crate) fn download_rustc_commit(&self) -> Option<&str> {
1659 static DOWNLOAD_RUSTC: OnceLock<Option<String>> = OnceLock::new();
1660 if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
1661 return self.download_rustc_commit.as_deref();
1663 }
1664
1665 DOWNLOAD_RUSTC
1666 .get_or_init(|| match &self.download_rustc_commit {
1667 None => None,
1668 Some(commit) => {
1669 self.download_ci_rustc(commit);
1670
1671 if !self.llvm_from_ci {
1675 if self.is_running_on_ci() {
1678 println!("WARNING: LLVM submodule has changes, `download-rustc` will be disabled.");
1679 return None;
1680 } else {
1681 panic!("ERROR: LLVM submodule has changes, `download-rustc` can't be used.");
1682 }
1683 }
1684
1685 if let Some(config_path) = &self.config {
1686 let ci_config_toml = match self.get_builder_toml("ci-rustc") {
1687 Ok(ci_config_toml) => ci_config_toml,
1688 Err(e) if e.to_string().contains("unknown field") => {
1689 println!("WARNING: CI rustc has some fields that are no longer supported in bootstrap; download-rustc will be disabled.");
1690 println!("HELP: Consider rebasing to a newer commit if available.");
1691 return None;
1692 }
1693 Err(e) => {
1694 eprintln!("ERROR: Failed to parse CI rustc bootstrap.toml: {e}");
1695 exit!(2);
1696 }
1697 };
1698
1699 let current_config_toml = Self::get_toml(config_path).unwrap();
1700
1701 let res = check_incompatible_options_for_ci_rustc(
1704 self.host_target,
1705 current_config_toml,
1706 ci_config_toml,
1707 );
1708
1709 let disable_ci_rustc_if_incompatible = env::var_os("DISABLE_CI_RUSTC_IF_INCOMPATIBLE")
1712 .is_some_and(|s| s == "1" || s == "true");
1713
1714 if disable_ci_rustc_if_incompatible && res.is_err() {
1715 println!("WARNING: download-rustc is disabled with `DISABLE_CI_RUSTC_IF_INCOMPATIBLE` env.");
1716 return None;
1717 }
1718
1719 res.unwrap();
1720 }
1721
1722 Some(commit.clone())
1723 }
1724 })
1725 .as_deref()
1726 }
1727
1728 pub fn do_if_verbose(&self, f: impl Fn()) {
1730 self.exec_ctx.do_if_verbose(f);
1731 }
1732
1733 pub fn any_sanitizers_to_build(&self) -> bool {
1734 self.target_config
1735 .iter()
1736 .any(|(ts, t)| !ts.is_msvc() && t.sanitizers.unwrap_or(self.sanitizers))
1737 }
1738
1739 pub fn any_profiler_enabled(&self) -> bool {
1740 self.target_config.values().any(|t| matches!(&t.profiler, Some(p) if p.is_string_or_true()))
1741 || self.profiler
1742 }
1743
1744 pub fn submodules(&self) -> bool {
1746 self.submodules.unwrap_or(self.rust_info.is_managed_git_subrepository())
1749 }
1750
1751 pub fn git_config(&self) -> GitConfig<'_> {
1752 GitConfig {
1753 nightly_branch: &self.stage0_metadata.config.nightly_branch,
1754 git_merge_commit_email: &self.stage0_metadata.config.git_merge_commit_email,
1755 }
1756 }
1757
1758 #[cfg_attr(
1768 feature = "tracing",
1769 instrument(
1770 level = "trace",
1771 name = "Config::update_submodule",
1772 skip_all,
1773 fields(relative_path = ?relative_path),
1774 ),
1775 )]
1776 pub(crate) fn update_submodule(&self, relative_path: &str) {
1777 let dwn_ctx = DownloadContext::from(self);
1778 update_submodule(dwn_ctx, &self.rust_info, relative_path);
1779 }
1780
1781 pub fn has_changes_from_upstream(&self, paths: &[&'static str]) -> bool {
1783 let dwn_ctx = DownloadContext::from(self);
1784 has_changes_from_upstream(dwn_ctx, paths)
1785 }
1786
1787 pub fn check_path_modifications(&self, paths: &[&'static str]) -> PathFreshness {
1789 self.path_modification_cache
1795 .lock()
1796 .unwrap()
1797 .entry(paths.to_vec())
1798 .or_insert_with(|| {
1799 check_path_modifications(&self.src, &self.git_config(), paths, self.ci_env).unwrap()
1800 })
1801 .clone()
1802 }
1803
1804 pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1805 self.target_config.get(&target).and_then(|t| t.sanitizers).unwrap_or(self.sanitizers)
1806 }
1807
1808 pub fn needs_sanitizer_runtime_built(&self, target: TargetSelection) -> bool {
1809 !target.is_msvc() && self.sanitizers_enabled(target)
1811 }
1812
1813 pub fn profiler_path(&self, target: TargetSelection) -> Option<&str> {
1814 match self.target_config.get(&target)?.profiler.as_ref()? {
1815 StringOrBool::String(s) => Some(s),
1816 StringOrBool::Bool(_) => None,
1817 }
1818 }
1819
1820 pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1821 self.target_config
1822 .get(&target)
1823 .and_then(|t| t.profiler.as_ref())
1824 .map(StringOrBool::is_string_or_true)
1825 .unwrap_or(self.profiler)
1826 }
1827
1828 pub fn enabled_codegen_backends(&self, target: TargetSelection) -> &[CodegenBackendKind] {
1832 self.target_config
1833 .get(&target)
1834 .and_then(|cfg| cfg.codegen_backends.as_deref())
1835 .unwrap_or(&self.rust_codegen_backends)
1836 }
1837
1838 pub fn default_codegen_backend(&self, target: TargetSelection) -> &CodegenBackendKind {
1841 self.enabled_codegen_backends(target).first().unwrap()
1843 }
1844
1845 pub fn jemalloc(&self, target: TargetSelection) -> bool {
1846 self.target_config.get(&target).and_then(|cfg| cfg.jemalloc).unwrap_or(self.jemalloc)
1847 }
1848
1849 pub fn rpath_enabled(&self, target: TargetSelection) -> bool {
1850 self.target_config.get(&target).and_then(|t| t.rpath).unwrap_or(self.rust_rpath)
1851 }
1852
1853 pub fn optimized_compiler_builtins(&self, target: TargetSelection) -> &CompilerBuiltins {
1854 self.target_config
1855 .get(&target)
1856 .and_then(|t| t.optimized_compiler_builtins.as_ref())
1857 .unwrap_or(&self.optimized_compiler_builtins)
1858 }
1859
1860 pub fn llvm_enabled(&self, target: TargetSelection) -> bool {
1861 self.enabled_codegen_backends(target).contains(&CodegenBackendKind::Llvm)
1862 }
1863
1864 pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1865 self.target_config
1866 .get(&target)
1867 .and_then(|t| t.llvm_libunwind)
1868 .or(self.llvm_libunwind_default)
1869 .unwrap_or(
1870 if target.contains("fuchsia")
1871 || (target.contains("hexagon") && !target.contains("qurt"))
1872 {
1873 LlvmLibunwind::InTree
1876 } else {
1877 LlvmLibunwind::No
1878 },
1879 )
1880 }
1881
1882 pub fn split_debuginfo(&self, target: TargetSelection) -> SplitDebuginfo {
1883 self.target_config
1884 .get(&target)
1885 .and_then(|t| t.split_debuginfo)
1886 .unwrap_or_else(|| SplitDebuginfo::default_for_platform(target))
1887 }
1888
1889 pub fn is_host_target(&self, target: TargetSelection) -> bool {
1891 self.host_target == target
1892 }
1893
1894 pub fn is_system_llvm(&self, target: TargetSelection) -> bool {
1899 is_system_llvm(&self.target_config, self.llvm_from_ci, self.host_target, target)
1900 }
1901
1902 pub fn is_rust_llvm(&self, target: TargetSelection) -> bool {
1906 match self.target_config.get(&target) {
1907 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
1911 _ => !self.is_system_llvm(target),
1914 }
1915 }
1916
1917 pub fn exec_ctx(&self) -> &ExecutionContext {
1918 &self.exec_ctx
1919 }
1920
1921 pub fn git_info(&self, omit_git_hash: bool, dir: &Path) -> GitInfo {
1922 GitInfo::new(omit_git_hash, dir, self)
1923 }
1924}
1925
1926impl AsRef<ExecutionContext> for Config {
1927 fn as_ref(&self) -> &ExecutionContext {
1928 &self.exec_ctx
1929 }
1930}
1931
1932fn compute_src_directory(src_dir: Option<PathBuf>, exec_ctx: &ExecutionContext) -> Option<PathBuf> {
1933 if let Some(src) = src_dir {
1934 return Some(src);
1935 } else {
1936 let mut cmd = helpers::git(None);
1939 cmd.arg("rev-parse").arg("--show-cdup");
1947 let output = cmd.allow_failure().run_capture_stdout(exec_ctx);
1949 if output.is_success() {
1950 let git_root_relative = output.stdout();
1951 let git_root = env::current_dir()
1954 .unwrap()
1955 .join(PathBuf::from(git_root_relative.trim()))
1956 .canonicalize()
1957 .unwrap();
1958 let s = git_root.to_str().unwrap();
1959
1960 let git_root = match s.strip_prefix("\\\\?\\") {
1962 Some(p) => PathBuf::from(p),
1963 None => git_root,
1964 };
1965 if git_root.join("src").join("stage0").exists() {
1972 return Some(git_root);
1973 }
1974 } else {
1975 }
1978 };
1979 None
1980}
1981
1982fn load_toml_config(
1987 src: &Path,
1988 config_path: Option<PathBuf>,
1989 get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
1990) -> (TomlConfig, Option<PathBuf>) {
1991 let toml_path = config_path.or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
1999 let using_default_path = toml_path.is_none();
2000 let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml"));
2001
2002 if using_default_path && !toml_path.exists() {
2003 toml_path = src.join(PathBuf::from("bootstrap.toml"));
2004 if !toml_path.exists() {
2005 toml_path = PathBuf::from("config.toml");
2006 if !toml_path.exists() {
2007 toml_path = src.join(PathBuf::from("config.toml"));
2008 }
2009 }
2010 }
2011
2012 if !using_default_path || toml_path.exists() {
2015 let path = Some(if cfg!(not(test)) {
2016 toml_path = toml_path.canonicalize().unwrap();
2017 toml_path.clone()
2018 } else {
2019 toml_path.clone()
2020 });
2021 (get_toml(&toml_path).unwrap_or_else(|e| bad_config(&toml_path, e)), path)
2022 } else {
2023 (TomlConfig::default(), None)
2024 }
2025}
2026
2027fn postprocess_toml(
2028 toml: &mut TomlConfig,
2029 src_dir: &Path,
2030 toml_path: Option<PathBuf>,
2031 exec_ctx: &ExecutionContext,
2032 override_set: &[String],
2033 get_toml: &impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
2034) {
2035 let git_info = GitInfo::new(false, src_dir, exec_ctx);
2036
2037 if git_info.is_from_tarball() && toml.profile.is_none() {
2038 toml.profile = Some("dist".into());
2039 }
2040
2041 for include_path in toml.include.clone().unwrap_or_default().iter().rev() {
2047 let include_path = toml_path
2048 .as_ref()
2049 .expect("include found in default TOML config")
2050 .parent()
2051 .unwrap()
2052 .join(include_path);
2053
2054 let included_toml =
2055 get_toml(&include_path).unwrap_or_else(|e| bad_config(&include_path, e));
2056 toml.merge(
2057 Some(include_path),
2058 &mut Default::default(),
2059 included_toml,
2060 ReplaceOpt::IgnoreDuplicate,
2061 );
2062 }
2063
2064 if let Some(include) = &toml.profile {
2065 let profile_aliases = HashMap::from([("user", "dist")]);
2069 let include = match profile_aliases.get(include.as_str()) {
2070 Some(alias) => alias,
2071 None => include.as_str(),
2072 };
2073 let mut include_path = PathBuf::from(src_dir);
2074 include_path.push("src");
2075 include_path.push("bootstrap");
2076 include_path.push("defaults");
2077 include_path.push(format!("bootstrap.{include}.toml"));
2078 let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
2079 eprintln!(
2080 "ERROR: Failed to parse default config profile at '{}': {e}",
2081 include_path.display()
2082 );
2083 exit!(2);
2084 });
2085 toml.merge(
2086 Some(include_path),
2087 &mut Default::default(),
2088 included_toml,
2089 ReplaceOpt::IgnoreDuplicate,
2090 );
2091 }
2092
2093 let mut override_toml = TomlConfig::default();
2094 for option in override_set.iter() {
2095 fn get_table(option: &str) -> Result<TomlConfig, toml::de::Error> {
2096 toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table))
2097 }
2098
2099 let mut err = match get_table(option) {
2100 Ok(v) => {
2101 override_toml.merge(None, &mut Default::default(), v, ReplaceOpt::ErrorOnDuplicate);
2102 continue;
2103 }
2104 Err(e) => e,
2105 };
2106 if let Some((key, value)) = option.split_once('=')
2109 && !value.contains('"')
2110 {
2111 match get_table(&format!(r#"{key}="{value}""#)) {
2112 Ok(v) => {
2113 override_toml.merge(
2114 None,
2115 &mut Default::default(),
2116 v,
2117 ReplaceOpt::ErrorOnDuplicate,
2118 );
2119 continue;
2120 }
2121 Err(e) => err = e,
2122 }
2123 }
2124 eprintln!("failed to parse override `{option}`: `{err}");
2125 exit!(2)
2126 }
2127 toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override);
2128}
2129
2130#[cfg(test)]
2131pub fn check_stage0_version(
2132 _program_path: &Path,
2133 _component_name: &'static str,
2134 _src_dir: &Path,
2135 _exec_ctx: &ExecutionContext,
2136) {
2137}
2138
2139#[cfg(not(test))]
2141pub fn check_stage0_version(
2142 program_path: &Path,
2143 component_name: &'static str,
2144 src_dir: &Path,
2145 exec_ctx: &ExecutionContext,
2146) {
2147 use build_helper::util::fail;
2148
2149 if exec_ctx.dry_run() {
2150 return;
2151 }
2152
2153 let stage0_output =
2154 command(program_path).arg("--version").run_capture_stdout(exec_ctx).stdout();
2155 let mut stage0_output = stage0_output.lines().next().unwrap().split(' ');
2156
2157 let stage0_name = stage0_output.next().unwrap();
2158 if stage0_name != component_name {
2159 fail(&format!(
2160 "Expected to find {component_name} at {} but it claims to be {stage0_name}",
2161 program_path.display()
2162 ));
2163 }
2164
2165 let stage0_version =
2166 semver::Version::parse(stage0_output.next().unwrap().split('-').next().unwrap().trim())
2167 .unwrap();
2168 let source_version =
2169 semver::Version::parse(fs::read_to_string(src_dir.join("src/version")).unwrap().trim())
2170 .unwrap();
2171 if !(source_version == stage0_version
2172 || (source_version.major == stage0_version.major
2173 && (source_version.minor == stage0_version.minor
2174 || source_version.minor == stage0_version.minor + 1)))
2175 {
2176 let prev_version = format!("{}.{}.x", source_version.major, source_version.minor - 1);
2177 fail(&format!(
2178 "Unexpected {component_name} version: {stage0_version}, we should use {prev_version}/{source_version} to build source with {source_version}"
2179 ));
2180 }
2181}
2182
2183pub fn download_ci_rustc_commit<'a>(
2184 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2185 rust_info: &channel::GitInfo,
2186 download_rustc: Option<StringOrBool>,
2187 llvm_assertions: bool,
2188) -> Option<String> {
2189 let dwn_ctx = dwn_ctx.as_ref();
2190
2191 if !is_download_ci_available(&dwn_ctx.host_target.triple, llvm_assertions) {
2192 return None;
2193 }
2194
2195 let if_unchanged = match download_rustc {
2197 None | Some(StringOrBool::Bool(false)) => return None,
2203 Some(StringOrBool::Bool(true)) => false,
2204 Some(StringOrBool::String(s)) if s == "if-unchanged" => {
2205 if !rust_info.is_managed_git_subrepository() {
2206 println!(
2207 "ERROR: `download-rustc=if-unchanged` is only compatible with Git managed sources."
2208 );
2209 crate::exit!(1);
2210 }
2211
2212 true
2213 }
2214 Some(StringOrBool::String(other)) => {
2215 panic!("unrecognized option for download-rustc: {other}")
2216 }
2217 };
2218
2219 let commit = if rust_info.is_managed_git_subrepository() {
2220 let freshness = check_path_modifications_(dwn_ctx, RUSTC_IF_UNCHANGED_ALLOWED_PATHS);
2223 dwn_ctx.exec_ctx.do_if_verbose(|| {
2224 eprintln!("rustc freshness: {freshness:?}");
2225 });
2226 match freshness {
2227 PathFreshness::LastModifiedUpstream { upstream } => upstream,
2228 PathFreshness::HasLocalModifications { upstream } => {
2229 if if_unchanged {
2230 return None;
2231 }
2232
2233 if dwn_ctx.is_running_on_ci() {
2234 eprintln!("CI rustc commit matches with HEAD and we are in CI.");
2235 eprintln!(
2236 "`rustc.download-ci` functionality will be skipped as artifacts are not available."
2237 );
2238 return None;
2239 }
2240
2241 upstream
2242 }
2243 PathFreshness::MissingUpstream => {
2244 eprintln!("No upstream commit found");
2245 return None;
2246 }
2247 }
2248 } else {
2249 channel::read_commit_info_file(dwn_ctx.src)
2250 .map(|info| info.sha.trim().to_owned())
2251 .expect("git-commit-info is missing in the project root")
2252 };
2253
2254 Some(commit)
2255}
2256
2257pub fn check_path_modifications_<'a>(
2258 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2259 paths: &[&'static str],
2260) -> PathFreshness {
2261 let dwn_ctx = dwn_ctx.as_ref();
2262 dwn_ctx
2268 .path_modification_cache
2269 .lock()
2270 .unwrap()
2271 .entry(paths.to_vec())
2272 .or_insert_with(|| {
2273 check_path_modifications(
2274 dwn_ctx.src,
2275 &git_config(dwn_ctx.stage0_metadata),
2276 paths,
2277 dwn_ctx.ci_env,
2278 )
2279 .unwrap()
2280 })
2281 .clone()
2282}
2283
2284pub fn git_config(stage0_metadata: &build_helper::stage0_parser::Stage0) -> GitConfig<'_> {
2285 GitConfig {
2286 nightly_branch: &stage0_metadata.config.nightly_branch,
2287 git_merge_commit_email: &stage0_metadata.config.git_merge_commit_email,
2288 }
2289}
2290
2291pub fn parse_download_ci_llvm<'a>(
2292 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2293 rust_info: &channel::GitInfo,
2294 download_rustc_commit: &Option<String>,
2295 download_ci_llvm: Option<StringOrBool>,
2296 asserts: bool,
2297) -> bool {
2298 let dwn_ctx = dwn_ctx.as_ref();
2299 let download_ci_llvm = download_ci_llvm.unwrap_or(StringOrBool::Bool(true));
2300
2301 let if_unchanged = || {
2302 if rust_info.is_from_tarball() {
2303 println!("ERROR: 'if-unchanged' is only compatible with Git managed sources.");
2305 crate::exit!(1);
2306 }
2307
2308 #[cfg(not(test))]
2310 update_submodule(dwn_ctx, rust_info, "src/llvm-project");
2311
2312 let has_changes = has_changes_from_upstream(dwn_ctx, LLVM_INVALIDATION_PATHS);
2314
2315 if has_changes {
2317 false
2318 } else {
2319 llvm::is_ci_llvm_available_for_target(&dwn_ctx.host_target, asserts)
2320 }
2321 };
2322
2323 match download_ci_llvm {
2324 StringOrBool::Bool(b) => {
2325 if !b && download_rustc_commit.is_some() {
2326 panic!(
2327 "`llvm.download-ci-llvm` cannot be set to `false` if `rust.download-rustc` is set to `true` or `if-unchanged`."
2328 );
2329 }
2330
2331 #[cfg(not(test))]
2332 if b && dwn_ctx.is_running_on_ci() && CiEnv::is_rust_lang_managed_ci_job() {
2333 panic!(
2335 "`llvm.download-ci-llvm` cannot be set to `true` on CI. Use `if-unchanged` instead."
2336 );
2337 }
2338
2339 b && llvm::is_ci_llvm_available_for_target(&dwn_ctx.host_target, asserts)
2341 }
2342 StringOrBool::String(s) if s == "if-unchanged" => if_unchanged(),
2343 StringOrBool::String(other) => {
2344 panic!("unrecognized option for download-ci-llvm: {other:?}")
2345 }
2346 }
2347}
2348
2349pub fn has_changes_from_upstream<'a>(
2350 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2351 paths: &[&'static str],
2352) -> bool {
2353 let dwn_ctx = dwn_ctx.as_ref();
2354 match check_path_modifications_(dwn_ctx, paths) {
2355 PathFreshness::LastModifiedUpstream { .. } => false,
2356 PathFreshness::HasLocalModifications { .. } | PathFreshness::MissingUpstream => true,
2357 }
2358}
2359
2360#[cfg_attr(
2361 feature = "tracing",
2362 instrument(
2363 level = "trace",
2364 name = "Config::update_submodule",
2365 skip_all,
2366 fields(relative_path = ?relative_path),
2367 ),
2368)]
2369pub(crate) fn update_submodule<'a>(
2370 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2371 rust_info: &channel::GitInfo,
2372 relative_path: &str,
2373) {
2374 let dwn_ctx = dwn_ctx.as_ref();
2375 if rust_info.is_from_tarball() || !submodules_(dwn_ctx.submodules, rust_info) {
2376 return;
2377 }
2378
2379 let absolute_path = dwn_ctx.src.join(relative_path);
2380
2381 if !absolute_path.exists() {
2385 t!(fs::create_dir_all(&absolute_path));
2386 }
2387
2388 if !git_info(dwn_ctx.exec_ctx, false, &absolute_path).is_managed_git_subrepository()
2391 && !helpers::dir_is_empty(&absolute_path)
2392 {
2393 return;
2394 }
2395
2396 let submodule_git = || {
2403 let mut cmd = helpers::git(Some(&absolute_path));
2404 cmd.run_in_dry_run();
2405 cmd
2406 };
2407
2408 let checked_out_hash =
2410 submodule_git().args(["rev-parse", "HEAD"]).run_capture_stdout(dwn_ctx.exec_ctx).stdout();
2411 let checked_out_hash = checked_out_hash.trim_end();
2412 let recorded = helpers::git(Some(dwn_ctx.src))
2414 .run_in_dry_run()
2415 .args(["ls-tree", "HEAD"])
2416 .arg(relative_path)
2417 .run_capture_stdout(dwn_ctx.exec_ctx)
2418 .stdout();
2419
2420 let actual_hash = recorded
2421 .split_whitespace()
2422 .nth(2)
2423 .unwrap_or_else(|| panic!("unexpected output `{recorded}`"));
2424
2425 if actual_hash == checked_out_hash {
2426 return;
2428 }
2429
2430 println!("Updating submodule {relative_path}");
2431
2432 helpers::git(Some(dwn_ctx.src))
2433 .allow_failure()
2434 .run_in_dry_run()
2435 .args(["submodule", "-q", "sync"])
2436 .arg(relative_path)
2437 .run(dwn_ctx.exec_ctx);
2438
2439 let update = |progress: bool| {
2441 let current_branch = helpers::git(Some(dwn_ctx.src))
2444 .allow_failure()
2445 .run_in_dry_run()
2446 .args(["symbolic-ref", "--short", "HEAD"])
2447 .run_capture(dwn_ctx.exec_ctx);
2448
2449 let mut git = helpers::git(Some(dwn_ctx.src)).allow_failure();
2450 git.run_in_dry_run();
2451 if current_branch.is_success() {
2452 let branch = current_branch.stdout();
2455 let branch = branch.trim();
2456 let branch = branch.strip_prefix("heads/").unwrap_or(branch);
2457 git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
2458 }
2459 git.args(["submodule", "update", "--init", "--recursive", "--depth=1"]);
2460 if progress {
2461 git.arg("--progress");
2462 }
2463 git.arg(relative_path);
2464 git
2465 };
2466 if !update(true).allow_failure().run(dwn_ctx.exec_ctx) {
2467 update(false).allow_failure().run(dwn_ctx.exec_ctx);
2468 }
2469
2470 let has_local_modifications = !submodule_git()
2473 .allow_failure()
2474 .args(["diff-index", "--quiet", "HEAD"])
2475 .run(dwn_ctx.exec_ctx);
2476 if has_local_modifications {
2477 submodule_git().allow_failure().args(["stash", "push"]).run(dwn_ctx.exec_ctx);
2478 }
2479
2480 submodule_git().allow_failure().args(["reset", "-q", "--hard"]).run(dwn_ctx.exec_ctx);
2481 submodule_git().allow_failure().args(["clean", "-qdfx"]).run(dwn_ctx.exec_ctx);
2482
2483 if has_local_modifications {
2484 submodule_git().allow_failure().args(["stash", "pop"]).run(dwn_ctx.exec_ctx);
2485 }
2486}
2487
2488pub fn git_info(exec_ctx: &ExecutionContext, omit_git_hash: bool, dir: &Path) -> GitInfo {
2489 GitInfo::new(omit_git_hash, dir, exec_ctx)
2490}
2491
2492pub fn submodules_(submodules: &Option<bool>, rust_info: &channel::GitInfo) -> bool {
2493 submodules.unwrap_or(rust_info.is_managed_git_subrepository())
2496}
2497
2498pub fn is_system_llvm(
2503 target_config: &HashMap<TargetSelection, Target>,
2504 llvm_from_ci: bool,
2505 host_target: TargetSelection,
2506 target: TargetSelection,
2507) -> bool {
2508 match target_config.get(&target) {
2509 Some(Target { llvm_config: Some(_), .. }) => {
2510 let ci_llvm = llvm_from_ci && is_host_target(&host_target, &target);
2511 !ci_llvm
2512 }
2513 Some(Target { llvm_config: None, .. }) => false,
2515 None => false,
2516 }
2517}
2518
2519pub fn is_host_target(host_target: &TargetSelection, target: &TargetSelection) -> bool {
2520 host_target == target
2521}
2522
2523pub(crate) fn ci_llvm_root<'a>(
2524 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2525 llvm_from_ci: bool,
2526 out: &Path,
2527) -> PathBuf {
2528 let dwn_ctx = dwn_ctx.as_ref();
2529 assert!(llvm_from_ci);
2530 out.join(dwn_ctx.host_target).join("ci-llvm")
2531}
2532
2533pub(crate) fn read_file_by_commit<'a>(
2535 dwn_ctx: impl AsRef<DownloadContext<'a>>,
2536 rust_info: &channel::GitInfo,
2537 file: &Path,
2538 commit: &str,
2539) -> String {
2540 let dwn_ctx = dwn_ctx.as_ref();
2541 assert!(
2542 rust_info.is_managed_git_subrepository(),
2543 "`Config::read_file_by_commit` is not supported in non-git sources."
2544 );
2545
2546 let mut git = helpers::git(Some(dwn_ctx.src));
2547 git.arg("show").arg(format!("{commit}:{}", file.to_str().unwrap()));
2548 git.run_capture_stdout(dwn_ctx.exec_ctx).stdout()
2549}
2550
2551fn bad_config(toml_path: &Path, e: toml::de::Error) -> ! {
2552 eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display());
2553 let e_s = e.to_string();
2554 if e_s.contains("unknown field")
2555 && let Some(field_name) = e_s.split("`").nth(1)
2556 && let sections = find_correct_section_for_field(field_name)
2557 && !sections.is_empty()
2558 {
2559 if sections.len() == 1 {
2560 match sections[0] {
2561 WouldBeValidFor::TopLevel { is_section } => {
2562 if is_section {
2563 eprintln!(
2564 "hint: section name `{field_name}` used as a key within a section"
2565 );
2566 } else {
2567 eprintln!("hint: try using `{field_name}` as a top level key");
2568 }
2569 }
2570 WouldBeValidFor::Section(section) => {
2571 eprintln!("hint: try moving `{field_name}` to the `{section}` section")
2572 }
2573 }
2574 } else {
2575 eprintln!(
2576 "hint: `{field_name}` would be valid {}",
2577 join_oxford_comma(sections.iter(), "or"),
2578 );
2579 }
2580 }
2581
2582 exit!(2);
2583}
2584
2585#[derive(Copy, Clone, Debug)]
2586enum WouldBeValidFor {
2587 TopLevel { is_section: bool },
2588 Section(&'static str),
2589}
2590
2591fn join_oxford_comma(
2592 mut parts: impl ExactSizeIterator<Item = impl std::fmt::Display>,
2593 conj: &str,
2594) -> String {
2595 use std::fmt::Write;
2596 let mut out = String::new();
2597
2598 assert!(parts.len() > 1);
2599 while let Some(part) = parts.next() {
2600 if parts.len() == 0 {
2601 write!(&mut out, "{conj} {part}")
2602 } else {
2603 write!(&mut out, "{part}, ")
2604 }
2605 .unwrap();
2606 }
2607 out
2608}
2609
2610impl std::fmt::Display for WouldBeValidFor {
2611 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2612 match self {
2613 Self::TopLevel { .. } => write!(f, "at top level"),
2614 Self::Section(section_name) => write!(f, "in section `{section_name}`"),
2615 }
2616 }
2617}
2618
2619fn find_correct_section_for_field(field_name: &str) -> Vec<WouldBeValidFor> {
2620 let sections = ["build", "install", "llvm", "gcc", "rust", "dist"];
2621 sections
2622 .iter()
2623 .map(Some)
2624 .chain([None])
2625 .filter_map(|section_name| {
2626 let dummy_config_str = if let Some(section_name) = section_name {
2627 format!("{section_name}.{field_name} = 0\n")
2628 } else {
2629 format!("{field_name} = 0\n")
2630 };
2631 let is_unknown_field = toml::from_str::<toml::Value>(&dummy_config_str)
2632 .and_then(TomlConfig::deserialize)
2633 .err()
2634 .is_some_and(|e| e.to_string().contains("unknown field"));
2635 if is_unknown_field {
2636 None
2637 } else {
2638 Some(section_name.copied().map(WouldBeValidFor::Section).unwrap_or_else(|| {
2639 WouldBeValidFor::TopLevel { is_section: sections.contains(&field_name) }
2640 }))
2641 }
2642 })
2643 .collect()
2644}