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